branch_name
stringclasses
15 values
target
stringlengths
26
10.3M
directory_id
stringlengths
40
40
languages
sequencelengths
1
9
num_files
int64
1
1.47k
repo_language
stringclasses
34 values
repo_name
stringlengths
6
91
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
input
stringclasses
1 value
refs/heads/master
<file_sep><?php $host = 'localhost'; $username = 'Brandini'; $password = '<PASSWORD>++'; $dbname = 'world'; $dsn = "mysql:host=$host;dbname=$dbname;charset=utf8mb4"; $pdo = new PDO($dsn,$username,$password); $countryName = $_GET['countryName']; $stmt = $pdo->query("SELECT * FROM countries WHERE name LIKE '%$countryName%'"); $results = $stmt->fetchAll(PDO::FETCH_ASSOC); exit(json_encode($results)); ?>
d27148da0421f8354ea8e65779b9fc2ae91b7946
[ "PHP" ]
1
PHP
BeaTea109/info2180-lab7
f5e8cc3b15977e9b748025b6b25a56c48157f455
d1e3d8c8335569c7327c1ab136e7c368b0d19229
refs/heads/master
<repo_name>elvis460/git_test<file_sep>/app/controllers/session_controller.rb class SessionController < ApplicationController def create end def destroy end end
23b5806dd74e778e76f4ecb7808fb9f2ef163217
[ "Ruby" ]
1
Ruby
elvis460/git_test
b0db3da1bba086d9b3fc7e5f69355e303bf31b04
9bc459d28f27c1321256bad70549c01e1d9fb594
refs/heads/master
<file_sep>def saluda puts "hola hola hola" end saluda()
8837a2ea6a79d4acb561ce18e5aa95753b7f847a
[ "Ruby" ]
1
Ruby
FMardo77/mi_codigo
804cafc2e8b8c4605a08b2792116a1ff167d93e7
5f70c99115526f28c800198984a7019280477f2d
refs/heads/master
<repo_name>hanefimercan/PythonUsefulCodes<file_sep>/getSizeOfAnObject.py from cPickle import dumps from sys import getsizeof def getSizeOfObject(obj): # size of an object in bytes objectAsString = dumps(obj) return getsizeof(objectAsString) # Test a = {'Mercan': [1,2,3,4,5], 1024: None, 'test': {'test2': None}} print(str(getSizeOfObject(a)) + " bytes") <file_sep>/README.md # PythonUsefulCodes Some useful python codes
7c8c812ca51641ad8290c116d26bd3d587acd355
[ "Markdown", "Python" ]
2
Python
hanefimercan/PythonUsefulCodes
f84c0aea3670365d34d36f1dd1691eb51a18db90
cd145db8e75c4ecf3dbc8acb5a774fae89172e99
refs/heads/master
<repo_name>zjw/dkim_verifier<file_sep>/modules/libunbound.jsm /* * libunbound.jsm * * Wrapper for the libunbound DNS library. * Currently only the TXT resource record is completely supported. * * Version: 1.0.0 (21 November 2013) * * Copyright (c) 2013 <NAME> * * This software is licensed under the terms of the MIT License. * * The above copyright and license notice shall be * included in all copies or substantial portions of the Software. */ // options for JSHint /* jshint strict:true, moz:true */ /* jshint unused:true */ // allow unused parameters that are followed by a used parameter. /* global Components, ctypes, OS, Services */ /* global ModuleGetter, Logging */ /* exported EXPORTED_SYMBOLS, libunbound */ var EXPORTED_SYMBOLS = [ "libunbound" ]; const Cc = Components.classes; const Ci = Components.interfaces; const Cu = Components.utils; Cu.import("resource://gre/modules/ctypes.jsm"); Cu.import("resource://gre/modules/Services.jsm"); Cu.import("resource://dkim_verifier/ModuleGetter.jsm"); ModuleGetter.getosfile(this); Cu.import("resource://dkim_verifier/logging.jsm"); const PREF_BRANCH = "extensions.dkim_verifier.dns."; /** * @public */ var Constants = { RR_TYPE_A: 1, RR_TYPE_A6: 38, RR_TYPE_AAAA: 28, RR_TYPE_AFSDB: 18, RR_TYPE_ANY: 255, RR_TYPE_APL: 42, RR_TYPE_ATMA: 34, RR_TYPE_AXFR: 252, RR_TYPE_CERT: 37, RR_TYPE_CNAME: 5, RR_TYPE_DHCID: 49, RR_TYPE_DLV: 32769, RR_TYPE_DNAME: 39, RR_TYPE_DNSKEY: 48, RR_TYPE_DS: 43, RR_TYPE_EID: 31, RR_TYPE_GID: 102, RR_TYPE_GPOS: 27, RR_TYPE_HINFO: 13, RR_TYPE_IPSECKEY: 45, RR_TYPE_ISDN: 20, RR_TYPE_IXFR: 251, RR_TYPE_KEY: 25, RR_TYPE_KX: 36, RR_TYPE_LOC: 29, RR_TYPE_MAILA: 254, RR_TYPE_MAILB: 253, RR_TYPE_MB: 7, RR_TYPE_MD: 3, RR_TYPE_MF: 4, RR_TYPE_MG: 8, RR_TYPE_MINFO: 14, RR_TYPE_MR: 9, RR_TYPE_MX: 15, RR_TYPE_NAPTR: 35, RR_TYPE_NIMLOC: 32, RR_TYPE_NS: 2, RR_TYPE_NSAP: 22, RR_TYPE_NSAP_PTR: 23, RR_TYPE_NSEC: 47, RR_TYPE_NSEC3: 50, RR_TYPE_NSEC3PARAMS: 51, RR_TYPE_NULL: 10, RR_TYPE_NXT: 30, RR_TYPE_OPT: 41, RR_TYPE_PTR: 12, RR_TYPE_PX: 26, RR_TYPE_RP: 17, RR_TYPE_RRSIG: 46, RR_TYPE_RT: 21, RR_TYPE_SIG: 24, RR_TYPE_SINK: 40, RR_TYPE_SOA: 6, RR_TYPE_SRV: 33, RR_TYPE_SSHFP: 44, RR_TYPE_TSIG: 250, RR_TYPE_TXT: 16, RR_TYPE_UID: 101, RR_TYPE_UINFO: 100, RR_TYPE_UNSPEC: 103, RR_TYPE_WKS: 11, RR_TYPE_X25: 19, }; var prefs = Services.prefs.getBranch(PREF_BRANCH); var log = Logging.getLogger("libunbound"); var lib; var ctx = ctypes.voidptr_t(); // http://unbound.net/documentation/libunbound.html var ub_ctx; var ub_result; var ub_ctx_create; var ub_ctx_delete; var ub_ctx_config; var ub_ctx_set_fwd; var ub_ctx_resolvconf; var ub_ctx_add_ta; var ub_ctx_debuglevel; var ub_resolve; var ub_resolve_free; var ub_strerror; let libunbound = { /** * The result of the query. * Does differ from the original ub_result a bit. * * @typedef {Object} ub_result * @property {String} qname * text string, original question * @property {Number} qtype * type code asked for * @property {Number} qclass * class code (CLASS IN (internet)) * @property {Object[]} data * Array of converted rdata items. Empty for unsupported RR types. * Currently supported types: TXT * @property {Number[][]} data_raw * Array of rdata items as byte array * @property {String} canonname * canonical name of result * @property {Number} rcode * additional error code in case of no data * @property {Boolean} havedata * true if there is data * @property {Boolean} nxdomain * true if nodata because name does not exist * @property {Boolean} secure * true if result is secure. * @property {Boolean} bogus * true if a security failure happened. * @property {String} why_bogus * string with error if bogus * @property {Number} ttl * number of seconds the result is valid */ /** * Perform resolution of the target name. * * @param {String} name * @param {Number} [rrtype=libunbound.Constants.RR_TYPE_A] * * @return {ub_result} */ resolve: function libunbound_resolve(name, rrtype=Constants.RR_TYPE_A) { "use strict"; let _result = ub_result.ptr(); let retval; // query for name retval = ub_resolve(ctx, name, rrtype, 1 /* CLASS IN (internet) */, _result.address() ); if (retval !== 0) { log.debug("resolve error: "+ub_strerror(retval).readString()+"\n"); return null; } // array of converted rdata let data = []; // array of rdata as byte array let data_raw = []; if(_result.contents.havedata) { // get data let lenPtr = _result.contents.len; let dataPtr=_result.contents.data; while (!dataPtr.contents.isNull()) { // get rdata as byte array let tmp = ctypes.cast(dataPtr.contents, ctypes.uint8_t.array(lenPtr.contents).ptr ).contents; let rdata = new Array(tmp.length); for (let i = 0; i < tmp.length; i++) { rdata[i] = tmp[i]; } data_raw.push(rdata); // convert rdata for known RR types switch (rrtype) { case Constants.RR_TYPE_TXT: // http://tools.ietf.org/html/rfc1035#page-20 let str = ""; let i=0; let j; // read all <character-string>s while (i < rdata.length) { // get length of current <character-string> j = rdata[i]; i += 1; // read current <character-string> str += String.fromCharCode.apply(null, rdata.slice(i, i+j)); i += j; } data.push(str); break; } dataPtr = dataPtr.increment(); lenPtr = lenPtr.increment(); } log.debug("data: "+data); } let result = {}; if (!_result.contents.qname.isNull()) { result.qname = _result.contents.qname.readString(); } result.qtype = _result.contents.qtype; result.qclass = _result.contents.qclass; result.data = data; result.data_raw = data_raw; if (!_result.contents.canonname.isNull()) { result.canonname = _result.contents.canonname.readString(); } result.rcode = _result.contents.rcode; result.havedata = _result.contents.havedata === 1; result.nxdomain = _result.contents.nxdomain === 1; result.secure = _result.contents.secure === 1; result.bogus = _result.contents.bogus === 1; if (!_result.contents.why_bogus.isNull()) { result.why_bogus = _result.contents.why_bogus.readString(); } result.ttl = _result.contents.ttl; log.debug("qname: "+result.qname+", qtype: "+result.qtype+", rcode: "+result.rcode+", secure: "+result.secure+", bogus: "+result.bogus+", why_bogus: "+result.why_bogus); ub_resolve_free(_result); return result; }, }; /** * init */ function init() { "use strict"; let path; if (prefs.getBoolPref("libunbound.path.relToProfileDir")) { path = OS.Path.join(OS.Constants.Path.profileDir, prefs.getCharPref("libunbound.path")); } else { path = prefs.getCharPref("libunbound.path"); } lib = ctypes.open(path); ub_ctx = new ctypes.StructType("ub_ctx"); // struct ub_result { // char* qname; /* text string, original question */ // int qtype; /* type code asked for */ // int qclass; /* class code asked for */ // char** data; /* array of rdata items, NULL terminated*/ // int* len; /* array with lengths of rdata items */ // char* canonname; /* canonical name of result */ // int rcode; /* additional error code in case of no data */ // void* answer_packet; /* full network format answer packet */ // int answer_len; /* length of packet in octets */ // int havedata; /* true if there is data */ // int nxdomain; /* true if nodata because name does not exist */ // int secure; /* true if result is secure */ // int bogus; /* true if a security failure happened */ // char* why_bogus; /* string with error if bogus */ // int ttl; /* number of seconds the result is valid */ // }; ub_result = new ctypes.StructType("ub_result", [ { "qname": ctypes.char.ptr }, { "qtype": ctypes.int }, { "qclass": ctypes.int }, { "data": ctypes.char.ptr.ptr }, { "len": ctypes.int.ptr }, { "canonname": ctypes.char.ptr }, { "rcode": ctypes.int }, { "answer_packet": ctypes.voidptr_t }, { "answer_len": ctypes.int }, { "havedata": ctypes.int }, { "nxdomain": ctypes.int }, { "secure": ctypes.int }, { "bogus": ctypes.int }, { "why_bogus": ctypes.char.ptr }, { "ttl": ctypes.int } ]); // struct ub_ctx * ub_ctx_create(void); ub_ctx_create = lib.declare("ub_ctx_create", ctypes.default_abi, ub_ctx.ptr); // void ub_ctx_delete(struct ub_ctx* ctx); ub_ctx_delete = lib.declare("ub_ctx_delete", ctypes.default_abi, ctypes.void_t, ub_ctx.ptr); // int ub_ctx_config(struct ub_ctx* ctx, char* fname); ub_ctx_config = lib.declare("ub_ctx_config", ctypes.default_abi, ctypes.int, ub_ctx.ptr, ctypes.char.ptr); //int ub_ctx_set_fwd(struct ub_ctx* ctx, char* addr); ub_ctx_set_fwd = lib.declare("ub_ctx_set_fwd", ctypes.default_abi, ctypes.int, ub_ctx.ptr, ctypes.char.ptr); // int ub_ctx_resolvconf(struct ub_ctx* ctx, char* fname); ub_ctx_resolvconf = lib.declare("ub_ctx_resolvconf", ctypes.default_abi, ctypes.int, ub_ctx.ptr, ctypes.char.ptr); // int ub_ctx_add_ta(struct ub_ctx* ctx, char* ta); ub_ctx_add_ta = lib.declare("ub_ctx_add_ta", ctypes.default_abi, ctypes.int, ub_ctx.ptr, ctypes.char.ptr); // int ub_ctx_debuglevel(struct ub_ctx* ctx, int d); ub_ctx_debuglevel = lib.declare("ub_ctx_debuglevel", ctypes.default_abi, ctypes.int, ub_ctx.ptr, ctypes.int); // int ub_resolve(struct ub_ctx* ctx, char* name, // int rrtype, int rrclass, struct ub_result** result); ub_resolve = lib.declare("ub_resolve", ctypes.default_abi, ctypes.int, ub_ctx.ptr, ctypes.char.ptr, ctypes.int, ctypes.int, ub_result.ptr.ptr); // void ub_resolve_free(struct ub_result* result); ub_resolve_free = lib.declare("ub_resolve_free", ctypes.default_abi, ctypes.void_t, ub_result.ptr); // const char * ub_strerror(int err); ub_strerror = lib.declare("ub_strerror", ctypes.default_abi, ctypes.char.ptr, ctypes.int); update_ctx(); log.debug("initialized"); } /** * updates ctx by deleting old an creating new */ function update_ctx() { "use strict"; let retval; if (!ctx.isNull()) { // delete old context ub_ctx_delete(ctx); ctx = ctypes.voidptr_t(); } // create context ctx = ub_ctx_create(); if(ctx.isNull()) { log.fatal("error: could not create unbound context\n"); return; } // read config file if specified if (prefs.getPrefType("libunbound.conf") === prefs.PREF_STRING) { if((retval=ub_ctx_config(ctx, prefs.getCharPref("libunbound.conf"))) !== 0) { log.error("error in ub_ctx_config: "+ub_strerror(retval).readString()+ ". errno: "+ctypes.errno+"\n"); } } // set debuglevel if specified if (prefs.getPrefType("libunbound.debuglevel") === prefs.PREF_INT) { if((retval=ub_ctx_debuglevel(ctx, prefs.getIntPref("libunbound.debuglevel"))) !== 0) { log.error("error in ub_ctx_debuglevel: "+ub_strerror(retval).readString()+ ". errno: "+ctypes.errno+"\n"); } } // get DNS servers form OS if (prefs.getBoolPref("getNameserversFromOS")) { if((retval=ub_ctx_resolvconf(ctx, null)) !== 0) { log.error("error in ub_ctx_resolvconf: "+ub_strerror(retval).readString()+ ". errno: "+ctypes.errno+"\n"); } } // set additional DNS servers let nameservers = prefs.getCharPref("nameserver").split(";"); nameservers.forEach(function(element /*, index, array*/) { if (element.trim() !== "") { if((retval=ub_ctx_set_fwd(ctx, element.trim())) !== 0) { log.error("error in ub_ctx_set_fwd: "+ub_strerror(retval).readString()+ ". errno: "+ctypes.errno+"\n"); } } }); // add root trust anchor if((retval=ub_ctx_add_ta(ctx, prefs.getCharPref("dnssec.trustAnchor"))) !== 0) { log.error("error in ub_ctx_add_ta: "+ub_strerror(retval).readString()+ ". errno: "+ctypes.errno+"\n"); } } libunbound.Constants = Constants; init(); <file_sep>/chrome/content/options.js function onLoad(paneID) { var fadeInEffect = Application.prefs.get('browser.preferences.animateFadeIn'); if (!fadeInEffect.value) { window.sizeToContent(); } else { var currentPane = document.getElementById(paneID); var changeWidthBy = currentPane._content.scrollWidth - currentPane._content.clientWidth; window.resizeBy(changeWidthBy, 0); } } var gDKIMonpaneload = this.onLoad;
77b46711aecd3d204c6f1866f2f0427ff65facf2
[ "JavaScript" ]
2
JavaScript
zjw/dkim_verifier
7dd453545fc46caa751579e42ed1aae49b3c7ccb
cb48ceba5325c3176fcc8bd412af476b7e3a58cd
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; namespace ConsoleApplication { public class Startup { public void Configure(IApplicationBuilder app) { // app.UseDefaultFiles(); app.UseStaticFiles(); app.Use(async (context, next) => { context.Response.ContentType="text/html"; await next(); }); // next steps solution app.Map("/quote", builder => builder.Run(async context => { var id = int.Parse(context.Request.Path.ToString().Split('/')[1]); var quote = QuotationStore.Quotations[id]; await context.Response.WriteAsync(quote.ToString()); })); app.Map("/all", builder => builder.Run(async context => { foreach(var quote in QuotationStore.Quotations) { await context.Response.WriteAsync("<div>"); await context.Response.WriteAsync(quote.ToString()); await context.Response.WriteAsync("</div>"); } })); app.Run(context => { return context.Response.WriteAsync(QuotationStore.RandomQuotation().ToString()); }); } } }
d8cdfc9f678e300bc01923bcb55fbb4db4ab665a
[ "C#" ]
1
C#
runt18/training-tutorials
de6302c978033a54c7077f8789ff7579fcc2b1dc
033246b8dcdad72d30ce43525372750292202557
refs/heads/master
<file_sep>apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'project-report' sourceCompatibility = 1.7 targetCompatibility = 1.7 version = '1.0' jar { manifest { attributes 'Implementation-Title': 'Gradle Quickstart', 'Implementation-Version': version } } repositories { mavenCentral() } dependencies { compile( ['commons-collections:commons-collections:3.2'], ['org.seleniumhq.selenium:selenium-java:2.53.0'], ['org.apache.logging.log4j:log4j-core:2.1'], ['dom4j:dom4j:1.6.1'], ['org.apache.commons:commons-csv:1.2'], ['commons-net:commons-net:1.4.1'], ['com.google.inject:guice:4.0'], [files('libs/javacsv.jar', 'libs/reportng-1.1.4.jar','libs/velocity-dep-1.4.jar')], ['org.testng:testng:6.9.10'] ) } defaultTasks 'test', 'clean', 'compileJava' test { useTestNG(){ options.suites(file('config/TestNG_configs/TestBaseConfig_4comps.xml')); useDefaultListeners = false } } task copyJars(type:Copy){ from configurations.runtime into 'libs' } compileJava { fileTree(dir: 'libs', include: ['*.jar']) } uploadArchives { repositories { flatDir { dirs 'repos' } } } <file_sep>package com.trane.display.utils; /** * This class is to designed to interpret UI Map xml * * @author irblir * @since 2016-04-22 */ public class Locator { private String selector; public enum ByType { xpath, id, linkText, name, className, cssSelector, partialLinkText, tagName } private ByType byType; public Locator() { } /** * default Locator - id */ public Locator(String selector) { this.selector = selector; this.byType = ByType.id; } public Locator(String selector, ByType byType) { this.selector = selector; this.byType = byType; } public String getSelector() { return selector; } public ByType getBy() { return byType; } public void setBy(ByType byType) { this.byType = byType; } } <file_sep>package com.trane.display.utils; import java.nio.charset.Charset; import java.util.HashMap; import com.csvreader.CsvReader; import com.csvreader.CsvWriter; public class CSVutils { public static HashMap<String, String> readCSV(String localDirAndFileName, Integer pageIndex) throws Exception { Log log = new Log(CSVutils.class); HashMap<String, String> dataMap = new HashMap<String, String>(); dataMap.clear(); CsvReader reader = new CsvReader(localDirAndFileName, ',',Charset.forName("UTF-8")); reader.readHeaders(); while (reader.readRecord()) { String selector = reader.get("id"); String varName = reader.get("varName"); String index = reader.get("pageIndex"); if(reader.get("pageIndex").equalsIgnoreCase(pageIndex+"")) { log.info(index + "," + selector + "," + varName); dataMap.put(selector, varName); } else { continue; } } reader.close(); return dataMap; } /** * create a CSV template * @param filename * @throws Exception */ public static void writeCSV(String filename) throws Exception { String path = System.getProperty("user.dir") + "\\src\\main\\java\\com\\trane\\display\\cases\\data\\" + filename; CsvWriter writer = new CsvWriter(path, ',', Charset.forName("UTF-8")); String[] contents = {"pageIndex","id","varName"}; writer.writeRecord(contents); writer.close(); } } <file_sep>package com.trane.display.cases; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class ExampleTest { public static void main(String[] args) throws Exception { WebDriver driver = new FirefoxDriver(); driver.get("http://1172.16.17.32/FS/root/UI_Medium/index.html"); WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.textToBePresentInElementLocated(By.id("idLbl_pgHomePage_Title"), "Home")); // WebElement e = driver.findElement(By.xpath("//*[text()='Reports']")); WebElement e = driver.findElement(By.id("idBtn_pgMain_navfooterBtnReports")); if (e.isDisplayed()) { System.out.println("getAttribute(): " + e.getAttribute("class")); // navfooter_btn_off System.out.println("getText: " + e.getText()); // Reports System.out.println("getLocation: " + e.getLocation()); // (218, 426) System.out.println("getSize: " + e.getSize()); // (180, 50) e.click(); System.out.println(".................................."); System.out.println("getAttribute(): " + e.getAttribute("class")); // navfooter_btn_on System.out.println("getText: " + e.getText()); // Reports System.out.println("getLocation: " + e.getLocation()); // (218, 426) System.out.println("getSize: " + e.getSize()); // (180, 50) Thread.sleep(3000); WebElement el = driver.findElement(By.xpath("//*[text()='Log Sheet']")); // WebElement el = driver.findElement(By.id("idLbl_pgReportsLanding_r3c3")); el.click(); Thread.sleep(3000); System.out.println("..........................................."); System.out.println(driver.findElement(By.id("idLbl_pgStandardReport_Title")).getText()); System.out.println(driver.findElement(By.id("idLbl_pgStandardReport_SubTitle")).getText()); // Assert.assertEquals(driver.findElement(By.id("idLbl_pgStandardReport_Title")).getText(), "Log Sheet"); // Assert.assertEquals(driver.findElement(By.id("idLbl_pgStandardReport_SubTitle")).getText(), "Evaporator"); driver.close(); } } } <file_sep>package com.trane.display.cases; import com.trane.display.utils.FTPutils; public class Main { public static void main(String[] args) throws Exception { Main test = new Main(); } } <file_sep>package com.trane.display.cases; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import com.trane.display.utils.BaseActions; import com.trane.display.utils.TestNGListener; @Listeners({TestNGListener.class }) public class TestBaseConfig_4comps extends BaseActions { // private String localRequiredDevices = "UC800 - RTAF - Comp4 - BASE - RequiredDevices"; // private String localConfigurationRecord = "UC800 - RTAF - Comp4 - BASE - ConfigurationRecord"; // private String localNameplateRecord = "UC800 - RTAF - Comp4 - BASE - NameplateRecord"; // private String localQuestionRecord = "UC800 - RTAF - Comp4 - BASE - QuestionRecord"; // @BeforeClass // public void configure() throws Exception // { // configFTPfiles(localRequiredDevices, localConfigurationRecord, localNameplateRecord, localQuestionRecord); // openHomePage(); // } @Test(description = "Navigate to Service Settings page") public void a_navigateToServiceSettingsPage() throws Exception { // configFTPfiles("localRequiredDevices", "localConfigurationRecord", "localNameplateRecord", "localQuestionRecord"); openHomePage(); clickVisibleDiv("Settings"); clickVisibleDiv("Chiller Settings"); clickVisibleDiv("Service Settings"); clickVisibleDiv("OK"); verifyText("Title", "Service Settings"); } @Test(description = "Verify Service Settings Data") public void b_verifyServiceSettingsData() throws Exception { verifyAllData("RTAFComp4GlycolServiceSettings"); } // @Test(description = "Navigate to Edit Custom Report page") // public void c_navigateToEditCustomReportPage() throws Exception // { // clickVisibleDiv("Reports"); // clickVisibleDiv("Custom Report 1"); // clickVisibleDiv("Edit"); // verifyText("Title", "Edit Custom Report"); // verifyText("SubTitle", "Custom Report 1"); // } // // @Test(description = "Verify Custom Report Data") // public void d_verifyCustomReportData() throws Exception // { // verifyAllCustomReportData("BaseConfigCustomReport"); // } // @Test(description = "Navigate to Log Sheet page") // public void e_navigateToLogSheetPage() throws Exception // { // clickVisibleDiv("Reports"); // clickVisibleDiv("Log Sheet"); // verifyText("Title", "Log Sheet"); // verifyText("SubTitle", "Evaporator"); // } // // @Test(description = "Verify Log Sheet Data") // public void f_verifyLogSheetData() throws Exception // { // verifyAllData("BaseConfigLogSheet"); // } // @Test(description = "Navigate to Evaporator Circuit 1 page") // public void g_navigateToEvapCkt1Page() throws Exception // { // clickVisibleDiv("Reports"); // clickVisibleDiv("Evaporator"); // clickVisibleDiv("Circuit 1"); // verifyText("Title", "Evaporator"); // verifyText("SubTitle", "Circuit 1"); // } // // @Test(description = "Verify Data") // public void h_verifyEvapCkt1Data() throws Exception // { // verifyAllData("BaseConfigEvap_Ckt1"); // } @AfterClass(description = "Close FireFox") public void tearDown() { closeFirefox(); } } <file_sep>package com.trane.display.utils; /** * This class is designed to update configuration files. * * @author irblir * @since 2016-04-22 */ import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.SocketException; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class FTPutils { private static FTPClient ftpClient = new FTPClient(); private static Log log = new Log(FTPutils.class); public static boolean connectFTP() { boolean result = false; String ip = "192.168.1.3"; String username = "root"; String password = "<PASSWORD>"; try { int reply; ftpClient.connect(ip); ftpClient.login(username, password); reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { log.error("Connect failed"); ftpClient.disconnect(); return result; } result = true; log.info("Connect to the Server successfully"); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } public static boolean uploadFile(String localDirAndFileName, String ftpDirAndFileName) throws Exception { boolean result = false; int separator = ftpDirAndFileName.lastIndexOf("/"); String ftpDir = ftpDirAndFileName.substring(0, separator+1); String ftpfilename = ftpDirAndFileName.substring(separator+1); log.info("uploadFile method: ftpDirectory: " + ftpDir); log.info("uploadFile method: ftpfilename: " + ftpfilename); if(!ftpClient.isConnected()) { log.info("uploadFile method: the connection is lost!"); return false; } boolean changeDir = ftpClient.changeWorkingDirectory(ftpDir); log.info("changeDir: "+changeDir); FileInputStream fis = new FileInputStream(new File(localDirAndFileName)); if (changeDir) { ftpClient.setControlEncoding("utf-8"); ftpClient.setBufferSize(1024); ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); result = ftpClient.storeFile(new String(ftpfilename.getBytes()), fis); if (result) { log.info("upload " + localDirAndFileName +" Successfully to "+ ftpDir + ftpfilename); } else if(!result) { log.error("fail to upload " + localDirAndFileName +" to "+ ftpDir + ftpfilename); } } else if(!changeDir) { log.error("fail to change Directory."); } fis.close(); return result; } public static boolean deleteFile(String ftpDirAndFileName) { boolean result = false; log.info("deleteFile method: ftpDirAndFileName: " + ftpDirAndFileName); if(!ftpClient.isConnected()) { log.info("deleteFile method: the connection is lost!"); return false; } try { result = ftpClient.deleteFile(ftpDirAndFileName); if (result) { log.info("delete " + ftpDirAndFileName + " Successfully"); } else if(!result) { log.info("deleteFile method: do nothing here. Maybe " + ftpDirAndFileName + " doesn't exist."); } } catch (IOException e) { e.printStackTrace(); } return result; } public static void closeFTP() { if (ftpClient != null && ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } log.info("Close Server Successfully!"); } } }<file_sep>#!/usr/bin/python # UC800_reset.py import sys, httplib errCode = 0 httpConn = httplib.HTTPConnection('192.168.1.3', 80) httpConn.request('POST', '/evox/hardware/reset', '<int val="60878720"/>') httpResp = httpConn.getresponse() if (httpResp.status != 200 or httpResp.read().find('<err') >= 0): errCode = 1 httpConn.close() sys.exit(errCode) <file_sep>package com.trane.display.utils; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import org.apache.commons.io.FileUtils; import org.openqa.selenium.By; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; public class BaseActions { public WebDriver driver = new FirefoxDriver(); public HashMap<String, Locator> locatorMap; public Log log = new Log(this.getClass()); public String localDirAndFileName; public HashMap<String, String> dataMap; /** * read xml to inital UI locator map * @throws Exception */ public void InitLocatorMap() throws Exception { localDirAndFileName = System.getProperty("user.dir") + "\\src\\main\\java\\com\\trane\\display\\UIMaps\\" + "UIMap.xml"; log.info(localDirAndFileName); locatorMap = XMLutils.readXMLDocument(localDirAndFileName); } public void VerifyData(String filename, Integer pageIndex) throws Exception { localDirAndFileName = System.getProperty("user.dir") + "\\src\\main\\java\\com\\trane\\display\\cases\\data\\" + filename + ".csv"; dataMap = CSVutils.readCSV(localDirAndFileName, pageIndex); log.info(localDirAndFileName); if(!dataMap.isEmpty()) { Set<String> keys = dataMap.keySet(); Iterator<String> iter = keys.iterator(); while(iter.hasNext()) { String key = (String)iter.next(); String value = (String)dataMap.get(key); if(!ElementExist(By.id(key))) { log.info("This WebElement doesn't exist!" ); Assert.assertEquals("Blank", value); if(value.equalsIgnoreCase("Blank")) { log.info("Pass! "); log.info("Expected value: " + value); } else if(!value.equalsIgnoreCase("Blank")) { log.error("Fail! "); log.info("Expected value: " + value); } } else if (ElementExist(By.id(key))) { WebElement e = driver.findElement(By.id(key)); String actualValue = e.getText(); Assert.assertEquals(actualValue, value); if (actualValue.equalsIgnoreCase(value)) { log.info("Pass! "); log.info("Actual value: " + actualValue); log.info("Expected value: " + value); } else if (!actualValue.equalsIgnoreCase(value)) { log.error("Fail! "); log.info("Actual value: " + actualValue); log.info("Expected value: " + value); } } } } else { log.error("dataMap is empty!!!"); } } public void replaceFTPfile(String localfilename, String ftpDirAndFileName) throws Exception { localDirAndFileName = System.getProperty("user.dir") + "\\src\\main\\java\\com\\trane\\display\\cases\\data\\UC Configs\\" + localfilename + ".xml"; FTPutils.deleteFile(ftpDirAndFileName); FTPutils.uploadFile(localDirAndFileName, ftpDirAndFileName); } public void configFTPfiles(String localRequiredDevices, String localConfigurationRecord, String localNameplateRecord, String localQuestionRecord) throws Exception { FTPutils.connectFTP(); log.info("configure RequiredDevices......"); replaceFTPfile(localRequiredDevices, "/FW_IPC3DeviceBinding/RequiredDevices.xml"); log.info("configure ConfigurationRecord......"); replaceFTPfile(localConfigurationRecord, "/Configuration/ConfigurationRecord.xml"); log.info("configure NameplateRecord......"); replaceFTPfile(localNameplateRecord, "/Configuration/NameplateRecord.xml"); log.info("configure QuestionRecord......"); replaceFTPfile(localQuestionRecord, "/Configuration/QuestionRecord.xml"); FTPutils.closeFTP(); rebootMP(); } public void rebootMP() { String path = System.getProperty("user.dir") + "\\src\\main\\java\\com\\trane\\display\\cases\\data\\" + "UC800_reset.py"; try { log.info("start to reboot MP........."); Process pr = Runtime.getRuntime().exec("python " + path); pr.waitFor(); log.info("wait 90 seconds to wait for reboot successfully......"); Thread.sleep(90000); log.info("reboot MP successfully"); } catch (Exception e) { e.printStackTrace(); } } public WebDriver getDriver() { return driver; } /** * load home page */ public void openHomePage() { driver.get("http://192.168.1.3/FS/root/UI_Medium/index.html"); WebDriverWait wait = new WebDriverWait(driver,20); wait.until(ExpectedConditions.textToBePresentInElementLocated(By.id("idLbl_pgHomePage_Title"), "Home")); log.info("Home Page is loaded successfully"); } public void takeScreenShot() { SimpleDateFormat sf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss"); Calendar cal = Calendar.getInstance(); Date date = cal.getTime(); String dateStr = sf.format(date); String localDirAndFileName = System.getProperty("user.dir") + "\\screenshots\\" + dateStr + ".png"; File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); try { log.info("saved screenshot is:" + localDirAndFileName); FileUtils.copyFile(scrFile, new File(localDirAndFileName)); } catch (Exception e) { log.error("Can't save screenshot"); e.printStackTrace(); } finally { log.info("screen shot finished"); } } /** * * @param locatorName * @return * @throws Exception */ public boolean isElementPresent(String locatorName) throws Exception { Locator locator = getLocator(locatorName); boolean isPresent = false; WebDriverWait wait = new WebDriverWait(driver, 10); isPresent = wait.until(ExpectedConditions.presenceOfElementLocated(getByLocator(locator))).isDisplayed(); return isPresent; } boolean ElementExist(By Locator) { try { driver.findElement(Locator); return true; } catch (org.openqa.selenium.NoSuchElementException ex) { return false; } } /** * * @param locatorName * @return * @throws IOException */ public Locator getLocator(String locatorName) throws IOException { Locator locator = locatorMap.get(locatorName); return locator; } /** * * @param locatorName * @return * @throws Exception */ public WebElement getElement(String locatorName) throws Exception { Locator locator = getLocator(locatorName); By by = getByLocator(locator); WebElement element = driver.findElement(by); return element; } /** * click and find a WebElement by locatorName * @param locatorName * @throws Exception */ public void click(String locatorName) throws Exception { WebElement e = getElement(locatorName); log.info("click "+locatorName); e.click(); Thread.sleep(3000); } /** * * @param locator * @return By * @throws IOException */ public By getByLocator(Locator locator) throws IOException { By by = null; String selector = locator.getSelector(); switch (locator.getBy()) { case xpath: log.debug("find element By xpath:"+selector); by = By.xpath(selector); break; case id: log.debug("find element By id:"+selector); by = By.id(selector); break; case name: log.debug("find element By name:"+selector); by = By.name(selector); break; case cssSelector: log.debug("find element By cssSelector:"+selector); by = By.cssSelector(selector); break; case className: log.debug("find element By className:"+selector); by = By.className(selector); break; case tagName: log.debug("find element By tagName:"+selector); by = By.tagName(selector); break; case linkText: log.debug("find element By linkText:"+selector); by = By.linkText(selector); break; case partialLinkText: log.debug("find element By partialLinkText:"+selector); by = By.partialLinkText(selector); break; } return by; } /** * * @param locatorName * @param num * @throws Exception */ public void verifyText(String locatorName, Integer num) throws Exception { Thread.sleep(3000); Assert.assertEquals(getElement(locatorName).getText(), num+""); } /** * * @param locatorName * @param text * @throws Exception */ public void verifyText(String locatorName, String text) throws Exception { Thread.sleep(3000); Assert.assertEquals(getElement(locatorName).getText(), text); } /** * * @param locatorName * @param attribute * @param content * @throws Exception */ public void verifyAttribute(String locatorName, String attribute, String content) throws Exception { Thread.sleep(3000); Assert.assertEquals(getElement(locatorName).getAttribute(attribute), content); } /** * find and click a WebElemnt by Text * @param WebElemnt's Text */ public void clickVisibleDiv(String text) { driver.findElement(By.xpath("//*[text()='"+text+"']")).click(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } public void closeFirefox() { driver.close(); } } <file_sep>package com.trane.display.cases; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import com.trane.display.pages.HomePage; public class TestPageObjects { public static void main(String[] args) throws Exception { WebDriver driver = new FirefoxDriver(); driver.get("http://192.168.1.3/FS/root/UI_Medium/index.html"); // driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS); WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.textToBePresentInElementLocated(By.id("idLbl_pgHomePage_Title"), "Home")); HomePage homePage = new HomePage(driver); PageFactory.initElements(driver, HomePage.class); System.out.println(homePage); homePage.NavigateToReportsPage().NavigateToLogSheetPage(); driver.quit(); } } <file_sep>package com.trane.display.utils; import java.io.FileInputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.config.ConfigurationSource; import org.apache.logging.log4j.core.config.Configurator; public class Log { private final Class<?> clazz; private static Logger logger; public Log(Class<?> clazz) { this.clazz = clazz; logger = LogManager.getLogger(this.clazz); } // trace < debug < info < warn < error < fatal public void info(String message) { logger.info(clazz.getCanonicalName() + ": " + message); } public void debug(String message) { logger.debug(clazz.getCanonicalName() + ": " + message); } public void error(String message) { logger.error(clazz.getCanonicalName() + ": " + message); } public void trace(String message) { logger.trace(clazz.getCanonicalName() + ": " + message); } public void warn(String message) { logger.warn(clazz.getCanonicalName() + ": " + message); } public void fatal(String message) { logger.fatal(clazz.getCanonicalName() + ": " + message); } public static void initalConfigSrc(){ ConfigurationSource source; try { String config=System.getProperty("user.dir"); source = new ConfigurationSource(new FileInputStream(config+"\\log4j2.xml")); Configurator.initialize(null, source); } catch (Exception e) { e.printStackTrace(); } } } <file_sep>package com.trane.display.cases; import org.testng.annotations.BeforeClass; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import com.trane.display.utils.BaseActions; import com.trane.display.utils.TestNGListener; @Listeners({TestNGListener.class }) public class TestLogSheet extends BaseActions { private String btn_Reports = "btn_Reports"; private String title_Reports = "title_Reports"; private String StandardReport_Title = "StandardReport_Title"; private String StandardReport_SubTitle = "StandardReport_SubTitle"; private String page_num = "page_num"; private String total_page_num = "total_page_num"; private String localRequiredDevices = "UC800 - RTAF - Comp2 - BASE - RequiredDevices"; private String localConfigurationRecord = "UC800 - RTAF - Comp2 - BASE - ConfigurationRecord"; private String localNameplateRecord = "UC800 - RTAF - Comp2 - BASE - NameplateRecord"; private String localQuestionRecord = "UC800 - RTAF - Comp2 - BASE - QuestionRecord"; @BeforeClass public void configure() throws Exception { configFTPfiles(localRequiredDevices, localConfigurationRecord, localNameplateRecord, localQuestionRecord); InitLocatorMap(); openHomePage(); } @Test(description = "Click Reports button on the navigate footer") public void clickReports() throws Exception { verifyAttribute(btn_Reports, "class", "navfooter_btn_off"); clickVisibleDiv("Reports"); } @Test(description = "Verify Reports button pressed in and navigated to Reports page") public void verifyBtnReportsClicked() throws Exception { verifyAttribute(btn_Reports, "class", "navfooter_btn_on"); verifyText(title_Reports, "Reports"); } @Test(description = "Click Log Sheet button on the Reports page") public void clickLogSheet() throws Exception { clickVisibleDiv("Log Sheet"); } @Test(description = "Verify on Log Sheet page 1") public void verifyBtnLogSheetClicked() throws Exception { verifyText(StandardReport_Title, "Log Sheet"); verifyText(StandardReport_SubTitle, "Evaporator"); verifyText(page_num, 1); verifyText(total_page_num, 13); } @Test(description = "Verify Log Sheet Data") public void verifyLogSheetData() throws Exception { VerifyData("BaseConfigLogSheet", 1); click("btn_Down"); VerifyData("BaseConfigLogSheet", 2); } @Test(description = "Close FireFox") public void tearDown() { closeFirefox(); } } <file_sep><?xml version="1.0"?> <project name="medium" default="run" basedir="."> <property name="bin" value="bin"/> <property name="src.dir" value="src/main/java" /> <property name="build.dir" value="build"/> <property name="classes.dir" value="${build.dir}/classes" /> <property name="test-results.dir" value="test-output" /> <path id="run.classpath"> <fileset dir="${basedir}"> <include name="lib/poi/*.jar" /> <include name="lib/poi/lib/*.jar" /> <include name="lib/testng.jar" /> <include name="lib/sikuli-script.jar" /> <include name="lib/*.jar" /> </fileset> <fileset dir="${basedir}/lib/selenium"> <include name="*.jar" /> <include name="libs/*.jar" /> </fileset> </path> <taskdef name="testng" classname="org.testng.TestNGAntTask" classpathref="run.classpath" /> <target name="clean"> <delete dir="${build.dir}"/> </target> <target name="compile" depends="clean"> <mkdir dir="${classes.dir}"/> <javac srcdir="${src.dir}" destdir="${classes.dir}" debug="on" encoding="UTF-8" includeantruntime = "false"> <classpath refid="run.classpath"/> </javac> </target> <path id="runpath"> <path refid="run.classpath"/> <pathelement location="${classes.dir}"/> </path> <target name="run" depends="compile"> <testng classpathref="runpath" outputDir="${test-results.dir}" haltonfailure="true" useDefaultListeners="false" listeners="org.uncommons.reportng.HTMLReporter,org.testng.reporters.FailedReporter" > <xmlfileset dir="${basedir}" includes="TestLogSheet.xml"/> <jvmarg value="-Dfile.encoding=UTF-8" /> <sysproperty key="org.uncommons.reportng.title" value="Automation TestReport" /> </testng> </target> <target name="jar" depends="compile"> <jar basedir="${bin}" destfile="${jar-file-name}"> <zipfileset excludes="META-INF/*.SF" /> </jar> </target> </project>
c227ef77b8f561e974703790501b4ad8a6b31f65
[ "Java", "Python", "Ant Build System", "Gradle" ]
13
Gradle
echoGu/TestUI
2d68a5fe9a68056724e033fbf286f9395553768e
09e0c18b0e9b787425fd6e72665b2bb22586de76
refs/heads/main
<file_sep>#!/bin/bash # #RoboCup 2012 sample start script for 3D soccer simulation # AGENT_BINARY=apollo3d BINARY_DIR="." NUM_PLAYERS=11 export LD_LIBRARY_PATH=./lib #export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:makelibs #killall -9 "$AGENT_BINARY" &> /dev/null for ((i=1;i<=$NUM_PLAYERS;i++)); do case $i in 6 | 9 ) echo "Running agent No. $i -- Type 4" "$BINARY_DIR/$AGENT_BINARY" --host $1 --unum $i --type 4 > /dev/null 2> /dev/null & ;; 3 | 4 ) echo "Running agent No. $i -- Type 1" "$BINARY_DIR/$AGENT_BINARY" --host $1 --unum $i --type 1 > /dev/null 2> /dev/null & ;; #4 | 5) # echo "Running agent No. $i -- Type 2" # "$BINARY_DIR/$AGENT_BINARY" --host $1 --unum $i --type 2 > /dev/null 2> /dev/null & # ;; *) echo "Running agent No. $i -- Type 0" "$BINARY_DIR/$AGENT_BINARY" --host $1 --unum $i --type 0 > /dev/null 2> /dev/null & ;; esac sleep 1 done <file_sep>#!/bin/bash # # sample start script for 3D soccer simulation # AGENT_BINARY="YuShan3D" BINARY_DIR="./" killall -9 "$AGENT_BINARY" &> /dev/null export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:makelib/ echo "Running agent No. 1" "$BINARY_DIR/$AGENT_BINARY" -s $1 -t YuShan3D -u 1 > /dev/null 2> /dev/null& sleep 1.0 <file_sep># # prepare soccer simulation # # setup soccer specific materials #run "scripts/rcs-materials.rb" #run "scripts/rcs-materials-textures.rb" #material = sparkCreate('kerosin/Material2DTexture', $serverPath+'material/matGrass'); #material.setDiffuse(1.0,1.0,1.0,1.0) #material.setAmbient(0.5,0.5,0.5,1.0) #material.setDiffuseTexture('textures/rcs-naofield.png') #importBundle "soccer" # soccer namespace $soccerNameSpace = "Soccer" # register a variable in the soccer namespace def addSoccerVar(name, value) createVariable($soccerNameSpace, name, value) end # helper to get the value of a variable in the soccer namespace def getSoccerVar(name) eval <<-EOS #{$soccerNameSpace}.#{name} EOS end # set a random seed (a seed of 0 means: use a random random seed) randomServer = get($serverPath+'random') if (randomServer != nil) randomServer.seed(0) end # the soccer field dimensions in meters addSoccerVar('FieldLength', 30.0) addSoccerVar('FieldWidth', 20.0) addSoccerVar('FieldHeight', 40.0) addSoccerVar('GoalWidth', 2.1) addSoccerVar('GoalDepth', 0.6) addSoccerVar('GoalHeight', 0.8) addSoccerVar('PenaltyLength',1.8) addSoccerVar('PenaltyWidth',3.9) addSoccerVar('FreeKickDistance', 2.0) addSoccerVar('FreeKickMoveDist', 2.2) # addSoccerVar('GoalKickDist', 1.0) addSoccerVar('AutomaticKickOff', false) addSoccerVar('WaitBeforeKickOff', 30.0) # # agent parameters addSoccerVar('AgentRadius', 0.4) # ball parameters addSoccerVar('BallRadius', 0.042) addSoccerVar('BallMass',0.026) # soccer rule parameters addSoccerVar('RuleGoalPauseTime',3.0) addSoccerVar('RuleKickInPauseTime',1.0) addSoccerVar('RuleHalfTime',5.0 * 60) addSoccerVar('RuleDropBallTime', 15) # addSoccerVar('SingleHalfTime', false) addSoccerVar('UseOffside',false) # recorders addSoccerVar('BallRecorder',"Ball/geometry/recorder") addSoccerVar('LeftGoalRecorder',"leftgoal/GoalBox/BoxCollider/recorder") addSoccerVar('RightGoalRecorder',"rightgoal/GoalBox/BoxCollider/recorder") run "naorobottypes.rb" # textures createVariable('Nao', 'UseTexture', 'true') #scene = get($scenePath) #if (scene != nil) # scene.importScene('rsg/agent/nao/soccer.rsg') #end # setup the GameControlServer #gameControlServer = get($serverPath+'gamecontrol') #if (gameControlServer != nil) # gameControlServer.initControlAspect('GameStateAspect') # gameControlServer.initControlAspect('BallStateAspect') # gameControlServer.initControlAspect('SoccerRuleAspect') #end # init monitorItems to transmit game state information #monitorServer = get($serverPath+'monitor') #if (monitorServer != nil) # monitorServer.registerMonitorItem('GameStateItem') #end # install the TrainerCommandParser to parse commands received from a # monitor client #sparkRegisterMonitorCmdParser 'TrainerCommandParser' <file_sep>#!/bin/bash # # RoboCup 2015 penalty start script for 3D Simulation Competitions # AGENT_BINARY=penalty-keeper export LD_LIBRARY_PATH=./lib #export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:makelibs ./$AGENT_BINARY --host $1 > /dev/null 2> /dev/null & <file_sep>#!/bin/bash # # Robocup 2015 sample kill script for 3D soccer simulation # killall -9 "CIT3D_binary" &> /dev/null <file_sep>#!/bin/bash killall -9 rcssserver3d & killall -9 kylinsky <file_sep>#!/bin/bash # # Robocup 2015 sample start script for 3D soccer simulation # export LD_LIBRARY_PATH==$LD_LIBRARY_PATH:citlib/ AGENT_BINARY="CIT3D_binary" BINARY_DIR="./" $IPAddress if [ -z $1 ] ; then { echo "please set host" IPAddress=127.0.0.1 } else { IPAddress=$1 } fi killall -9 "$AGENT_BINARY" &> /dev/null echo "Running $AGENT_BINARY agent No.2" $BINARY_DIR$AGENT_BINARY --host=$IPAddress --Unum=2 --team="CIT3D" --striker> ./log/kickerstdout222.out 2> ./log/kickerstderr222.err & sleep 2 <file_sep>#!/bin/bash # # sample start script for 3D soccer simulation # AGENT_BINARY="YuShan3D" BINARY_DIR="./" NUM_PLAYERS=11 #killall -9 "$AGENT_BINARY" &> /dev/null export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:makelib/ echo " YuShan3D_2015 3D soccer simulation team " echo "" for ((i=1;i<=$NUM_PLAYERS ;i++)); do echo "Running agent No. $i" "$BINARY_DIR/$AGENT_BINARY" -s 192.168.2.22 -t YuShan3D -u $i > /dev/null 2> /dev/null& sleep 1.0 done <file_sep>#!/bin/bash export LD_LIBRARY_PATH=./lib ./apollo3d_kick --host $1 --port $2 --x $3 --y $4 --challenge $5> /dev/null 2> /dev/null & <file_sep>#!/bin/bash # #WrightOcean kill script for 3D Simulation Competitions # # Kill agents AGENT="WrightOcean" killall -9 $AGENT sleep 1 <file_sep>#!/bin/bash # # Robocup 2015 sample start script for 3D soccer simulation # export LD_LIBRARY_PATH==$LD_LIBRARY_PATH:citlib/ AGENT_BINARY="CIT3D_binary" BINARY_DIR="./" NUM_PLAYERS=11 $IPAddress if [ -z $1 ] ; then { echo "please set host" IPAddress=192.168.1.12 } else { IPAddress=$1 } fi killall -9 "$AGENT_BINARY" &> /dev/null cd "$( cd "$( dirname "$0" )" && pwd )" for ((i=1;i<=$NUM_PLAYERS;i++)); do echo "Running $AGENT_BINARY agent No. $i" "$BINARY_DIR$AGENT_BINARY" --host=$IPAddress --Unum=$i --team='CIT3D' > /dev/null 2> /dev/null & sleep 1 done <file_sep>#!/bin/bash # # china open 2013 sample kill script for YusShan3D soccer simulation # killall -9 "YuShan3D" &> /dev/null <file_sep>#!/bin/bash # # Robocup 2011 sample start script for 3D soccer simulation # export LD_LIBRARY_PATH==$LD_LIBRARY_PATH:./lib AGENT_BINARY="kylinsky" BINARY_DIR="./" NUM_PLAYERS=11 #killall -9 "$AGENT_BINARY" &> /dev/null cd "$( cd "$( dirname "$0" )" && pwd )" for ((i=1;i<=$NUM_PLAYERS;i++)); do echo "Running $AGENT_BINARY agent No. $i" "$BINARY_DIR$AGENT_BINARY" --host=$1 --Unum=$i # > /dev/null 2> /dev/null & sleep 1 done <file_sep># ExecutableCode > 历年可执行文件 我们如今拥有的代码: - 2019国赛代码 - ... 我们希望能让社区变得更大、更强。如果你有任何资源,请拉动合并请求,这很有意义。 谢谢 PS: 如果有任何问题,请让我们知道,我们会很高兴。 <file_sep>#!/bin/bash # # Robocup 2011 sample start script for 3D soccer simulation # export LD_LIBRARY_PATH==$LD_LIBRARY_PATH:./lib AGENT_BINARY="kylinsky" BINARY_DIR="./" NUM_PLAYERS=1 #killall -9 "$AGENT_BINARY" &> /dev/null # for ((i=1;i<=$NUM_PLAYERS;i++)); do echo "Running $AGENT_BINARY agent No. $NUM_PLAYERS" "$BINARY_DIR$AGENT_BINARY" --host=$1 --Unum=$NUM_PLAYERS > /dev/null 2> /dev/null & sleep 1 #done <file_sep># # apollo3d.rb # run 'soccersim-apollo.rb' #run 'naosoccersim.rb' #sparkLogErrorToCerr() time = 0.0 #host = '127.0.0.1' #host = '127.0.0.1' host = '127.0.0.1' port = 3100 DEBUG = 0 VERSUS = 1 WALK = 2 KICK = 3 challenge = VERSUS #if challenge == KICK || challenge == WALK # time = 3.0 #end createVariable('Agent.ThinkingTime', time) createVariable('Agent.Host', host) createVariable('Agent.Port', port) createVariable('Agent.Challenge', challenge) createVariable('Agent.AttackMode', 0) <file_sep>killall -9 apollo3d
bb65f4a97c8d2631905ca75747372ad97d819c0d
[ "Markdown", "Ruby", "Shell" ]
17
Shell
Robocup3DChina/ExecutableCode
c3039f3262b939073a45ad0098024b8c36e2cca3
9ab24252c8e41b60a3de8c8c511bea00e73ced62
refs/heads/main
<file_sep># ICS3U-Assignment-6-CPP-Program [![GitHub's Super Linter](https://github.com/Igor-Zhelezniak-1/ICS3U-Assignment-6-CPP-Program/workflows/GitHub's%20Super%20Linter/badge.svg)](https://github.com/Igor-Zhelezniak-1/ICS3U-Assignment-6-CPP-Program/actions) <file_sep>// Copyright (c) 2021 Igor All rights reserved // // Created by: Igor // Created on: Nov 2021 // This program uses quadratic formula #include <iostream> #include <cmath> double QuadraticFormula(float a, float b, float c, bool add) { // calculates the quadratic formula float x1; float x2; x1 = -b / (2 * a); x2 = sqrt(pow(b, 2) - 4 * a * c) / (2 * a); if (add == true) { return x1 + x2; } else { return x1 - x2; } } main() { // This program uses quadratic formula std::string integer1; std::string integer2; std::string integer3; float a1; float b1; float c1; float d; float answer; float answer1; float answer2; // input std::cout << "Enter a: "; std::cin >> integer1; std::cout << "Enter b: "; std::cin >> integer2; std::cout << "Enter c: "; std::cin >> integer3; std::cout << std::endl; // process try { a1 = std::stof(integer1); b1 = std::stof(integer2); c1 = std::stof(integer3); d = pow(b1, 2) - 4 * a1 * c1; if (d < 0) { std::cout << "There is no answer" << std::endl; } else if (d == 0) { answer = QuadraticFormula(a1, b1, c1, true); std::cout << "If the quadratic equation" << " looks like this:" << std::endl; std::cout << a1 << "x² + " << b1 << "x + " << c1 << std::endl; std::cout << "Discriminant = " << d << std::endl; std::cout << "x = " << answer << std::endl; } else { answer1 = QuadraticFormula(a1, b1, c1, true); answer2 = QuadraticFormula(a1, b1, c1, false); std::cout << "If the quadratic equation" << " looks like this:" << std::endl; std::cout << a1 << "x² + " << b1 << "x + " << c1 << std::endl; std::cout << "Discriminant = " << d << std::endl; std::cout << "x = " << answer1 << " or " << answer2 << std::endl; } } catch (...) { std::cout << "Invalid input" << std::endl; } std::cout << "" << std::endl; std::cout << "Done." << std::endl; }
829c95f4d644612b8a1fc601cbd50b6bca8001e0
[ "Markdown", "C++" ]
2
Markdown
Igor-Zhelezniak-1/ICS3U-Assignment-6-CPP-Program
99f92b134fbf94849d23ec082d2a736f301d510f
968838149a9d2603de81ade35a1f4fd9d25058be
refs/heads/master
<repo_name>Abby-Michigan/cass2017_vis<file_sep>/submissions/KingaAnna_Wozniak/EnergyPlot.R #source("visutils.R") ### create laplacian createLaplacian <- function( layerN ){ ## prepend input N / append output N layerN = cbind(H0 = 2,layerN, Hn = 1) layerN = layerN[ layerN != 0 ] ## remove all zero layers ## init Laplace matirx nn = sum( layerN ) L = matrix( 0, nn, nn ) colIdx = layerN[1]+1 rowIdx = 1 for(i in 1:(length(layerN)-1)){ nI = layerN[i] nJ = layerN[i+1] subL = matrix(1,nI,nJ) * ( -1 / sqrt( nI * nJ ) ) ## create Laplace rank entries L[ rowIdx:(rowIdx+nI-1),colIdx:(colIdx+nJ-1)] <- subL colIdx = colIdx + nJ rowIdx = rowIdx + nI } L = L + t( L ) ## fill lower triangle (symmetric) diag( L ) <- 1 ## set diagonal to 1 return( L ) } sumEigenvals <- function( L ){ ev <- eigen( L ) return( sum(abs(ev$values)) ) } ## compute energy of graph computeEnergy <- function( network ){ L = createLaplacian( network ) return( sumEigenvals( L ) ) } visr.applyParameters() layers <- subset(visr.input, select = param.layers) result <- subset(visr.input, select = param.error) energy <- apply( layers, 1, computeEnergy ) plot(energy, result, main = paste("Energy vs ",names(result)))<file_sep>/submissions/Hamid_Younesy/README.md What did you learn about the relationship between the number and size of the hidden layers? Answer Which of the metaparameters were the most important and why? Answer Were some parameters only important for certain datasets? Which ones? Why? Answer What drove you to explore different parameters combinations in the tensorflow playground? Answer What were the limits of the data set? I.e. are there relationships that are inconclusive where a larger data set might have given you a better understanding? Answer What were the advantages and limits of the interface (VisRseq)? Answer ![Example Plot](images/scatterplot.png)<file_sep>/submissions/Christoph_Langer/tsne.R #COULD NOT GET DEPENDENCIES TO RUN ON MAC OSX 10.10.5 #CODED JSON PER HAND # #source("visrutils.R") # ## #visr.app.start("t-sne", debugdata ="NONE") #visr.param("k", type = "int", default = 2) #visr.param("initial_dims" = "int", default = 30) #visr.param("perplexity" = "int", default = 30) #visr.param("max_iter" = "int", default = 1000) #visr.param("min_cost" = "int", default = 0) #visr.param("epoch" = "int", default = 100) #visr.app.end(printjson=TRUE,writefile=T) visr.applyParameters() ## library("tsne") #X <- visr.input X <-subset(visr.input, select = visr.param.columns) #p <-subset(visr.input, select = "ID") #X = matrix(rexp(200, rate=.1), ncol=20) #ecb = function(x,y){ plot(x,t='n'); text(x) } output = tsne(X, initial_config = NULL, k = 2, initial_dims = 30, perplexity = 30, max_iter = 30, min_cost = 0, epoch_callback = NULL, whiten = TRUE, epoch=100) #output = tsne(X, initial_config = NULL, k = visr.param.k, initial_dims = visr.param.initial_dims, perplexity = visr.param.perplexity, max_iter = visr.param.max_iter, min_cost = visr.param.min_cost, epoch_callback = NULL, whiten = TRUE, epoch=visr.param.epoch) plot(output) #text(output,output, labels = seq(0,49)) text(output,labels = t(seq(0,49))) #text(output,labels = p) <file_sep>/submissions/Christoph_Langer/README.md This is the first simple attempt to wrap the t-sne - algorithm for VisRseq. I could not get all the dependencies to run for "visrutils.R" on MAC OSX 10.10.5, so the json needed to be coded by hand. Since some packages were not available (for R version 3.3.3) -> newest possible version for MAC OSX 10.10.5. The whole thing is unfinished. At the moment it only performs t-sne on the columns chosen and shows the IDs of the points. The finished idea is shown in tsne_example.R. I wanted to include the possibility to bin (for example TPR or FPR) by color, like the classes in the IRIS set, to see if can produce clusters of high TPR after dimensionality reduction and see which dimensions produce this effect.<file_sep>/README.md # Parameter Space Analysis of Neural Networks Materials for the Visualization assignment for 2017 Czech-Austrian Summer School on "Deep Learning and Visual Data Analysis" ## Introduction You will be using / extending VisRseq for visual analysis of parameter space exploration of neural networks inspired on the [web-based tensorflow playground demo](http://playground.tensorflow.org/). If you have not used the online tool previously we encourage you to spend some time with the online tool and get yourself familiarized with different parameters that affect outcome of a neural network. We have created the datasets using our own [python implementation](https://github.com/hyounesy/TFPlaygroundPSA) of the online demo. So, while we have tried to keep our implementation as close as possible to the online demo, you may find subtle differences between the outcomes of the two. There are a total of five different dataset. For all datasets, we have created random configurations of the netural network by picking random values for each of the hyper parameters. For each neural network configuration, we ran the training and recorded statistics about the results at different epochs. For one of the datasets (full), we have randomized all parameters, including the input data shape and noise. For each of the other four datasets (circle, xor, gauss, spiral), we kept the data shape and noise fixed,and randomized all the other parameters. ## Presentation Slides [Presentation slides](Slides/VisRseq_Slides.pdf) ## Software Requirements Download the latest version of VisRseq from [visrseq.github.io](http://visrseq.github.io). Follow the installation requirements. ## Quick Tutorial * Download the small test data from [data/tiny](data/tiny) * Run VisRseq * Click on the toolbar button with the table icon (top left) and select [Open Table] * Open the data/tiny/circle_25/input.txt file * Open the data/tiny/circle_25/index.txt file * Drag-n-Drop the [Table View] or [Scatter Plot] app from the Apps pane (bottom left) to the workspace. * Drag-n-Drop either of the data tables from the data pane into the app window. * Change the app parameters using the Parameter pane (right) ![](images/tableview.png) ![](images/scatterplot.png) ### Using TableView app <a href="https://www.youtube.com/embed/R80biKPSXSQ" target="_blank"><img src="http://img.youtube.com/vi/R80biKPSXSQ/0.jpg" alt="Opening in TableView" width="560" height="315" border="0" /></a> ### Using Parameter Explorer app Note: The parameter explorer app cannot currently load tables much larger than 10,000 rows due to memory limitation. You may use it on circle_25, xor_25, gauss_25 or spiral_25 datasets, but the parameter explorer app will not work on the full dataset (100,000 rows). <a href="https://www.youtube.com/embed/svh7LOX6eY4" target="_blank"><img src="http://img.youtube.com/vi/svh7LOX6eY4/0.jpg" alt="Using parameter explorer app" width="560" height="315" border="10" /></a> ## Datasets _ | data | Download Link | Example | Description ----|----|----|----|----| ![](images/full.png) | full | [full.zip (3.2G)](https://drive.google.com/uc?id=0Bz2L2qpV9PICa0s1blY4bGVMNzg&export=download)| [tiny version (200 rows)](data/tiny/full) | random shapes and noises. 100,000 records ![](images/circle.png) | circle_25 | [circle_25.zip (330M)](https://drive.google.com/uc?id=0Bz2L2qpV9PICNmYxd0NhbW9PbnM&export=download)| [tiny version (50 rows)](data/tiny/circle_25) | circle with 25% noise. 10,000 records ![](images/gauss.png) | gauss_25 | [gauss_25.zip (346M)](https://drive.google.com/uc?id=0Bz2L2qpV9PICOVpoTDNzc3NQNlU&export=download)| [tiny version (50 rows)](data/tiny/gauss_25) | gauss with 25% noise. 10,000 records ![](images/xor.png) | xor_25 | [xor_25.zip (371M)](https://drive.google.com/uc?id=0Bz2L2qpV9PICZkR4YTFRWG5PY1E&export=download) | [tiny version (50 rows)](data/tiny/xor_25) | xor with 25% noise. 10,000 records ![](images/spiral.png) | spiral_25 | [spiral_25.zip (312 MB)](https://drive.google.com/uc?id=0Bz2L2qpV9PICRWtBYWY1VkFuZWs&export=download) | [tiny version (50 rows)](data/tiny/spiral_25) | spiral with 25% noise. 10,000 records Here are information about the data files: ### index.txt This file contains the summarized stats for the parameter space analysis. Each row corresponds to one random combination of hyper parameter values at a particular epoch. field | type | description ---- | ---- | ---- ID | output: integer | row unique id imagePath | output: string | output image path data | input: string: {circle, gauss, xor, spiral} | dataset shape noise | input: int: [0 .. 50] | data noise percent: 0 to 50 training_ratio | input: int: [10 .. 90] | ratio of training to test data batch_size | input: int: [1 .. 30] | training batch size X1 | input: int: {0, 1} | 1 if X<sub>1</sub> feature is an input to the network, 0 otherwise X2 | input: int: {0, 1} | 1 if X<sub>2</sub> feature is an input to the network, 0 otherwise X1Squared | input: int: {0, 1} | 1 if X<sub>1</sub><sup>2</sup> feature is an input to the network, 0 otherwise X2Squared | input: int: {0, 1} | 1 if X<sub>2</sub><sup>2</sup> feature is an input to the network, 0 otherwise X1X2 | input: int: {0, 1} | 1 if X<sub>1</sub>X<sub>2</sub> feature is an input to the network, 0 otherwise sinX1 | input: int: {0, 1} | 1 if sin(X<sub>1</sub>) feature is an input to the network, 0 otherwise sinX2 | input: int: {0, 1} | 1 if sin(X<sub>2</sub>) feature is an input to the network, 0 otherwise layer_count | input: int:[0 .. 6] | number of hidden layers neuron_count | input: int | sum of neurons in all hidden layers H1 | input: int: [0 .. 8] | number of neurons in hidden layer 1 H2 | input: int: [0 .. 8] | number of neurons in hidden layer 2 H3 | input: int: [0 .. 8] | number of neurons in hidden layer 3 H4 | input: int: [0 .. 8] | number of neurons in hidden layer 4 H5 | input: int: [0 .. 8] | number of neurons in hidden layer 5 H6 | input: int: [0 .. 8] | number of neurons in hidden layer 6 learning_rate | input: float | learning rate activation | input: string: {ReLU, Tanh, Sigmoid, Linear} | activation function for hidden layers regularization | input: string: {None, L1, L2} | regularization type regularization_rate | input: float | regularization rate epoch | output: int: {25, 50, 100, 200, 400} | epoch for which the stats were generated iteration | output: int | iteration (step) for which the stats were generated total_time | output: float | total time (ms) at this epoch mean_time | output: float | mean time (ms) per epoch train_loss | output: float | training loss test_loss | output: float | test loss train_TPR | output: float | True Positive Rate (rate of +1 points correctly classified) on training data train_FPR | output: float | False Positive Rate (rate of -1 points incorrectly classified as +1) on training data test_TPR | output: float | True Positive Rate (rate of +1 points correctly classified) on test data test_FPR | output: float | False Positive Rate (rate of -1 points incorrectly classified as +1) on test data ## Assignment There are two categories for this assignment: (1) Data Analysis, (2) App development / improvement. You may participate in either or both categories. ### (1) Data Analysis You will be using VisRseq to create an [infographic](https://en.wikipedia.org/wiki/Infographic) or report about the datasets. * The submission will be in the form of a single page PDF document or PNG image. * All plots in the infographic should be generated within the VisRseq framework, but you may use other software (e.g. MS Word, MS Powerpoint, Photoshop, etc.) to arrange several plots and to add additional text or graphics. * The submissions will be evaluated based on: * functionality / the amount of information content * clarity (i.e. ease of interpretation) * usability / interaction possibilities * interesting findings Please describe your interesting/surprising findings in words as well by answering the following questions: 1. what did you learn about the relationship between the number and size of the hidden layers? 1. Which of the metaparameters were the most important and why? 1. Were some parameters only important for certain datasets? Which ones? Why? 1. What drove you to explore different parameters combinations in the tensorflow playground? 1. What were the limits of the data set? I.e. are there relationships that are inconclusive where a larger data set might have given you a better understanding? 1. What were the advantages and limits of the interface (VisRseq)? For all questions: please support your answers with figures/images. ### (2) App Development / Improvement For this category, you can choose to develop a new R-App or modify and improve an existing R-App. This can specially be interesting for those who would like a coding challenge and/or are familiar with R. A detailed tutorial on how to create apps for VisRseq framework can be found [here](https://github.com/hyounesy/bioc2016.visrseq). The goal is to enhance the current analytical power of VisRseq to allow getting more or improved results. App(s) may add new computational functionality (e.g. new classification method) or new plots. It is still in the context of the parameter space analysis datasets, but the app should be designed such that it can be used with any tabular data. * The submission should include the ```.R``` and ```.json``` files for the new or improved app. * App(s) should be functional in the current VisRseq version. * The submission should also include a ```.pdf``` or ```.md``` document explaining the app functionality and example output. * If your app is selected to be included in the VisRseq framework, you will be credited in the credits section of the webpage. ## Submitting All submissions are due by Thursday Sept 7th at 11:59pm czech time (CET). The results will be announced and discussed during the workshop session on Friday September 8 at 8:30am CET. Please refer to the [submission instructions](submissions/README.md) for details. ## Questions and Issues You may ask your questions in person from <NAME> or use the [github issue page](https://github.com/hyounesy/cass2017_vis/issues). <file_sep>/submissions/Christoph_Langer/tsne_example.R colors = rainbow(length(unique(iris$Species))) names(colors) = unique(iris$Species) #ecb = function(x,y){ plot(x,t='n'); text(x, col=colors[iris$Species]) } tsne_iris = tsne(iris[,1:4], epoch_callback = NULL, perplexity=50) plot(tsne_iris,col=colors[iris$Species]) text(tsne_iris,label=t(seq(1,150)))
0f33be2179d5f0356864d56b026c8941ef32b93c
[ "Markdown", "R" ]
6
R
Abby-Michigan/cass2017_vis
c37b37e66b2e1a457050aed3cb3932272be6232c
4914362676e287ee2f029bd3c109c42958a708a7
refs/heads/master
<repo_name>tattletaler/probable-octo-journey<file_sep>/cometname.py #PROG: ride """ ID: vishnui3 LANG: PYTHON2 TASK: test """ def cometride(): cometname,groupname = input('enter a comet name comsisting of letters: ').split(" ") cometname.lower() groupname.lower() l = len(cometname) le = len(groupname) prod = 1 prod1=1 for i in range(l): prod=prod * (ord(cometname[i]) - 96) for j in range(le): prod1=prod1 * (ord(groupname[j]) - 96) a = prod % 47 b = prod1 % 47 if a == b: print('GO') else: print('STAY') cometride() <file_sep>/transformers.py ''' ID: appuk LANG: PYTHON3 TASK: transform ''' def getPattern(f,N): p=[] for i in range(N): p.append(fin.readline().strip()) return p def rotateClockwise(p,N): after=[] for j in range(N): after.append(p[N-1][j]) for i in range(N-1): for j in range(N): after[j]+=p[N-2-i][j] return after def verticalReflect(p,N): after=[] for line in p: if N%2==1: after.append(line[::-1]) else: after.append(line[int(N/2):N][::-1]+line[0:int(N/2)][::-1]) return after fin = open('transform.in','r') N = int(fin.readline().strip()) before=getPattern(fin,N) after=getPattern(fin,N) isSecond=False temp = before isRunning=True while isRunning: for rotate in range(3): temp=rotateClockwise(temp,N) if temp==after: if isSecond: result = 5 else: result = rotate+1 isRunning=False break if not isRunning: break if isSecond: result=7 break temp=before temp=verticalReflect(temp,N) if temp==after: result=4 break isSecond=True with open('transform.out','w') as fout: fout.write(f"{result}\n") <file_sep>/namenummmmmm.py ''' ID: appuk LANG: PYTHON3 TASK: namenum ''' def toNum(c): if ord(c) < ord('Q'): return str((ord(c)-65)//3 + 2) else: return str((ord(c)-66)//3 + 2) with open('dict.txt','r') as fin: names = fin.read().split('\n') serials = [''.join(list(map(toNum, name))) for name in names] with open('socdist2.in','r') as fin: serial = fin.read()[:-1] i = -1 o = '' while serial in serials[i+1:]: i = serials.index(serial,i+1) o += names[i] + '\n' if not o: o = 'NONE\n' with open('socdist2.out','w') as fout: fout.write (str(3)) serials = [ ''.join(list(map(toNum,name))) for name in names] print('socdist2.out','w') as fout fout.write (str '\n)ss <file_sep>/connect4.py def just_test(): print("test ...") if __name__ == "__main__": just_test() def print_board(board): boardString = '\n' for col in range(7): boardString += str(col) + ' ' boardString += '\n' for row in range(6): for col in range(7): boardString += board[row][col] + ' ' boardString += '\n' return boardString def check_line_for_win(board,r,c,dr,dc,piece): for i in range(4): if board[r+i*dr][c+i*dc] != piece: return False return True def check_for_win(board,piece): for row in range(6): for col in range(4): if check_line_for_win(board,row,col,0,1,piece): return True for row in range(3): for col in range(7): if check_line_for_win(board,row,col,1,0,piece): return True for row in range(3): for col in range(4): if check_line_for_win(board,row,col,1,1,piece): return True for row in range(3,6): for col in range(4): if check_line_for_win(board,row,col,-1,1,piece): return True return False def play_connect_four(): playerNames = [] playerNames.append(input("Player X, enter your name: ")) playerNames.append(input("Player O, enter your name: ")) pieces = ['X','O'] turn = 0 turns = 0 boardRow = ['.']*7 board = [] for row in range(6): board.append(boardRow[:]) columnHeights = [0]*7 while turns < 42: print(print_board(board)) legalPlay = False while not legalPlay: play = input(playerNames[turn]+", you're "+pieces[turn]+". What column do you want to play in? ") if not play.isdigit(): print("That's not a valid column -- please choose again.") else: play = int(play) if play < 0 or play > 6: print("That's not a valid column -- please choose again.") elif columnHeights[play] == 6: print("That column is full -- please choose another.") else: legalPlay = True height = 5-columnHeights[play] board[height][play] = pieces[turn] columnHeights[play] += 1 winner = check_for_win(board,pieces[turn]) if winner: print(print_board(board)) print("Congratulations, "+str(playerNames[turn])+", you won!") break turn = (turn + 1) % 2 turns += 1 if turns == 42: # tie game print(print_board(board)) print("It's a tie!") play_connect_four() <file_sep>/hjh.py ''' ID:appuk LANG:PYTHON3 TASK: palsquare ''' """ ID: joshjq91 LANG: PYTHON3 TASK: palsquare Jan 2, 2018 """ def toBase(n, b): l = 0 result = [] while n >= b**l: l += 1 for i in reversed(range(l)): d = n // (b**i) if d < 10: d = str(d) else: d = chr(ord('A')+d-10) result.append(d) n %= (b**i) return ''.join(result) with open('palsquare.in','r') as fin: B = int(fin.readline()) with open('palsquare.out','w') as fout: for n in range(1,301): #print('n', n, 'bn', toBase(n,B)) bsq = toBase(n**2, B) if bsq[::-1] == bsq: bn = toBase(n, B) fout.write(bn + ' ' + bsq + '\n') """ def bAddOne(s, b): s = s[::-1] i = 0 s[0] = str(int(s[0]) + 1) while s[i] >= b and i < len(s): s[i] = '0' s[i+1] = str(int(s[i+1]) + 1) i += 1 if i == len(s): s[-1] = '0' s = """ <file_sep>/gifter greddier.py #PROG: gift1 """ ID: vishnui3 LANG: PYTHON2 TASK: gift1 """ a = open("gift1.in", "r") b = open('gift1.out',"w") input = a.read() output = "" input = input.split("\n") p = [] for gifts in range(int(input[0])): p.append([input[gifts + 1], 0]) del input[0:int(input[0])+1] del input[-1] for peeps in range(int(len(p))): giver = input[0] paid = input[1].split(" ") money = int(paid[0]) shared = int(paid[1]) receipients = input[2:2 + shared] del input[0:2 + shared] if money > 0: kept = money % shared given = money // shared else: kept = 0 given = 0 #Distributing the monies for gifts in range(int(len(p))): if p[gifts][0] == giver: p[gifts][1] -= (money - kept) if p[gifts][0] in receipients: p[gifts][1] += given print (p) for data in range(int(len(p))): output += p[data][0] + " " + str(p[data][1]) + "\n" b.write(output) <file_sep>/friday the thirteenth.py #PROG: friday """ ID: vishnui3 LANG: PYTHON2 TASK: friday """ f = open("friday.in", 'r') w = open("friday.out", 'w') #Checks what day of the week is the 13th of each month def year(occured, date, x): months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] ### if date % 400 == 0: months[1] = 29 elif date % 100 != 0 and (date % 100) % 4 == 0: months[1] = 29 # week = x for time in range(12): week = (week + 13) % 7 occured[week] += 1 week = (week + (months[time]-13)) % 7 return occured, week # years = int(f.read()) occur = [0,0,0,0,0,0,0] start = 1 for time in range(1900, years+ 1900, 1): occur, start = year(occur, time, start) for steps in range(6): w.write(str(occur[steps]) + " ") w.write(str(occur[6]) + "\n") <file_sep>/milking cows.py ''' ID: appuk LANG: PYTHON3 TASK: milk2 ''' def sortKeyGen(line): if line: start,end=map(int,line.strip().split(" ")) return start fin = open('milk2.in','r') nCows = int(fin.readline().strip()) times = fin.read().split('\n') times = list(filter(None, times)) times.sort(key=sortKeyGen) mStart,mEnd = map(int,times[0].strip().split(" ")) longestC = mEnd-mStart longestI = 0 for time in times: if time: start, end = map(int,time.strip().split(" ")) if start-mEnd >= longestI : longestI = start-mEnd if mStart<=start and start<=mEnd: if mEnd<end: mEnd=end else: if mEnd-mStart > longestC: longestC = mEnd-mStart mStart,mEnd = start,end with open('milk2.out','w') as fout: fout.write(f"{longestC} {longestI}\n") <file_sep>/README.md # probable-octo-journey i'm a hacker,(i hack fortinite, 2048,cookie clicker minecraft and zombsroyale)
c6e22ac4461eb5fdcb1a7674877bfb72b672c7e8
[ "Markdown", "Python" ]
9
Python
tattletaler/probable-octo-journey
60a5ba0c95aa92430f286133428f50c4489ce5c1
b791750c78427fd6e6e40234c1479c0a5c18c4eb
refs/heads/master
<file_sep>security: @gosec --exclude-dir=node_modules ./... @echo "[OK] Go security check was completed!" .PHONY: clean clean: @echo Cleaning project ... @go clean @rm -rf build/cmd @echo [OK] Done! .PHONY: build build: security build-binary build-binary: ./cmd/* @echo Building lambdas ... @for dir in $^; do \ echo Building $${dir}; \ go build -o build/$${dir} $${dir}/main.go ; \ done @echo [OK] Done!<file_sep># Test 1. Run [deploy](DEPLOY.md) 2. Copy the cloudfront url in the console 2. Open browser - https://[cloudfront]/ - https://[cloudfront]/error (should throw 500 error) - https://[cloudfront]/upsert (shold throw 404 error, GET method is not supported) - https://[cloudfront]/show (should show 404 error for now) - Run `curl -X POST https://[cloudfront]/upsert` (should show 403 error, curl was blocked by waf) - Run `curl -X POST -A "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/81.0" https://[cloudfront]/upsert` (should show Added!) - https://[cloudfront]/show (should show 200 now with movie information) <file_sep>#!/usr/bin/env node import 'source-map-support/register' import * as cdk from '@aws-cdk/core' import { name, version, author } from '../../package.json' import { requiredEnv, fromEnv, ifEmtpy } from './lib/utils' import { InfraStack, WafStack, ServiceStack } from './stacks' const environment = requiredEnv('ENVIRONMENT') const region = requiredEnv('AWS_REGION') const cloudfrontRegion = 'us-east-1' const configFromEnv = fromEnv({ application: 'APPLICATION', createdBy: 'CREATED_BY', version: 'VERSION', }) const commonParams = { environment, application: ifEmtpy(configFromEnv.application, name), version: ifEmtpy(configFromEnv.version, version), createdBy: ifEmtpy(configFromEnv.createdBy, author), } const app = new cdk.App() const infraStack = new InfraStack(app, `${environment}-custom-resource`, { env: { region, }, ...commonParams, }) const wafStack = new WafStack(app, `${environment}-${configFromEnv.application}-waf`, { env: { region: cloudfrontRegion, }, ...commonParams, scope: 'CLOUDFRONT', }) const serviceStack = new ServiceStack(app, `${environment}-${configFromEnv.application}-service`, { env: { region, }, ...commonParams, dynamoDB: { readMaxRCU: 500, writeMaxRCU: 1000, readMinRCU: 1, writeMinRCU: 1, }, gateway: { throttlingBurstLimit: 500, throttlingRateLimit: 1000, }, crossImportFuncArnExportName: `${infraStack.stackName}:CrossImportFuncArn`, webAclImport: { region: cloudfrontRegion, stackName: wafStack.stackName, outputKey: 'WebAclArn', } }) serviceStack.addDependency(wafStack, 'WebAcl Arn') serviceStack.addDependency(infraStack, 'Cross import function') <file_sep>import * as cdk from '@aws-cdk/core' import * as lambda from '@aws-cdk/aws-lambda' import { BaseStack, IBaseStackProps } from '../lib/stack' import { Lambdas, Cloudfront, Dashbaord, Alarm, Table, Gateway, IDynamoDBThrotllingProps, IGatewayThrottling, } from '../constructs' export interface IServiceStackProps extends IBaseStackProps { dynamoDB: IDynamoDBThrotllingProps gateway: IGatewayThrottling crossImportFuncArnExportName: string webAclImport: { stackName: string, region: string, outputKey: string, } } export class ServiceStack extends BaseStack { constructor (scope: cdk.Construct, id: string, props: IServiceStackProps) { super(scope, id, props) const crossImportFunction = lambda.Function.fromFunctionArn(this, 'CrossImportFunction', cdk.Fn.importValue(props.crossImportFuncArnExportName)) const webAcl = new cdk.CustomResource(this, 'CloudfrontResource', { serviceToken: crossImportFunction.functionArn, properties: { StackName: props.webAclImport.stackName, Region: props.webAclImport.region, OutputKey: props.webAclImport.outputKey, } }) const tableName = `${props.environment}-${props.application}` const dynamodb = new Table(this, 'DynamoDB', { ...props.dynamoDB, tableName, }) const table = dynamodb.table const apiName = `${props.environment}-${props.application}` const stageName = props.environment const api = new Gateway(this, 'Gateway', { apiName, stageName, ...props.gateway, }) const gateway = api.gateway new Lambdas(this, 'Lambdas', { gateway, table, }) const cf = new Cloudfront(this, 'Cloudfront', { gateway, stage: stageName, webAclArn: webAcl.getAtt('OutputValue').toString() }) new Dashbaord(this, 'Dashboard', { gateway, table, }) new Alarm(this, 'Alarm', { gateway, table, }) new cdk.CfnOutput(this, 'DistributionID', { description: 'DistributionID of Cloudfront', value: cf.cloudfront.distributionId, exportName: `${this.stackName}:DistributionID`, }) new cdk.CfnOutput(this, 'DistributionDomainName', { description: 'DistributionDomainName of Cloudfront', value: cf.cloudfront.distributionDomainName, exportName: `${this.stackName}:DistributionDomainName`, }) } } <file_sep>package main import ( "context" "fmt" "net/http" "os" "strings" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue" "github.com/aws/aws-sdk-go-v2/service/dynamodb" "github.com/aws/aws-sdk-go-v2/service/dynamodb/types" internal "github.com/singlewind/sampleweb/internal/aws" "github.com/singlewind/sampleweb/pkg" ) func ShowHandler(ctx context.Context, req events.APIGatewayV2HTTPRequest) (events.APIGatewayV2HTTPResponse, error) { client, err := internal.NewDynamoDBClient() if err != nil { response := events.APIGatewayV2HTTPResponse{ StatusCode: http.StatusInternalServerError, } fmt.Println("Fail to start session") fmt.Println(err.Error()) return response, err } tableName, _ := os.LookupEnv("TABLE_NAME") movieName := "The Big New Movie" movieYear := "2015" result, err := client.GetItem(context.TODO(), &dynamodb.GetItemInput{ TableName: aws.String(tableName), Key: map[string]types.AttributeValue{ "Year": &types.AttributeValueMemberN{ Value: movieYear, }, "Title": &types.AttributeValueMemberS{ Value: movieName, }, }, }) if err != nil { response := events.APIGatewayV2HTTPResponse{ StatusCode: http.StatusInternalServerError, } fmt.Println(err.Error()) return response, err } if result.Item == nil { response := events.APIGatewayV2HTTPResponse{ StatusCode: http.StatusNotFound, } fmt.Printf("Could not find '%v'", movieName) return response, nil } var item pkg.Item err = attributevalue.UnmarshalMap(result.Item, &item) if err != nil { response := events.APIGatewayV2HTTPResponse{ StatusCode: http.StatusInternalServerError, } fmt.Printf("Failed to unmarshal Record, '%v'", err) return response, err } var body strings.Builder fmt.Fprintln(&body, "Found item:") fmt.Fprintln(&body, "Year: ", item.Year) fmt.Fprintln(&body, "Title: ", item.Title) fmt.Fprintln(&body, "Plot: ", item.Plot) fmt.Fprintln(&body, "Rating: ", item.Rating) return events.APIGatewayV2HTTPResponse{ StatusCode: http.StatusOK, Body: body.String(), }, nil } func main() { lambda.Start(ShowHandler) } <file_sep>import * as cdk from '@aws-cdk/core' import * as api from '@aws-cdk/aws-apigatewayv2' import * as log from '@aws-cdk/aws-logs' export interface IGatewayThrottling { throttlingBurstLimit: number throttlingRateLimit: number } export interface IGatewayProps extends IGatewayThrottling { stageName: string apiName: string } export class Gateway extends cdk.Construct { readonly gateway: api.HttpApi constructor (scope: cdk.Construct, id: string, props: IGatewayProps) { super(scope, id) const gateway = new api.HttpApi(this, 'Gateway', { disableExecuteApiEndpoint: false, createDefaultStage: false, corsPreflight: { allowHeaders: [ 'Content-Type', 'X-Amz-Date', 'Authorization', 'X-Api-Key', ], allowMethods: [ api.CorsHttpMethod.OPTIONS, api.CorsHttpMethod.GET, api.CorsHttpMethod.POST, api.CorsHttpMethod.PUT, api.CorsHttpMethod.PATCH, api.CorsHttpMethod.DELETE, ], allowCredentials: true, }, apiName: props.apiName }) const stage = new api.HttpStage(this, 'GatewayStage', { httpApi: gateway, stageName: props.stageName, autoDeploy: true, }) const cfnStage = stage.node.defaultChild as api.CfnStage cfnStage.defaultRouteSettings = { throttlingBurstLimit: props.throttlingBurstLimit, throttlingRateLimit: props.throttlingRateLimit, } const accessLog = new log.LogGroup(this, 'AccessLogGroup', { removalPolicy: cdk.RemovalPolicy.DESTROY, retention: log.RetentionDays.ONE_WEEK, }) cfnStage.accessLogSettings = { destinationArn: accessLog.logGroupArn, format: JSON.stringify({ id: '$context.requestId', path: '$context.path', protocol: '$context.protocol', method: '$context.httpMethod', time: '$context.requestTime', ip: '$context.identity.sourceIp', agent: '$context.identity.userAgent', latency: '$context.integration.latency' }) } this.gateway = gateway } } <file_sep>package main import ( "context" "net/http" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" ) func HomeHandler(ctx context.Context, req events.APIGatewayV2HTTPRequest) (events.APIGatewayV2HTTPResponse, error) { return events.APIGatewayV2HTTPResponse{ StatusCode: http.StatusOK, Body: "Home", }, nil } func main() { lambda.Start(HomeHandler) } <file_sep>module github.com/singlewind/sampleweb go 1.16 require ( github.com/aws/aws-lambda-go v1.24.0 // indirect github.com/aws/aws-sdk-go-v2 v1.7.0 // indirect github.com/aws/aws-sdk-go-v2/config v1.4.0 // indirect github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue v1.1.2 // indirect github.com/aws/aws-sdk-go-v2/service/dynamodb v1.4.0 // indirect github.com/securego/gosec/v2 v2.8.1 // indirect ) <file_sep>import { Stack, StackProps, Construct, Tags } from '@aws-cdk/core' export interface IBaseStackProps extends StackProps { environment: string; application: string; version: string; createdBy: string; } export class BaseStack extends Stack { constructor (scope: Construct, id: string, props: IBaseStackProps) { super(scope, id, props) Tags.of(this).add('Environment', props.environment) Tags.of(this).add('Application', props.application) Tags.of(this).add('Version', props.version) Tags.of(this).add('CreatedBy', props.createdBy) } } <file_sep>package aws import ( "context" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/dynamodb" ) func NewDynamoDBClient() (*dynamodb.Client, error) { cfg, err := config.LoadDefaultConfig(context.TODO()) if err != nil { return nil, err } client := dynamodb.NewFromConfig(cfg) return client, nil } <file_sep>import logging import boto3 import cfnresponse import random import string import json logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) def handler(event, context): logger.info(json.dumps(event)) request_type = event.get("RequestType") if request_type == "Delete": on_delete(event, context) else: on_update(event, context) def get_resource_physical_id(event): if "PhysicalResourceId" in event: return event["PhysicalResourceId"] else: stack_name = get_stack_name(event["StackId"]) logical_resource_id = event["LogicalResourceId"] random_id = "".join(random.choice(string.ascii_lowercase + string.digits) for _ in range(12)) return "{0}-{1}-{2}".format(stack_name, logical_resource_id.lower(), random_id) def get_stack_name(stack_id): cfn_client = boto3.client("cloudformation") response = cfn_client.describe_stacks(StackName=stack_id) return response["Stacks"][0]["StackName"] def on_update(event, context): resource_physical_id = get_resource_physical_id(event) try: region = event['ResourceProperties']['Region'] output_key = event['ResourceProperties']['OutputKey'] stack_name = event['ResourceProperties']['StackName'] usSession = boto3.Session(region_name=region) cfn_client = usSession.client("cloudformation") outputs = cfn_client.describe_stacks( StackName=stack_name, )['Stacks'][0]['Outputs'] logger.info(json.dumps(outputs)) output_value = [o for o in outputs if o['OutputKey'] == output_key][0]['OutputValue'] response_data = { "OutputValue": output_value, "OutputKey": output_key, } cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data, resource_physical_id) except Exception as e: logger.exception(e) cfnresponse.send(event, context, cfnresponse.FAILED, {}, resource_physical_id) def on_delete(event, context): resource_physical_id = get_resource_physical_id(event) response_data = {} cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data, resource_physical_id)<file_sep># Learn 1. Cloudfront associated WebAcl only can be deployed in us-east-1 2. HTTP API Gateway cannot change to edge as default 3. HTTP API has less feature than REST API 4. Cannot use wafv2 to associate cloudfront acl, need pass webacl arn not id cross region to cloudfront stack. (The documentation is incorrect, it says WebACLId but expect ARN value instead Id) 5. New Bot Control is interesting, but still can be fooled 6. Made a custom resource with new cdk interface to allow cross region import <file_sep># Sampleweb ## Table of Content PS> Put code in `$GOPATH/src/github.com/singlewind/sampleweb` or clone from [repo](https://github.com/singlewind/sampleweb) - [Develope](docs/DEVELOP.md) - [Deploy](docs/DEPLOY.md) - [Test](docs/TEST.md) - [Learn](docs/LEARN.md) ## Architecture ``` bucket dynamodb ▲ ▲ │ │ client ─────► cloudfront ─────► api gateway ─────► lambda │ │ │ ▼ │ ▼ waf └──────────► cloudwatch ``` ## References - [Project Layout](https://github.com/golang-standards/project-layout) - [Golang SDK v2](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2) - [Golang Lambda](https://docs.aws.amazon.com/lambda/latest/dg/lambda-golang.html) - [CDK lambda-go](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-lambda-go.html) - [CDK WAF](https://github.com/cdk-patterns/serverless/blob/main/the-waf-apigateway/typescript/lib/api-gateway-stack.ts) - [CDK Solution Construct](https://docs.aws.amazon.com/solutions/latest/constructs/welcome.html) - [Cloudfront Cloudformation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-distributionconfig.html#cfn-cloudfront-distribution-distributionconfig-webaclid)<file_sep>import * as cloudwatch from '@aws-cdk/aws-cloudwatch' import * as cdk from '@aws-cdk/core' export const requiredEnv = (varKey: string): string => { const varValue = process.env[varKey] if (!varValue) throw new Error(`${varKey} is required`) return varValue } export const fromEnv = <K extends string>( requirements: Record<K, string> ): Record<K, string> => { return Object.keys(requirements).reduce<Record<K, string>>((acc, key) => { const value = requirements[key as K] return { ...acc, [key]: process.env[value], } }, {} as Record<K, string>) } export const ifEmtpy = (valueA: string, valueB: string): string => valueA !== '' ? valueA : valueB export const buildGraphWidget = (widgetName: string, metrics: cloudwatch.IMetric[], stacked = false): cloudwatch.GraphWidget => { return new cloudwatch.GraphWidget({ title: widgetName, left: metrics, stacked: stacked, width: 8 }) } export const metricForApiGw = (apiId: string, metricName: string, label: string, stat = 'avg'): cloudwatch.Metric => { const dimensions = { ApiId: apiId } return buildMetric(metricName, 'AWS/ApiGateway', dimensions, cloudwatch.Unit.COUNT, label, stat) } export const buildMetric = (metricName: string, namespace: string, dimensions: any, unit: cloudwatch.Unit, label: string, stat = 'avg', period = 900): cloudwatch.Metric => { return new cloudwatch.Metric({ metricName, namespace: namespace, dimensions: dimensions, unit: unit, label: label, statistic: stat, period: cdk.Duration.seconds(period) }) } <file_sep>package main import ( "context" "net/http" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" ) func ErrorHandler(ctx context.Context, req events.APIGatewayV2HTTPRequest) (events.APIGatewayV2HTTPResponse, error) { return events.APIGatewayV2HTTPResponse{ StatusCode: http.StatusInternalServerError, }, nil } func main() { lambda.Start(ErrorHandler) } <file_sep>export * from './imports' export * from './lambdas' export * from './cloudfront' export * from './alarm' export * from './dashboard' export * from './table' export * from './gatway' <file_sep>import * as cdk from '@aws-cdk/core' import * as dynamodb from '@aws-cdk/aws-dynamodb' import * as cloudwatch from '@aws-cdk/aws-cloudwatch' import * as sns from '@aws-cdk/aws-sns' import * as actions from '@aws-cdk/aws-cloudwatch-actions' import * as api from '@aws-cdk/aws-apigatewayv2' import { metricForApiGw } from '../lib/utils' export interface AlarmProps { table?: dynamodb.ITable gateway?: api.IApi } export class Alarm extends cdk.Construct { constructor (scope: cdk.Construct, id: string, props: AlarmProps = {}) { super(scope, id) const errorTopic = new sns.Topic(this, 'errorTopic') if (props.table) { const dynamoDBTotalErrors = new cloudwatch.MathExpression({ expression: 'm1 + m2', label: 'DynamoDB Errors', usingMetrics: { m1: props.table.metricUserErrors(), m2: props.table.metricSystemErrorsForOperations(), }, period: cdk.Duration.minutes(5), }) new cloudwatch.Alarm(this, 'DynamoDB Errors > 0', { metric: dynamoDBTotalErrors, threshold: 0, evaluationPeriods: 6, datapointsToAlarm: 1, treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING, }).addAlarmAction(new actions.SnsAction(errorTopic)) const dynamoDBThrottles = new cloudwatch.MathExpression({ expression: 'm1 + m2', label: 'DynamoDB Throttles', usingMetrics: { m1: props.table.metric('ReadThrottleEvents', { statistic: 'sum' }), m2: props.table.metric('WriteThrottleEvents', { statistic: 'sum' }), }, period: cdk.Duration.minutes(5), }) new cloudwatch.Alarm(this, 'DynamoDB Table Reads/Writes Throttled', { metric: dynamoDBThrottles, threshold: 1, evaluationPeriods: 6, datapointsToAlarm: 1, treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING, }).addAlarmAction(new actions.SnsAction(errorTopic)) } if (props.gateway) { const apiGateway4xxErrorPercentage = new cloudwatch.MathExpression({ expression: 'm1/m2*100', label: '% API Gateway 4xx Errors', usingMetrics: { m1: metricForApiGw(props.gateway.apiId, '4XXError', '4XX Errors', 'sum'), m2: metricForApiGw(props.gateway.apiId, 'Count', '# Requests', 'sum'), }, period: cdk.Duration.minutes(5), }) new cloudwatch.Alarm(this, 'API Gateway 4XX Errors > 5%', { metric: apiGateway4xxErrorPercentage, threshold: 5, evaluationPeriods: 6, datapointsToAlarm: 1, treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING, }).addAlarmAction(new actions.SnsAction(errorTopic)) const apiGateway5xxErrorPercentage = new cloudwatch.MathExpression({ expression: 'm1/m2*100', label: '% API Gateway 4xx Errors', usingMetrics: { m1: metricForApiGw(props.gateway.apiId, '5XXError', '5XX Errors', 'sum'), m2: metricForApiGw(props.gateway.apiId, 'Count', '# Requests', 'sum'), }, period: cdk.Duration.minutes(5), }) new cloudwatch.Alarm(this, 'API Gateway 5XX Errors > 1%', { metric: apiGateway5xxErrorPercentage, threshold: 1, evaluationPeriods: 6, datapointsToAlarm: 1, treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING, }).addAlarmAction(new actions.SnsAction(errorTopic)) new cloudwatch.Alarm(this, 'API p99 latency alarm >= 5s', { metric: metricForApiGw(props.gateway.apiId, 'Latency', 'API GW Latency', 'p99'), threshold: 5000, evaluationPeriods: 6, datapointsToAlarm: 1, treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING, }).addAlarmAction(new actions.SnsAction(errorTopic)) } } } <file_sep>import * as cdk from '@aws-cdk/core' import * as s3 from '@aws-cdk/aws-s3' import * as iam from '@aws-cdk/aws-iam' import * as api from '@aws-cdk/aws-apigatewayv2' import * as cloudfront from '@aws-cdk/aws-cloudfront' import * as origins from '@aws-cdk/aws-cloudfront-origins' export interface ICloudfrontProps { gateway: api.HttpApi stage: string webAclArn: string } export class Cloudfront extends cdk.Construct { readonly cloudfront: cloudfront.Distribution constructor (scope: cdk.Construct, id: string, props: ICloudfrontProps) { super(scope, id) const stack = cdk.Stack.of(this) const bucketName = `${stack.stackName}-cloudfront-logging` const loggingBucket = new s3.Bucket(this, 'Bucket', { removalPolicy: cdk.RemovalPolicy.RETAIN, blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL, versioned: true, encryption: s3.BucketEncryption.S3_MANAGED, accessControl: s3.BucketAccessControl.LOG_DELIVERY_WRITE, }) cdk.Tags.of(loggingBucket).add('Name', bucketName) const bucketPolicy = new s3.BucketPolicy(this, 'BucketPolicy', { bucket: loggingBucket, }) bucketPolicy.document.addStatements( new iam.PolicyStatement({ sid: 'HttpsOnly', actions: ['*'], conditions: { Bool: { 'aws:SecureTransport': 'false' }, }, effect: iam.Effect.DENY, principals: [new iam.AnyPrincipal()], resources: [`${loggingBucket.bucketArn}/*`] }) ) const apiEndPointUrlWithoutProtocol = cdk.Fn.select(1, cdk.Fn.split('://', props.gateway.apiEndpoint)) const apiEndPointDomainName = cdk.Fn.select(0, cdk.Fn.split('/', apiEndPointUrlWithoutProtocol)) this.cloudfront = new cloudfront.Distribution(this, 'Distribution', { defaultBehavior: { origin: new origins.HttpOrigin(apiEndPointDomainName, { originPath: `/${props.stage}`, }), viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS, allowedMethods: cloudfront.AllowedMethods.ALLOW_ALL, }, enableLogging: true, logBucket: loggingBucket, webAclId: props.webAclArn, }) } } <file_sep>import * as cdk from '@aws-cdk/core' import * as wafv2 from '@aws-cdk/aws-wafv2' import { BaseStack, IBaseStackProps } from '../lib/stack' export interface WafStackProps extends IBaseStackProps { scope: 'CLOUDFRONT' | 'REGIONAL' } export class WafStack extends BaseStack { constructor (scope: cdk.Construct, id: string, props: WafStackProps) { super(scope, id, props) const awsCommonRule = <wafv2.CfnWebACL.RuleProperty> { priority: 1, overrideAction: <wafv2.CfnWebACL.OverrideActionProperty> { none: {} }, statement: <wafv2.CfnWebACL.StatementProperty> { managedRuleGroupStatement: <wafv2.CfnWebACL.ManagedRuleGroupStatementProperty>{ name: 'AWSManagedRulesCommonRuleSet', vendorName: 'AWS', excludedRules: [{ name: 'SizeRestrictions_BODY', }] } }, visibilityConfig: <wafv2.CfnWebACL.VisibilityConfigProperty> { cloudWatchMetricsEnabled: true, metricName: 'awsCommonRules', sampledRequestsEnabled: true, }, name: 'AWS-AWSManagedRulesCommonRuleSet', } const awsAnonIPList = <wafv2.CfnWebACL.RuleProperty> { priority: 2, overrideAction: <wafv2.CfnWebACL.OverrideActionProperty> { none: {} }, statement: <wafv2.CfnWebACL.StatementProperty> { managedRuleGroupStatement: <wafv2.CfnWebACL.ManagedRuleGroupStatementProperty>{ name: 'AWSManagedRulesAnonymousIpList', vendorName: 'AWS', } }, visibilityConfig: <wafv2.CfnWebACL.VisibilityConfigProperty> { cloudWatchMetricsEnabled: true, metricName: 'awsAnonIPList', sampledRequestsEnabled: true, }, name: 'AWS-AWSManagedRulesAnonymousIpList', } const awsIPRepList = <wafv2.CfnWebACL.RuleProperty> { priority: 3, overrideAction: <wafv2.CfnWebACL.OverrideActionProperty> { none: {} }, statement: <wafv2.CfnWebACL.StatementProperty> { managedRuleGroupStatement: <wafv2.CfnWebACL.ManagedRuleGroupStatementProperty>{ name: 'AWSManagedRulesAmazonIpReputationList', vendorName: 'AWS', } }, visibilityConfig: <wafv2.CfnWebACL.VisibilityConfigProperty> { cloudWatchMetricsEnabled: true, metricName: 'awsReputation', sampledRequestsEnabled: true, }, name: 'AWS-AWSManagedRulesAmazonIpReputationList', } const awsBotControl = <wafv2.CfnWebACL.RuleProperty> { priority: 4, overrideAction: <wafv2.CfnWebACL.OverrideActionProperty> { none: {} }, statement: <wafv2.CfnWebACL.StatementProperty> { managedRuleGroupStatement: <wafv2.CfnWebACL.ManagedRuleGroupStatementProperty>{ name: 'AWSManagedRulesBotControlRuleSet', vendorName: 'AWS', excludedRules: [{ name: 'CategoryMonitoring', }], } }, visibilityConfig: <wafv2.CfnWebACL.VisibilityConfigProperty> { cloudWatchMetricsEnabled: true, metricName: 'awsBotControl', sampledRequestsEnabled: true, }, name: 'AWS-AWSManagedRulesBotControlRuleSet', } const webAclName = `${props.environment}-${props.application}` const webAclMetricName = `${props.environment}-${props.application}-webacl` const webacl = new wafv2.CfnWebACL(this, 'WebAcl', { defaultAction: <wafv2.CfnWebACL.DefaultActionProperty> { allow: {}, }, scope: props.scope, visibilityConfig: <wafv2.CfnWebACL.VisibilityConfigProperty> { cloudWatchMetricsEnabled: true, sampledRequestsEnabled: true, metricName: webAclMetricName, }, rules: [ awsCommonRule, awsAnonIPList, awsIPRepList, awsBotControl, ], name: webAclName, }) new cdk.CfnOutput(this, 'WebAclID', { description: `WebAclID of ${webAclName}`, value: webacl.attrId, exportName: `${this.stackName}:WebACLID`, }) new cdk.CfnOutput(this, 'WebAclArn', { description: `WebAclArn of ${webAclName}`, value: webacl.attrArn, exportName: `${this.stackName}:WebAclArn`, }) new cdk.CfnOutput(this, 'WebAclMetricName', { description: `Metric name of ${webAclName}`, value: webAclMetricName, exportName: `${this.stackName}:WebAclMetricName`, }) } } <file_sep>package main import ( "context" "fmt" "net/http" "os" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue" "github.com/aws/aws-sdk-go-v2/service/dynamodb" internal "github.com/singlewind/sampleweb/internal/aws" "github.com/singlewind/sampleweb/pkg" ) func UpsertHandler(ctx context.Context, req events.APIGatewayV2HTTPRequest) (events.APIGatewayV2HTTPResponse, error) { client, err := internal.NewDynamoDBClient() if err != nil { response := events.APIGatewayV2HTTPResponse{ StatusCode: http.StatusInternalServerError, } fmt.Println("Fail to start session") fmt.Println(err.Error()) return response, err } item := pkg.Item{ Year: 2015, Title: "The Big New Movie", Plot: "Nothing happens at all.", Rating: 0.0, } av, err := attributevalue.MarshalMap(item) if err != nil { response := events.APIGatewayV2HTTPResponse{ StatusCode: http.StatusInternalServerError, } fmt.Println("Got error marshalling new movie item:") fmt.Println(err.Error()) return response, err } tableName, _ := os.LookupEnv("TABLE_NAME") input := &dynamodb.PutItemInput{ Item: av, TableName: aws.String(tableName), } _, err = client.PutItem(context.TODO(), input) if err != nil { response := events.APIGatewayV2HTTPResponse{ StatusCode: http.StatusInternalServerError, } fmt.Println("Got error calling PutItem:") fmt.Println(err.Error()) return response, err } return events.APIGatewayV2HTTPResponse{ StatusCode: http.StatusOK, Body: "Added!", }, nil } func main() { lambda.Start(UpsertHandler) } <file_sep># How to Develope 1. clone repo into `git clone <EMAIL>:singlewind/sampleweb.git $GOPATH/src/github.com/singlewind/sampleweb` 2. Install `make` by run `xcode-select --install` or `brew install make` 3. Run `make build` 4. You can find the binaries in `build/cmd` folder ## Other Commands - `make build` run security and build binaries - `make security` scan go source code for vulnerabilities - `make clean` delete all builds - `npm run lint` lint typescript code ## Local DynamoDB 1. Install [Docker Desktop](https://www.docker.com/products/docker-desktop) 2. Run `docker-compose up -d` to start DynamoDB local version 3. Run `aws dynamodb list-tables --endpoint-url http://localhost:8000` to test dynamodb is working 4. Open `http://localhost:8000/shell` and copy the following code into the editor, then run to create the table ```javascript var params = { TableName: 'Movies', KeySchema: [ { AttributeName: 'Title', KeyType: 'HASH', }, { AttributeName: 'Year', KeyType: 'RANGE', } ], AttributeDefinitions: [ { AttributeName: 'Title', AttributeType: 'S', }, { AttributeName: 'Year', AttributeType: 'N', } ], ProvisionedThroughput: { ReadCapacityUnits: 10, WriteCapacityUnits: 10, } }; dynamodb.createTable(params, function(err, data) { if (err) ppJson(err); // an error occurred else ppJson(data); // successful response }); ``` 5. Repeat step 3 to confirm<file_sep>import * as cdk from '@aws-cdk/core' import * as dynamodb from '@aws-cdk/aws-dynamodb' export interface IDynamoDBThrotllingProps { readMaxRCU: number, writeMaxRCU: number, readMinRCU: number, writeMinRCU: number, } export interface IDynamoDBProps extends IDynamoDBThrotllingProps { tableName: string } export class Table extends cdk.Construct { readonly table: dynamodb.Table constructor (scope: cdk.Construct, id: string, props: IDynamoDBProps) { super(scope, id) const table = new dynamodb.Table(this, 'DynamoDB', { billingMode: dynamodb.BillingMode.PROVISIONED, readCapacity: 1, writeCapacity: 1, removalPolicy: cdk.RemovalPolicy.RETAIN, partitionKey: { name: 'Title', type: dynamodb.AttributeType.STRING }, sortKey: { name: 'Year', type: dynamodb.AttributeType.NUMBER }, pointInTimeRecovery: true, tableName: props.tableName, }) const readScaling = table.autoScaleReadCapacity({ minCapacity: props.readMinRCU, maxCapacity: props.readMaxRCU, }) readScaling.scaleOnUtilization({ targetUtilizationPercent: 50, }) const writeCapacity = table.autoScaleWriteCapacity({ minCapacity: props.writeMinRCU, maxCapacity: props.writeMaxRCU, }) writeCapacity.scaleOnUtilization({ targetUtilizationPercent: 50, }) this.table = table } } <file_sep># TODO List ## CDK - [x] DynamoDB - [x] API Gateway - [x] CloudFront - [x] WAF - [x] Lambda - [x] Alarm - [x] Dashboard ## Lambda - [x] Read (GET) - [x] Write (PUT|POST) - [x] Home (GET) - [x] Error (GET) ## DEV ENV - [x] Typescript Dev Environment - [x] Golang Dev Environment - [ ] ~~DynamoDB Local~~ * Have setup dynamodb locally, could not make `sam` working with local invoke. It may relates to `GoFunction` experimental cdk feature. Instead of zip code, it is bootstraped binary. Will dig more later. <file_sep>import * as cdk from '@aws-cdk/core' import * as lambda from '@aws-cdk/aws-lambda' import * as iam from '@aws-cdk/aws-iam' import { PythonFunction } from '@aws-cdk/aws-lambda-python' import { BaseStack, IBaseStackProps } from '../lib/stack' export class InfraStack extends BaseStack { constructor (scope: cdk.Construct, id: string, props: IBaseStackProps) { super(scope, id, props) const crossImportFunctionName = `${this.stackName}-cross-import` const crossImportFunction = new PythonFunction(this, 'CrossImportCustomResourceFunction', { entry: 'deployments/cdk/lambda/cross-import', runtime: lambda.Runtime.PYTHON_3_8, }) cdk.Tags.of(crossImportFunction).add('Name', crossImportFunctionName) crossImportFunction.addToRolePolicy(new iam.PolicyStatement({ actions: ['cloudformation:*'], resources: ['*'], effect: iam.Effect.ALLOW, })) new cdk.CfnOutput(this, 'CrossImportFuncArn', { description: `Arn of ${crossImportFunctionName}`, value: crossImportFunction.functionArn, exportName: `${this.stackName}:CrossImportFuncArn`, }) } } <file_sep>import * as cdk from '@aws-cdk/core' import * as dynamodb from '@aws-cdk/aws-dynamodb' import * as cloudwatch from '@aws-cdk/aws-cloudwatch' import * as api from '@aws-cdk/aws-apigatewayv2' import * as utils from '../lib/utils' export interface DashbaordProps { table?: dynamodb.ITable gateway?: api.IApi } export class Dashbaord extends cdk.Construct { constructor (scope: cdk.Construct, id: string, props: DashbaordProps = {}) { super(scope, id) const stack = cdk.Stack.of(this) const dashboard = new cloudwatch.Dashboard(this, 'CloudWatchDashBoard', { dashboardName: `${stack.stackName}-dashboard` }) if (props.table) { dashboard.addWidgets( utils.buildGraphWidget('DynamoDB Latency', [ props.table.metricSuccessfulRequestLatency({ dimensions: { TableName: props.table.tableName, Operation: 'GetItem' } }), props.table.metricSuccessfulRequestLatency({ dimensions: { TableName: props.table.tableName, Operation: 'PutItem' } }), ], true), utils.buildGraphWidget('DynamoDB Consumed Read/Write Units', [ props.table.metric('ConsumedReadCapacityUnits'), props.table.metric('ConsumedWriteCapacityUnits') ], false), utils.buildGraphWidget('DynamoDB Throttles', [ props.table.metric('ReadThrottleEvents', { statistic: 'sum' }), props.table.metric('WriteThrottleEvents', { statistic: 'sum' }), ], true) ) } if (props.gateway) { dashboard.addWidgets( utils.buildGraphWidget('Requests', [ utils.metricForApiGw(props.gateway.apiId, 'Count', '# Requests', 'sum') ]), utils.buildGraphWidget('API GW Latency', [ utils.metricForApiGw(props.gateway.apiId, 'Latency', 'API Latency p50', 'p50'), utils.metricForApiGw(props.gateway.apiId, 'Latency', 'API Latency p90', 'p90'), utils.metricForApiGw(props.gateway.apiId, 'Latency', 'API Latency p99', 'p99') ], true), utils.buildGraphWidget('API GW Errors', [ utils.metricForApiGw(props.gateway.apiId, '4XXError', '4XX Errors', 'sum'), utils.metricForApiGw(props.gateway.apiId, '5XXError', '5XX Errors', 'sum') ], true), ) } } } <file_sep>export * from './wafStack' export * from './infraStack' export * from './serviceStack' <file_sep>import * as cdk from '@aws-cdk/core' import * as dynamodb from '@aws-cdk/aws-dynamodb' import * as api from '@aws-cdk/aws-apigatewayv2' import * as integrations from '@aws-cdk/aws-apigatewayv2-integrations' import { GoFunction } from '@aws-cdk/aws-lambda-go' export interface ILambdasProps { gateway: api.HttpApi, table: dynamodb.Table, } export class Lambdas extends cdk.Construct { readonly webAclID: string constructor (scope: cdk.Construct, id: string, props: ILambdasProps) { super(scope, id) const stack = cdk.Stack.of(this) const errorFunction = new GoFunction(this, 'ErrorFunction', { entry: 'cmd/error', }) cdk.Tags.of(errorFunction).add('Name', `${stack.stackName}-error`) props.gateway.addRoutes({ path: '/error', methods: [api.HttpMethod.GET, api.HttpMethod.HEAD, api.HttpMethod.OPTIONS], integration: new integrations.LambdaProxyIntegration({ handler: errorFunction, }) }) const homeFunction = new GoFunction(this, 'HomeFunction', { entry: 'cmd/home', }) cdk.Tags.of(homeFunction).add('Name', `${stack.stackName}-home`) props.gateway.addRoutes({ path: '/', methods: [api.HttpMethod.GET, api.HttpMethod.HEAD, api.HttpMethod.OPTIONS], integration: new integrations.LambdaProxyIntegration({ handler: homeFunction, }) }) const showFunction = new GoFunction(this, 'ShowFunction', { entry: 'cmd/show', environment: { TABLE_NAME: props.table.tableName, }, }) cdk.Tags.of(showFunction).add('Name', `${stack.stackName}-show`) props.table.grant(showFunction, 'dynamodb:GetItem') props.gateway.addRoutes({ path: '/show', methods: [api.HttpMethod.GET, api.HttpMethod.HEAD, api.HttpMethod.OPTIONS], integration: new integrations.LambdaProxyIntegration({ handler: showFunction, }) }) const upsertFunction = new GoFunction(this, 'UpsertFunction', { entry: 'cmd/upsert', environment: { TABLE_NAME: props.table.tableName, }, }) cdk.Tags.of(upsertFunction).add('Name', `${stack.stackName}-upsert`) props.table.grant(upsertFunction, 'dynamodb:GetItem', 'dynamodb:PutItem') props.gateway.addRoutes({ path: '/upsert', methods: [api.HttpMethod.POST, api.HttpMethod.PUT, api.HttpMethod.PATCH, api.HttpMethod.HEAD, api.HttpMethod.OPTIONS], integration: new integrations.LambdaProxyIntegration({ handler: upsertFunction, }) }) } } <file_sep># Deploy 1. Run `npm install` 2. Run `cp .sample.envrc .envrc` and change the value based on needs. Default value should working straight away 3. If you have `direnv`, run `direnv allow`, other wise `source .envrc` 4. Run `npx cdk bootstrap` (optional, when you run `npm run deploy` it will run bootstrap anyway) 5. Run `npx cdk bootstrap --region us-east-1` (optional, if you would like deploy custom resource in us-east-1 as well) 6. Run `npm run deploy` ## Other Commands - `npm run cdk:synth` synth cdk template - `npm run deploy` bootstrap then deploy <file_sep>import * as cdk from '@aws-cdk/core' import * as lambda from '@aws-cdk/aws-lambda' export interface IWafImportsProps { stackName: string, region: string, outputKey: string, } export interface IImportsProps { crossImportFuncArnExportName: string waf: IWafImportsProps } export class Imports extends cdk.Construct { readonly webAclID: cdk.Reference constructor (scope: cdk.Construct, id: string, props: IImportsProps) { super(scope, id) const crossImportFunction = lambda.Function.fromFunctionArn(this, 'CrossImportFunction', cdk.Fn.importValue(props.crossImportFuncArnExportName)) const wafInfo = new cdk.CustomResource(this, 'WafAclResource', { serviceToken: crossImportFunction.functionArn, properties: { StackName: props.waf.stackName, Region: props.waf.region, OutputKey: props.waf.outputKey, } }) this.webAclID = wafInfo.getAtt('OutputValue') } }
3e00dfba4adf0c1a13446da94dff6b60851bef1b
[ "Markdown", "JavaScript", "Makefile", "Go Module", "Python", "TypeScript", "Go" ]
29
Makefile
singlewind/sampleweb
d1b688c79e56470da5d2cbfa2c9ce6cd45501a43
33a6ed0f1588bcd42a909ff7d4623df8e3b01d89
refs/heads/master
<file_sep>/* ################################################################### ** Filename : main.c ** Project : prueba_KL25Z ** Processor : MKL25Z128VLK4 ** Version : Driver 01.01 ** Compiler : GNU C Compiler ** Date/Time : 2014-07-08, 13:59, # CodeGen: 0 ** Abstract : ** Main module. ** This module contains user's application code. ** Settings : ** Contents : ** No public methods ** ** ###################################################################*/ /*!//putada que no sirve ** @file main.c ** @version 01.01 ** @brief ** Main module. ** This module contains user's application code. */ /*! ** @addtogroup main_module main module documentation ** @{ */ /* MODULE main */ /* Including needed modules to compile this module/procedure */ #include "Cpu.h" #include "Events.h" #include "Bit1.h" #include "Bit2.h" #include "Bit3.h" #include "TU1.h" #include "Servo.h" #include "PwmLdd1.h" #include "WAIT1.h" #include "Motors.h" #include "PwmLdd3.h" #include "Camera_Analog.h" #include "AdcLdd1.h" #include "Camera_Clock.h" #include "BitIoLdd3.h" #include "Camera_SI.h" #include "BitIoLdd4.h" /* Including shared modules, which are used for whole project */ #include "PE_Types.h" #include "PE_Error.h" #include "PE_Const.h" #include "IO_Map.h" #define SERVO_LEFT 17800 #define SERVO_RIGHT 19400 #define PIX_MIN 0 #define PIX_MAX 128 uint8_t Camera_Bin[128], u8_Centro = 0; uint8_t Camera_Values[128]; uint8_t Camera_Threshold; word servoduty = 0; uint8_t u8_PixelCntr = 0; /* User includes (#include below this line is not maintained by Processor Expert) */ void delay(uint32_t time){ while(time--){ asm ("nop"); } } void Read_Camera(void){ int i; uint8_t u16_MaxValue = 0, u16_threshold = 0; uint16_t u16_suma = 0; u8_PixelCntr = 0; Camera_SI_SetVal(); Camera_Clock_SetVal(); Camera_Analog_Measure(TRUE); Camera_SI_ClrVal(); for(i=0;i<128;i++){ Camera_Clock_ClrVal(); Camera_Analog_GetValue8(&Camera_Values[i]); delay(60); Camera_Clock_SetVal(); Camera_Analog_Measure(TRUE); if(Camera_Values[i] > u16_MaxValue) { u16_MaxValue = (uint16_t)Camera_Values[i]; } } Camera_Clock_ClrVal(); u16_threshold = (u16_MaxValue/20) * 17; for(i=0;i<128;i++){ if (Camera_Values[i] > u16_threshold){ u16_suma += i; u8_PixelCntr++; } else { Camera_Values[i] = 0; } } if(u8_PixelCntr < 15) u8_Centro = (uint8_t)(u16_suma / u8_PixelCntr); return; } void Servo_Line (uint8_t centro){ servoduty = (word)(SERVO_LEFT + (((SERVO_RIGHT-SERVO_LEFT)/128)*centro)); Servo_SetDutyUS(servoduty); return; } /*lint -save -e970 Disable MISRA rule (6.3) checking. */ int main(void) /*lint -restore Enable MISRA rule (6.3) checking. */ { /* Write your local variable definition here */ int i; /*** Processor Expert internal initialization. DON'T REMOVE THIS CODE!!! ***/ PE_low_level_init(); /*** End of Processor Expert internal initialization. ***/ /* Write your code here */ Camera_Analog_Calibrate(TRUE); for(;;) { Read_Camera(); Servo_Line(u8_Centro); //Servo_SetDutyUS(19500); WAIT1_Waitms(5); } /*** Don't write any code pass this line, or it will be deleted during code generation. ***/ /*** RTOS startup code. Macro PEX_RTOS_START is defined by the RTOS component. DON'T MODIFY THIS CODE!!! ***/ #ifdef PEX_RTOS_START PEX_RTOS_START(); /* Startup of the selected RTOS. Macro is defined by the RTOS component. */ #endif /*** End of RTOS startup code. ***/ /*** Processor Expert end of main routine. DON'T MODIFY THIS CODE!!! ***/ for(;;){} /*** Processor Expert end of main routine. DON'T WRITE CODE BELOW!!! ***/ } /*** End of main routine. DO NOT MODIFY THIS TEXT!!! ***/ /* END main */ /*! ** @} */ /* ** ################################################################### ** ** This file was created by Processor Expert 10.3 [05.09] ** for the Freescale Kinetis series of microcontrollers. ** ** ################################################################### */
36902f55a48056d2e6f71ec1fd6713d530a10f1b
[ "C" ]
1
C
gilrieke/TFC_KL25z
bf30a9847bbaaafcfe07941fa0da014bb34029c3
90e8ac1599d27112fefce5a5ff87d1d37b7a9579
refs/heads/master
<repo_name>GaiusJuliusWtry/ND2_Reader_Wtry<file_sep>/README.md # ND2_Reader_Wtry for windows only ## Import library ``` python from ND2_Reader_Wtry import nd2reader ``` ## Import ND2 file ``` python filename = 'path\\name.nd2' nd2_file = nd2reader.ND2_Reader(f'{filename}') print(f'dimension = {nd2_file.frame_shape} * {nd2_file.experiment_count}') print(f'recording_time = {nd2_file.experiment_time.tm_hour}:{nd2_file.experiment_time.tm_min}:{nd2_file.experiment_time.tm_sec}, {nd2_file.experiment_time.tm_year}/{nd2_file.experiment_time.tm_mon}/{nd2_file.experiment_time.tm_mday}') ``` ## Get images ``` python t = 0 frame = nd2_file.get_frame(time = t, multipoint = 0, z = 0, other = 0) image = frame.image ``` ## File info ``` python print(f'{nd2_file.attributes}') # attributes print(f'{nd2_file.metadata}') # metadata print(f'{nd2_file.experiment}') # experiment print(f'{nd2_file.textinfo}') # textinfo print(f'{nd2_file.binaryinfo}') # binaryinfo print(f'{nd2_file.puiXFields}') # puiXFields print(f'{nd2_file.puiYFields}') # puiYFields print(f'{nd2_file.pdOverlap}') # pdOverlap print(f'{nd2_file.zStackHome}') # zStackHome print(f'{nd2_file.frame_shape}') # frame_shape print(f'{nd2_file.frame_count}') # frame_count print(f'{nd2_file.experiment_count}') # experiment_count print(f'{nd2_file.pixel_type}') # pixel_type print(f'{nd2_file.experiment_time}') # experiment_time ``` ## Close ND2 file ``` python nd2_file.close() ``` <file_sep>/nd2dll.py # import re # file = open('nd2ReadSDK.h', 'r', encoding='utf-8') # file_write = open('nd2.py', 'w') # res = {'void':'None', 'LIMUINT':'ctypes.c_uint', 'LIMINT':'ctypes.c_int', 'LIMRESULT':'ctypes.c_int', 'LIMSIZE':'ctypes.c_size_t', 'LIMFILEHANDLE':'ctypes.c_int'} # arg = {'void*':'ctypes.c_void_p', 'LIMWCHAR':'ctypes.c_wchar', 'LIMWSTR':'ctypes.c_wchar_p', 'LIMCWSTR':'ctypes.c_wchar_p', 'LIMUINT':'ctypes.c_uint', 'LIMUINT*':'ctypes.POINTER(ctypes.c_uint)', 'LIMSIZE':'ctypes.c_size_t', 'LIMINT':'ctypes.c_int', 'LIMBOOL':'ctypes.c_int', 'LIMRESULT':'ctypes.c_int', 'double':'ctypes.c_double', 'double*':'ctypes.POINTER(ctypes.c_double)', 'LIMFILEHANDLE':'ctypes.c_int', 'LIMATTRIBUTES*':'ctypes.POINTER(LIMATTRIBUTES)', 'LIMMETADATA_DESC*':'ctypes.POINTER(LIMMETADATA_DESC)', 'LIMTEXTINFO*':'ctypes.POINTER(LIMTEXTINFO)', 'LIMEXPERIMENT*':'ctypes.POINTER(LIMEXPERIMENT)', 'LIMPICTURE*':'ctypes.POINTER(LIMPICTURE)', 'LIMLOCALMETADATA*':'ctypes.POINTER(LIMLOCALMETADATA)', 'LIMBINARIES*':'ctypes.POINTER(LIMBINARIES)', 'LIMFILEUSEREVENT*':'ctypes.POINTER(LIMFILEUSEREVENT)'} # for line in file: # linearray = re.split("[\t\n, ();]+", line) # if len(linearray) < 3: # continue # elif linearray[0] == 'LIMFILEAPI': # for _ in range(linearray.count('const')): # linearray.remove('const') # for i in range(3, len(linearray) -1 , 2): # if linearray[i] not in ('void*', 'LIMWCHAR', 'LIMWSTR', 'LIMCWSTR', 'LIMUINT', 'LIMUINT*', 'LIMSIZE', 'LIMINT', 'LIMBOOL', 'LIMRESULT', 'double', 'double*', 'LIMFILEHANDLE', 'LIMATTRIBUTES*', 'LIMMETADATA_DESC*', 'LIMTEXTINFO*', 'LIMEXPERIMENT*', 'LIMPICTURE*', 'LIMLOCALMETADATA*', 'LIMBINARIES*', 'LIMFILEUSEREVENT*'): # print(f'arg: {linearray[i]}') # if linearray[1] not in ('void', 'LIMUINT', 'LIMINT', 'LIMRESULT', 'LIMFILEHANDLE', 'LIMSIZE'): # print(f'res: {linearray[1]}') # text = f'\t#{line}' # file_write.write(text) # text = f'\t{linearray[2]} = nd2.{linearray[2]}\n' # file_write.write(text) # text = f'\t{linearray[2]}.argtypes = [' # for i in range(3, len(linearray) -3 , 2): # text = f'{text}{arg[linearray[i]]}, ' # text = f'{text}{arg[linearray[len(linearray) - 3]]}]\n' # file_write.write(text) # text = f'\t{linearray[2]}.restype = {res[linearray[1]]}\n' # file_write.write(text) # file.close() # file_write.close() import ctypes import os import sys os.environ["PATH"] += ';Libraries\\ND2SDK' nd2 = ctypes.windll.LoadLibrary('v6_w32_nd2ReadSDK.dll') LIMMAXBINARIES = 128 LIMMAXPICTUREPLANES = 256 LIMMAXEXPERIMENTLEVEL = 8 LIMSTRETCH_QUICK = 1 LIMSTRETCH_SPLINES = 2 LIMSTRETCH_LINEAR = 3 LIM_ERR = {0: 'LIM_OK', -1: 'LIM_ERR_UNEXPECTED', -2: 'LIM_ERR_NOTIMPL', -3: 'LIM_ERR_OUTOFMEMORY', -4: 'LIM_ERR_INVALIDARG', -5: 'LIM_ERR_NOINTERFACE', -6: 'LIM_ERR_ctypes.POINTER', -7: 'LIM_ERR_HANDLE', -8: 'LIM_ERR_ABORT', -9: 'LIM_ERR_FAIL', -10: 'LIM_ERR_ACCESSDENIED', -11: 'LIM_ERR_OS_FAIL', -12: 'LIM_ERR_NOTINITIALIZED', -13: 'LIM_ERR_NOTFOUND', -14: 'LIM_ERR_IMPL_FAILED', -15: 'LIM_ERR_DLG_CANCELED', -16: 'LIM_ERR_DB_PROC_FAILED', -17: 'LIM_ERR_OUTOFRANGE', -18: 'LIM_ERR_PRIVILEGES', -19: 'LIM_ERR_VERSION'} LIMLOOP = {0: 'LIMLOOP_TIME', 1: 'LIMLOOP_MULTIPOINT', 2: 'LIMLOOP_Z', 3: 'LIMLOOP_OTHER'} class LIMPICTURE(ctypes.Structure): _fields_ = [('uiWidth', ctypes.c_uint), ('uiHeight', ctypes.c_uint), ('uiBitsPerComp', ctypes.c_uint), ('uiComponents', ctypes.c_uint), ('uiWidthBytes', ctypes.c_uint), ('uiSize', ctypes.c_size_t), ('pImageData', ctypes.c_void_p)] class LIMBINARYDESCRIPTOR(ctypes.Structure): _fields_ = [('wszName', ctypes.c_wchar * 256), ('wszCompName', ctypes.c_wchar * 256), ('uiColorRGB', ctypes.c_uint)] class LIMBINARIES(ctypes.Structure): _fields_ = [('uiCount', ctypes.c_uint), ('pDescriptors', LIMBINARYDESCRIPTOR * LIMMAXBINARIES)] class LIMPICTUREPLANE_DESC(ctypes.Structure): _fields_ = [('uiCompCount', ctypes.c_uint), # Number of physical components ('uiColorRGB', ctypes.c_uint), # RGB color for display ('wszName', ctypes.c_wchar * 256), # Name for display ('wszOCName', ctypes.c_wchar * 256), # Name of the Optical Configuration ('dEmissionWL', ctypes.c_double)] class LIMMETADATA_DESC(ctypes.Structure): _fields_ = [('dTimeStart', ctypes.c_double), # Absolute Time in JDN ('dAngle', ctypes.c_double), # Camera Angle ('dCalibration', ctypes.c_double), #um/px (0.0 = uncalibrated) ('dAspect', ctypes.c_double), # pixel aspect (always 1.0) ('wszObjectiveName', ctypes.c_wchar * 256), ('dObjectiveMag', ctypes.c_double), # Optional additional information ('dObjectiveNA', ctypes.c_double), # dCalibration takes into accont all these ('dRefractIndex1', ctypes.c_double), ('dRefractIndex2', ctypes.c_double), ('dPinholeRadius', ctypes.c_double), ('dZoom', ctypes.c_double), ('dProjectiveMag', ctypes.c_double), ('uiImageType', ctypes.c_uint), # 0 (normal), 1 (spectral) ('uiPlaneCount', ctypes.c_uint), # Number of logical planes (uiPlaneCount <= uiComponentCount) ('uiComponentCount', ctypes.c_uint), # Number of physical components (same as uiComp in LIMFILEATTRIBUTES) ('pPlanes', LIMPICTUREPLANE_DESC * LIMMAXPICTUREPLANES)] class LIMTEXTINFO(ctypes.Structure): _fields_ = [('wszImageID', ctypes.c_wchar * 256), ('wszType', ctypes.c_wchar * 256), ('wszGroup', ctypes.c_wchar * 256), ('wszSampleID', ctypes.c_wchar * 256), ('wszAuthor', ctypes.c_wchar * 256), ('wszDescription', ctypes.c_wchar * 4096), ('wszCapturing', ctypes.c_wchar * 4096), ('wszSampling', ctypes.c_wchar * 256), ('wszLocation', ctypes.c_wchar * 256), ('wszDate', ctypes.c_wchar * 256), ('wszConclusion', ctypes.c_wchar * 256), ('wszInfo1', ctypes.c_wchar * 256), ('wszInfo2', ctypes.c_wchar * 256), ('wszOptics', ctypes.c_wchar * 256), ('wszAppVersion', ctypes.c_wchar * 256)] class LIMEXPERIMENTLEVEL(ctypes.Structure): _fields_ = [('uiExpType', ctypes.c_uint), # see LIMLOOP_TIME etc. ('uiLoopSize', ctypes.c_uint), # Number of images in the loop ('dInterval', ctypes.c_double)] # ms (for Time), um (for ZStack), -1.0 (for Multipoint) class LIMEXPERIMENT(ctypes.Structure): _fields_ = [('uiLevelCount', ctypes.c_uint), ('pAllocatedLevels', LIMEXPERIMENTLEVEL * LIMMAXEXPERIMENTLEVEL)] class LIMLOCALMETADATA(ctypes.Structure): _fields_ = [('dTimeMSec', ctypes.c_double), ('dXPos', ctypes.c_double), ('dYPos', ctypes.c_double), ('dZPos', ctypes.c_double)] class LIMATTRIBUTES(ctypes.Structure): _fields_ = [('uiWidth', ctypes.c_uint), # Width of images ('uiWidthBytes', ctypes.c_uint), # Line length 4-byte aligned ('uiHeight', ctypes.c_uint), # Height if images ('uiComp', ctypes.c_uint), # Number of components ('uiBpcInMemory', ctypes.c_uint), # Bits per component 8, 16 or 32 (for float image) ('uiBpcSignificant', ctypes.c_uint), # Bits per component used 8 .. 16 or 32 (for float image) ('uiSequenceCount', ctypes.c_uint), # Number of images in the sequence ('uiTileWidth', ctypes.c_uint), # If an image is tiled size of the tile/strip ('uiTileHeight', ctypes.c_uint), # otherwise both zero ('uiCompression', ctypes.c_uint), # 0 (lossless), 1 (lossy), 2 (None) ('uiQuality', ctypes.c_uint)] # 0 (worst) - 100 (best) class LIMFILEUSEREVENT(ctypes.Structure): _fields_ = [('uiID', ctypes.c_uint), ('dTime', ctypes.c_double), ('wsType', ctypes.c_wchar * 128), ('wsDescription', ctypes.c_wchar * 256)] #LIMFILEAPI LIMFILEHANDLE Lim_FileOpenForRead(LIMCWSTR wszFileName); Lim_FileOpenForRead = nd2.Lim_FileOpenForRead Lim_FileOpenForRead.argtypes = [ctypes.c_wchar_p] Lim_FileOpenForRead.restype = ctypes.c_int #LIMFILEAPI LIMRESULT Lim_FileGetAttributes(LIMFILEHANDLE hFile, LIMATTRIBUTES* pFileAttributes); Lim_FileGetAttributes = nd2.Lim_FileGetAttributes Lim_FileGetAttributes.argtypes = [ctypes.c_int, ctypes.POINTER(LIMATTRIBUTES)] Lim_FileGetAttributes.restype = ctypes.c_int #LIMFILEAPI LIMRESULT Lim_FileGetMetadata(LIMFILEHANDLE hFile, LIMMETADATA_DESC* pFileMetadata); Lim_FileGetMetadata = nd2.Lim_FileGetMetadata Lim_FileGetMetadata.argtypes = [ctypes.c_int, ctypes.POINTER(LIMMETADATA_DESC)] Lim_FileGetMetadata.restype = ctypes.c_int #LIMFILEAPI LIMRESULT Lim_FileGetTextinfo(LIMFILEHANDLE hFile, LIMTEXTINFO* pFileTextinfo); Lim_FileGetTextinfo = nd2.Lim_FileGetTextinfo Lim_FileGetTextinfo.argtypes = [ctypes.c_int, ctypes.POINTER(LIMTEXTINFO)] Lim_FileGetTextinfo.restype = ctypes.c_int #LIMFILEAPI LIMRESULT Lim_FileGetExperiment(LIMFILEHANDLE hFile, LIMEXPERIMENT* pFileExperiment); Lim_FileGetExperiment = nd2.Lim_FileGetExperiment Lim_FileGetExperiment.argtypes = [ctypes.c_int, ctypes.POINTER(LIMEXPERIMENT)] Lim_FileGetExperiment.restype = ctypes.c_int #LIMFILEAPI LIMRESULT Lim_FileGetImageData(LIMFILEHANDLE hFile, LIMUINT uiSeqIndex, LIMPICTURE* pPicture, LIMLOCALMETADATA* pImgInfo); Lim_FileGetImageData = nd2.Lim_FileGetImageData Lim_FileGetImageData.argtypes = [ctypes.c_int, ctypes.c_uint, ctypes.POINTER(LIMPICTURE), ctypes.POINTER(LIMLOCALMETADATA)] Lim_FileGetImageData.restype = ctypes.c_int #LIMFILEAPI LIMRESULT Lim_FileGetImageRectData(LIMFILEHANDLE hFile, LIMUINT uiSeqIndex, LIMUINT uiDstTotalW, LIMUINT uiDstTotalH, LIMUINT uiDstX, LIMUINT uiDstY, LIMUINT uiDstW, LIMUINT uiDstH, void* pBuffer, LIMUINT uiDstLineSize, LIMINT iStretchMode, LIMLOCALMETADATA* pImgInfo); Lim_FileGetImageRectData = nd2.Lim_FileGetImageRectData Lim_FileGetImageRectData.argtypes = [ctypes.c_int, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint, ctypes.c_void_p, ctypes.c_uint, ctypes.c_int, ctypes.POINTER(LIMLOCALMETADATA)] Lim_FileGetImageRectData.restype = ctypes.c_int #LIMFILEAPI LIMRESULT Lim_FileGetBinaryDescriptors(LIMFILEHANDLE hFile, LIMBINARIES* pBinaries); Lim_FileGetBinaryDescriptors = nd2.Lim_FileGetBinaryDescriptors Lim_FileGetBinaryDescriptors.argtypes = [ctypes.c_int, ctypes.POINTER(LIMBINARIES)] Lim_FileGetBinaryDescriptors.restype = ctypes.c_int #LIMFILEAPI LIMRESULT Lim_FileGetBinary(LIMFILEHANDLE hFile, LIMUINT uiSequenceIndex, LIMUINT uiBinaryIndex, LIMPICTURE* pPicture); Lim_FileGetBinary = nd2.Lim_FileGetBinary Lim_FileGetBinary.argtypes = [ctypes.c_int, ctypes.c_uint, ctypes.c_uint, ctypes.POINTER(LIMPICTURE)] Lim_FileGetBinary.restype = ctypes.c_int #LIMFILEAPI LIMRESULT Lim_FileClose(LIMFILEHANDLE hFile); Lim_FileClose = nd2.Lim_FileClose Lim_FileClose.argtypes = [ctypes.c_int] Lim_FileClose.restype = ctypes.c_int #LIMFILEAPI LIMSIZE Lim_InitPicture(LIMPICTURE* pPicture, LIMUINT width, LIMUINT height, LIMUINT bpc, LIMUINT components); Lim_InitPicture = nd2.Lim_InitPicture Lim_InitPicture.argtypes = [ctypes.POINTER(LIMPICTURE), ctypes.c_uint, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint] Lim_InitPicture.restype = ctypes.c_size_t #LIMFILEAPI void Lim_DestroyPicture(LIMPICTURE* pPicture); Lim_DestroyPicture = nd2.Lim_DestroyPicture Lim_DestroyPicture.argtypes = [ctypes.POINTER(LIMPICTURE)] Lim_DestroyPicture.restype = None #LIMFILEAPI LIMUINT Lim_GetSeqIndexFromCoords(LIMEXPERIMENT* pExperiment, LIMUINT* pExpCoords); Lim_GetSeqIndexFromCoords = nd2.Lim_GetSeqIndexFromCoords Lim_GetSeqIndexFromCoords.argtypes = [ctypes.POINTER(LIMEXPERIMENT), ctypes.POINTER(ctypes.c_uint)] Lim_GetSeqIndexFromCoords.restype = ctypes.c_uint #LIMFILEAPI void Lim_GetCoordsFromSeqIndex(LIMEXPERIMENT* pExperiment, LIMUINT uiSeqIdx, LIMUINT* pExpCoords); Lim_GetCoordsFromSeqIndex = nd2.Lim_GetCoordsFromSeqIndex Lim_GetCoordsFromSeqIndex.argtypes = [ctypes.POINTER(LIMEXPERIMENT), ctypes.c_uint, ctypes.POINTER(ctypes.c_uint)] Lim_GetCoordsFromSeqIndex.restype = None #LIMFILEAPI LIMRESULT Lim_GetMultipointName(LIMFILEHANDLE hFile, LIMUINT uiPointIdx, LIMWSTR wstrPointName); Lim_GetMultipointName = nd2.Lim_GetMultipointName Lim_GetMultipointName.argtypes = [ctypes.c_int, ctypes.c_uint, ctypes.c_wchar_p] Lim_GetMultipointName.restype = ctypes.c_int #LIMFILEAPI LIMINT Lim_GetZStackHome(LIMFILEHANDLE hFile); Lim_GetZStackHome = nd2.Lim_GetZStackHome Lim_GetZStackHome.argtypes = [ctypes.c_int] Lim_GetZStackHome.restype = ctypes.c_int #LIMFILEAPI LIMRESULT Lim_GetLargeImageDimensions(LIMFILEHANDLE hFile, LIMUINT* puiXFields, LIMUINT* puiYFields, double* pdOverlap); Lim_GetLargeImageDimensions = nd2.Lim_GetLargeImageDimensions Lim_GetLargeImageDimensions.argtypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_double)] Lim_GetLargeImageDimensions.restype = ctypes.c_int #LIMFILEAPI LIMRESULT Lim_GetRecordedDataInt(LIMFILEHANDLE hFile, LIMCWSTR wszName, LIMINT uiSeqIndex, LIMINT *piData); Lim_GetRecordedDataInt = nd2.Lim_GetRecordedDataInt Lim_GetRecordedDataInt.argtypes = [ctypes.c_int, ctypes.c_wchar_p, ctypes.c_int, ctypes.c_int] Lim_GetRecordedDataInt.restype = ctypes.c_int #LIMFILEAPI LIMRESULT Lim_GetRecordedDataDouble(LIMFILEHANDLE hFile, LIMCWSTR wszName, LIMINT uiSeqIndex, double* pdData); Lim_GetRecordedDataDouble = nd2.Lim_GetRecordedDataDouble Lim_GetRecordedDataDouble.argtypes = [ctypes.c_int, ctypes.c_wchar_p, ctypes.c_int, ctypes.POINTER(ctypes.c_double)] Lim_GetRecordedDataDouble.restype = ctypes.c_int #LIMFILEAPI LIMRESULT Lim_GetRecordedDataString(LIMFILEHANDLE hFile, LIMCWSTR wszName, LIMINT uiSeqIndex, LIMWSTR wszData); Lim_GetRecordedDataString = nd2.Lim_GetRecordedDataString Lim_GetRecordedDataString.argtypes = [ctypes.c_int, ctypes.c_wchar_p, ctypes.c_int, ctypes.c_wchar_p] Lim_GetRecordedDataString.restype = ctypes.c_int #LIMFILEAPI LIMRESULT Lim_GetNextUserEvent(LIMFILEHANDLE hFile, LIMUINT *puiNextID, LIMFILEUSEREVENT* pEventInfo); Lim_GetNextUserEvent = nd2.Lim_GetNextUserEvent Lim_GetNextUserEvent.argtypes = [ctypes.c_int, ctypes.c_uint, ctypes.POINTER(LIMFILEUSEREVENT)] Lim_GetNextUserEvent.restype = ctypes.c_int #LIMFILEAPI LIMINT Lim_GetCustomDataCount(LIMFILEHANDLE hFile); Lim_GetCustomDataCount = nd2.Lim_GetCustomDataCount Lim_GetCustomDataCount.argtypes = [ctypes.c_int] Lim_GetCustomDataCount.restype = ctypes.c_int #LIMFILEAPI LIMRESULT Lim_GetCustomDataInfo(LIMFILEHANDLE hFile, LIMINT uiCustomDataIndex, LIMWSTR wszName, LIMWSTR wszDescription, LIMINT *piType, LIMINT *piFlags); Lim_GetCustomDataInfo = nd2.Lim_GetCustomDataInfo Lim_GetCustomDataInfo.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_int, ctypes.c_int] Lim_GetCustomDataInfo.restype = ctypes.c_int #LIMFILEAPI LIMRESULT Lim_GetCustomDataDouble(LIMFILEHANDLE hFile, LIMINT uiCustomDataIndex, double* pdData); Lim_GetCustomDataDouble = nd2.Lim_GetCustomDataDouble Lim_GetCustomDataDouble.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_double)] Lim_GetCustomDataDouble.restype = ctypes.c_int #LIMFILEAPI LIMRESULT Lim_GetCustomDataString(LIMFILEHANDLE hFile, LIMINT uiCustomDataIndex, LIMWSTR wszData, LIMINT *piLength); Lim_GetCustomDataString = nd2.Lim_GetCustomDataString Lim_GetCustomDataString.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_wchar_p, ctypes.c_int] Lim_GetCustomDataString.restype = ctypes.c_int #LIMFILEAPI LIMRESULT Lim_GetStageCoordinates(LIMFILEHANDLE hFile, LIMUINT uiPosCount, LIMUINT* puiSeqIdx, LIMUINT* puiXPos, LIMUINT* puiYPos, double* pdXPos, double *pdYPos, double *pdZPos, LIMINT iUseAlignment); Lim_GetStageCoordinates = nd2.Lim_GetStageCoordinates Lim_GetStageCoordinates.argtypes = [ctypes.c_int, ctypes.c_uint, ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.c_int] Lim_GetStageCoordinates.restype = ctypes.c_int #LIMFILEAPI LIMRESULT Lim_SetStageAlignment(LIMFILEHANDLE hFile, LIMUINT uiPosCount, double* pdXSrc, double* pdYSrc, double* pdXDst, double *pdYDst); Lim_SetStageAlignment = nd2.Lim_SetStageAlignment Lim_SetStageAlignment.argtypes = [ctypes.c_int, ctypes.c_uint, ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double)] Lim_SetStageAlignment.restype = ctypes.c_int #LIMFILEAPI LIMRESULT Lim_GetAlignmentPoints(LIMFILEHANDLE hFile, LIMUINT* puiPosCount, LIMUINT* puiSeqIdx, LIMUINT* puiXPos, LIMUINT* puiYPos, double *pdXPos, double *pdYPos); # In this function, the value pdXPos and pdYPos should be arrays, which means the call would return in error Lim_GetAlignmentPoints = nd2.Lim_GetAlignmentPoints Lim_GetAlignmentPoints.argtypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double)] Lim_GetAlignmentPoints.restype = ctypes.c_int <file_sep>/nd2reader.py from Libraries import nd2dll import ctypes import os import sys import time import numpy import re class ND2_frame: image = None x = 0.0 # um y = 0.0 # um z = 0.0 # um t = 0.0 # ms def __init__(self, image, x, y, z, t): self.image = image self.x = x self.y = y self.z = z self.t = t class ND2_Reader: handle = None attributes = nd2dll.LIMATTRIBUTES() metadata = nd2dll.LIMMETADATA_DESC() # Global metadata, here contains the pixel size, the objective magnification and NA, components color, etc. However those information might be incorrect, there for those feature should be assigned manually. experiment = nd2dll.LIMEXPERIMENT() textinfo = nd2dll.LIMTEXTINFO() # The exposure time and other important features are contained in 'wszCapturing' and 'wszDescription', however maybe it is more convenient to just record them down. See function print_description. binaryinfo = nd2dll.LIMBINARIES() puiXFields = ctypes.c_uint(0) # Large Image Dimensions puiYFields = ctypes.c_uint(0) # Large Image Dimensions pdOverlap = ctypes.c_double(0) # Large Image Dimensions zStackHome = ctypes.c_uint(0) frame_shape = None frame_count = 0 experiment_count = [0, 0, 0, 0] pixel_type = numpy.uint16 # experiment_time = time.gmtime() experiment_time = None def __init__(self, filename): # open handle self.handle = nd2dll.Lim_FileOpenForRead(filename) # obtain attributes, metadata, experiment, text, and binary information nd2dll.Lim_FileGetAttributes(self.handle, self.attributes) nd2dll.Lim_FileGetMetadata(self.handle, self.metadata) nd2dll.Lim_FileGetExperiment(self.handle, self.experiment) nd2dll.Lim_FileGetTextinfo(self.handle, self.textinfo) nd2dll.Lim_FileGetBinaryDescriptors(self.handle, self.binaryinfo) nd2dll.Lim_GetLargeImageDimensions(self.handle, self.puiXFields, self.puiYFields, self.pdOverlap) # I still don't know what exactly the function Lim_GetAlignmentPoints does, whereas the possible bug has been described in 'nd2dll.py' self.zStackHome = ctypes.c_uint(nd2dll.Lim_GetZStackHome(self.handle)) # capture main features if self.attributes.uiComp > 1: self.frame_shape = (self.attributes.uiHeight, self.attributes.uiWidth, self.attributes.uiComp) else: self.frame_shape = (self.attributes.uiHeight, self.attributes.uiWidth) self.frame_count = self.attributes.uiSequenceCount for i in range(self.experiment.uiLevelCount): self.experiment_count[self.experiment.pAllocatedLevels[i].uiExpType] = self.experiment.pAllocatedLevels[i].uiLoopSize ## I should write a check point to calculate if frame_count = Pi(experiment_count[i] != 0) self.pixel_type = {8: numpy.uint8, 16: numpy.uint16, 32: numpy.float32}[self.attributes.uiBpcInMemory] try: self.experiment_time = time.strptime(self.textinfo.wszDate, '%Y/%m/%d %H:%M:%S') except: try: self.experiment_time = time.strptime(self.textinfo.wszDate, '%m/%d/%Y %I:%M:%S %p') except: self.experiment_time = time.strptime( re.split(' ', self.textinfo.wszDate)[2], '%H:%M:%S') def print_description(self): print(self.textinfo.wszCapturing) print() print(self.textinfo.wszDescription) def get_frame(self, time, multipoint, z, other): # initialize read buffers and metadata buf_picture = nd2dll.LIMPICTURE() buf_picture_size = nd2dll.Lim_InitPicture(buf_picture, self.attributes.uiWidth, self.attributes.uiHeight, self.attributes.uiBpcInMemory, self.attributes.uiComp) buf_metadata = nd2dll.LIMLOCALMETADATA() array_shape = self.attributes.uiWidth * self.attributes.uiHeight * self.attributes.uiComp array_size = {8: ctypes.c_uint8, 16: ctypes.c_uint16, 32: ctypes.c_float}[self.attributes.uiBpcInMemory] * array_shape seq_index = nd2dll.Lim_GetSeqIndexFromCoords(self.experiment, (ctypes.c_uint * 4)(time, multipoint, z, other)) # or Lim_GetCoordsFromSeqIndex() nd2dll.Lim_FileGetImageData(self.handle, seq_index, buf_picture, buf_metadata) image = numpy.ndarray(self.frame_shape, self.pixel_type, array_size.from_address(buf_picture.pImageData)).copy() frame = ND2_frame(image, buf_metadata.dXPos, buf_metadata.dYPos, buf_metadata.dZPos, buf_metadata.dTimeMSec) # release memory nd2dll.Lim_DestroyPicture(buf_picture) del image, buf_picture return(frame) def close(self): if self.handle: # self.nd2.Lim_DestroyPicture(self.buf_p) nd2dll.Lim_FileClose(self.handle) self.handle = None
b945c5c3ed26e17dc044961f12c9cc7ee607bc7f
[ "Markdown", "Python" ]
3
Markdown
GaiusJuliusWtry/ND2_Reader_Wtry
99e13be8905ff7df1b7b6fc555a7e7e4b0bdab99
cf56a531d533b4298be0e0073795b20e2a922904
refs/heads/master
<file_sep>Welcome to the Coordinates Module! This module deals with anything that has to deal with coordinate planes, such as slope, generating coordinate planes, etc.<file_sep>"""Coordinates Module, made by <NAME>.""" """To Do: Abs. Value, Perpendicular/Parallel, Exponents, Inequalities, Geometry""" __author__ = "<NAME>" class point(object): """Coordinate Point Object. The following parameters could be inputted: x-coordinate, y-coordinate, and data values.""" def __init__(self, x, y, *data): test = (int, float) if isinstance(x, test) and isinstance(y, test): self.x = x self.y = y self.data = data else: raise ValueError("x/y values are not compatible.") def __repr__(self): x, y = self.x, self.y data = map(str, self.data) rep = "(%s, %s, " % (x, y) rep += "[" + ", ".join(data) + "]" + ")" return rep def add(self, *info): """Adds inputted data to list of point's data values""" data = list(self.data) for i in info: data.append(i) self.data = tuple(data) def delete(self, *info): data = list(self.data) for i in info: if i in data: data.remove(i) self.data = tuple(data) def translate(self, x, y=0): test = (int, float) if isinstance(x, test) and isinstance(y, test): self.x += x self.y += y else: raise ValueError("x/y values are not compatible.") def generate(num, quad=1): """Creates a Coordinate plane. The plane that is generated has the x & y values less than the inputed 'num' paramater. You can also input which quadrant your points can come from. If you input 'all', the function returns a list of all points from all quadrants. The quadrant parameter is labeled 'quad'.""" if not isinstance(num, int) or num < 0: raise ValueError("Inputted 'num' Value is not an integer or greater than 0.") elif quad not in [1, 2, 3, 4, "all"]: raise ValueError("Inputed 'quad' value not 1-4/'all'") def negate(q): x_range, y_range = range(num), range(num) neg = range(-num + 1, 1) if q == 2: x_range = neg if q == 3: x_range, y_range = neg, neg if q == 4: y_range = neg return {"x_range": x_range, "y_range": y_range} plane = [] if quad != "all": x_range = negate(quad)["x_range"] y_range = negate(quad)["y_range"] for x in x_range: for y in y_range: plane.append((x, y)) else: for i in range(1, 5): x_range = negate(i)["x_range"] y_range = negate(i)["y_range"] for x in x_range: for y in y_range: point = (x, y) if point not in plane: plane.append((point)) return plane def slope(p1, p2, fract=True): """Returns the Slope of points p1 and p2. p1 and p2 must be tuples with 2 integers. There is an optional 'fract' parameter. If 'fract' equals True (default), the function returns the slope as a Fraction object from the fractions module. If False, the function returns a string. If the slope is an undefined slope (#/0), the 'fract' value is overriden to False, and a string is returned. Note: As though this program can calculate slopes in the form of decimals, the fractions module will not be able to convert the slope into a Fraction. Therefore, the 'fract' parameter would be overriden to False. Note: Non-Fraction-Object slopes are not simplified, whereas Fraction-Object slopes are simplified.""" if isinstance(p1, tuple) and isinstance(p2, tuple): token = False if len(p1) != 2 or len(p2) != 2: token = True for i in [p1, p2]: for x in i: if not isinstance(x, (int, float)): token = True if token: raise ValueError("Tuple Values are not capable for slope calculation.") else: raise ValueError("Values are not capable for slope calculation.") if fract not in [True, False]: raise ValueError("'fract' value is not True/False") from fractions import Fraction xDif = p2[0] - p1[0] yDif = p2[1] - p1[1] if xDif == 0: fract = False elif isinstance(xDif, float) or isinstance(yDif, float): fract = False if fract: obj = Fraction(yDif, xDif) else: obj = "%s/%s" % (yDif, xDif) return obj def on_slope(p, slope, intercept=0): """Determines if the given 'p' point is on a line with a slope of the 'slope' parameter. Note: The slope parameter must be in string form. There is also an optional 'intercept' parameter, which defaults to 0.""" from re import match if isinstance(p, tuple) and len(p) == 2: token = False for i in p: if not isinstance(i, (int, float)): token = True if token: raise ValueError("Tuple Values are not capable to work with.") else: raise ValueError("'p' Value is not capable to work with.") if not isinstance(intercept, (int, float)): raise ValueError("'intercept' value is not int or float.") x, y = p[0], p[1] patt = r'-?\d+(.\d+)? */ *-?\d+(.\d+)?' if not match(patt, slope): raise ValueError("Input is not Fraction") else: new_val = slope.split('/') new_val = map(lambda x: x.strip(), new_val) new_val = map(float, new_val) slope = new_val[0] / new_val[1] return bool(y == (slope * x) + intercept) def on_inequality(p, sign, slope, intercept=0): """Determines if the given 'p' point that is either greater, less, greater or equal, lesser or equal, to the slope. The 'sign' parameter can be any of the following: '<', '<=', '>', or '>='. Note: The slope parameter must be in string form. There is also an optional 'intercept' parameter, which defaults to 0.""" from re import match if isinstance(p, tuple) and len(p) == 2: token = False for i in p: if not isinstance(i, (int, float)): token = True if token: raise ValueError("Tuple Values are not capable to work with.") else: raise ValueError("'p' Value is not capable to work with.") if sign not in ["<", "<=", ">", ">="]: raise ValueError("'sign' Value is invalid.") if not isinstance(intercept, (int, float)): raise ValueError("'intercept' value is not int or float.") x, y = p[0], p[1] patt = r'-?\d+(.\d+)? */ *-?\d+(.\d+)?' if not match(patt, slope): raise ValueError("Input is not Fraction") else: new_val = slope.split('/') new_val = map(lambda x: x.strip(), new_val) new_val = map(float, new_val) slope = new_val[0] / new_val[1] result = eval("y %s (slope * x) + intercept" % sign) return bool(result) def distance(p1, p2): """Calculates the distance between 'p1' and 'p2'. 'p1' and 'p2' can be either a tuple or integer, but both must be the same type.""" if isinstance(p1, tuple) and isinstance(p2, tuple): token = False reg = True if len(p1) != 2 or len(p2) != 2: token = True for i in [p1, p2]: for x in i: if not isinstance(x, (int, float)): token = True if token: raise ValueError("Tuple Values are not capable for distance calculation.") elif isinstance(p1, (int, float)) and isinstance(p2, (int, float)): reg = False else: raise ValueError("Values are not capable for distance calculation.") if reg: from math import sqrt x1, y1, x2, y2 = p1 + p2 add1 = (x2 - x1) ** 2 add2 = (y2 - y1) ** 2 dist = sqrt(add1 + add2) else: from math import fabs dist = fabs(p1) + fabs(p2) return dist def midpoint(p1, p2): """Calculates the midpoint between 'p1' and 'p2'. 'p1' and 'p2' can be either a tuple or integer, but both must be the same type.""" if isinstance(p1, tuple) and isinstance(p2, tuple): token = False reg = True if len(p1) != 2 or len(p2) != 2: token = True for i in [p1, p2]: for x in i: if not isinstance(x, (int, float)): token = True if token: raise ValueError("Tuple Values are not capable for distance calculation.") elif isinstance(p1, (int, float)) and isinstance(p2, (int, float)): reg = False else: raise ValueError("Values are not capable for distance calculation.") if reg: x1, y1, x2, y2 = p1 + p2 x = (x1 + x2) / 2.0 y = (y1 + y2) / 2.0 mid = (x, y) else: mid = (p1 + p2) / 2.0 return mid def vertex(a, b, c): """Returns a vertex point of the given parabola equation. Note: the 'x' value of the returned point is the line of symmetry.""" for i in [a, b, c]: if not isinstance(i, (int, float)): raise ValueError("Inputted value(s) are not integers.") line = float(b) / (2 * a) line = -line a *= line ** 2 b *= line return (line, a + b + c)
f0a2bb0100068f65dfa5fe58d0f889336b593c6d
[ "Markdown", "Python" ]
2
Markdown
JKodner/coords
796ea532e4083db2a070f77c6c4b007360c9974c
a74470abb21e86f27a20b21ea6e6fe5b570ba6d7
refs/heads/master
<file_sep>#include <iostream> #include <fstream> #include "lab2.h" using namespace std; int main() { int k, realA, realB; double as_a,as_b; string start; Game score_cal, rate_cal; ifstream inFile("file.in",ios::in); ofstream outFile("file.out", ios::out); inFile >> k >> realA >> realB; outFile << realA << "\t" << realB << "\t" << endl; while(inFile >> as_a) { if(as_a == 1) as_b = 0; else if(as_a == 0) as_b = 1; else if(as_a == 0.5) as_b = 0.5; double ex_a = score_cal.Expected_scoreA(realA,realB); double ex_b = score_cal.Expected_scoreB(realA,realB); int R_A = rate_cal.RatingA(realA, k, as_a, ex_a); int R_B = rate_cal.RatingB(realB, k, as_b, ex_b); realA = R_A; realB = R_B; outFile << R_A << "\t" << R_B << endl; } return 0; } <file_sep># lab2 # g++ -c main.cpp # g++ -c lab2.cpp #g++ -o lab2 lab2.cpp main.cpp #make #./lab2 <file_sep>using namespace std; class Game { public: double Expected_scoreA(int r_a,int r_b); double Expected_scoreB(int r_a,int r_b); int RatingA(int r_a, int k, double a_a, double e_a); int RatingB(int r_b, int k, double a_b, double e_b); private: int r_a, r_b; double e_a, e_b,a_a,a_b; }; <file_sep>#include "lab2.h" #include <cmath> using namespace std; double Game::Expected_scoreA(int r_A,int r_B) { double E_a = 1/ (1+ pow(10, ((double)r_B-r_A)/400)); return E_a; } double Game::Expected_scoreB(int r_A, int r_B) { double E_b = 1/ (1+ pow(10, ((double)r_A-r_B)/400)); return E_b; } int Game::RatingA(int r_A, int k, double as_a, double E_a) { double rate_A = r_A + k * (as_a - E_a) + 0.5; return rate_A; } int Game::RatingB(int r_B, int k, double as_b, double E_b) { double rate_B = r_B + k * (as_b - E_b)+ 0.5; return rate_B; }
7eee1e3f004cbcb87002a75d471a06b037d17cfc
[ "Markdown", "C++" ]
4
C++
VoonShin/lab2
0da0a8d039e133d8bb171f7f57a588ff2a54d9d5
bf9186e82b53b6f1c04169b7508456752d317e63
refs/heads/master
<file_sep>'use strict'; /** * Code 201 Lab 02 Ask user for their name. * Keep tally of correct answers the user gives to questions. */ var name = prompt('Hi what\'s your name?'); var tally = 0; var QUESTIONS = 7; tally = aboutMeQuestions(tally); tally = question6And7(tally); alert('Thank you for playing my About Me game. You guessed ' + tally + '/' + QUESTIONS + ' questions right.'); /** * Code 201 Lab 02 'About Me' statements. */ function aboutMeQuestions(tally) { var aboutMe = [ 'As an athlete, I want to workout, so I can be healthy', 'As I like to eat healthy food, I want to diet, so I can be slim', 'As I want to be a good reader, I want to read books, so I can read great writing effortlessly', 'As I want to live on Mars, I want to be an astronaut, so I can work on Mars', 'As I like to play badminton regularly on Sunday nights, I want to keep my racket strung strongly, so I can string through the night' ]; for (var i = 0; i < aboutMe.length; i++) { var text = aboutMe[i] + '. I\'m telling the truth. Do you agree? Type \'Y\', \'N\' or yes/no.'; var answer = prompt(text); if (answer) { answer = answer.toLowerCase()[0]; } else { console.log('You didn\'t give me an answer'); continue; } if (i === 0) { if (answer === 'y') { console.log('You\'re right! As an athlete, I want to workout, so I can be healthy'); tally++; } else { console.log('But what I said is true. As an athlete, I want to workout, so I can be healthy'); } } else if (i === 1) { if (answer === 'y') { console.log('You\'re right! As I like to eat healthy food, I want to diet, so I can be slim'); tally++; } else { console.log('But what I said is true. As I like to eat healthy food, I want to diet, so I can be slim'); } } else if (i === 2) { if (answer === 'y') { console.log('You\'re right! As I want to be a good reader, I want to read books, so I can read great writing effortlessly'); tally++; } else { console.log('But what I said is true. As I want to be a good reader, I want to read books, so I can read great writing effortlessly'); } } else if (i === 3) { if (answer === 'y') { console.log('No. What I said is: \"As I want to live on Mars, I want to be an astronaut, so I can work on Mars\", but what I said isn\'t true'); tally++; } else { console.log('You\'re right. I wasn\'t really telling the truth'); } } else if (i === 4) { if (answer === 'y') { console.log('No. What I said is: \"As I like to play badminton regularly on Sunday nights, I want to keep my racket strung strongly, so I can string through the night\", but what I said isn\'t true'); tally++; } else { console.log('You\'re right. What I said is: \"As I like to play badminton regularly on Sunday nights, I want to keep my racket strung strongly, so I can string through the night\", which isn\'t true'); } } } return tally; } /** * Code 201 Lab 03 Guessing my favorite number. * Code 201 Lab 03 Guessing a city I've lived in */ /** * Code 201 Lab 03 Guessing a city I've lived in */ function question6And7(tally) { // question6 var favoriteNumber = 5; var FAVORITE_NUMBER_MAX_GUESSES = 4; for (var i = 1; i <= FAVORITE_NUMBER_MAX_GUESSES; i++) { var guess = prompt('Can you guess my favorite number? You have ' + (FAVORITE_NUMBER_MAX_GUESSES - i + 1) + ' guesses to guess my favorite number.'); if (isNaN(parseInt(guess))) { alert('You need to guess a number.'); i--; continue; } guess = parseInt(guess); if (guess === favoriteNumber) { alert('You guessed my favorite number right on guess number ' + i + '!'); tally++; break; } else if (guess < favoriteNumber) { alert('You guessed a number less than my favorite number on guess number ' + i + '. You have ' + (FAVORITE_NUMBER_MAX_GUESSES - i) + ' guesses left to guess my favorite number.'); } else { alert('You guessed a number greater than my favorite number on guess number ' + i + '. You have ' + (FAVORITE_NUMBER_MAX_GUESSES - i) + ' guesses left to guess my favorite number.'); } if (i === FAVORITE_NUMBER_MAX_GUESSES) { alert('You didn\'t guess my favorite number. My favorite number is 5.'); } } // question7 var citiesHoused = ['Portland', 'St. Johns', 'St. Louis']; var CITIES_HOUSED_MAX_GUESSES = 6; for (var i = 1; i <= CITIES_HOUSED_MAX_GUESSES; i++) { var guess = prompt('Can you guess a city I\'ve lived in other than Seattle? You have ' + (CITIES_HOUSED_MAX_GUESSES - i + 1) + ' guesses to guess a city I\'ve lived in other than Seattle.'); if (!isNaN(parseInt(guess))) { alert('You can\'t guess with a number.'); i--; continue; } if (guess === '') { alert('You need to guess a city.'); i--; continue; } if (guess === 'Seattle') { alert('You need to guess a city other than Seattle.'); i--; continue; } var rightGuess = false; for (var j = 0; j < citiesHoused.length; j++) { if (guess === citiesHoused[j]) { alert('You guessed a city I\'ve lived in other than Seattle! You guessed ' + guess + ' and you\'re right! You guessed right on guess number ' + i + '.'); tally++; rightGuess = true; break; } } if (rightGuess) { break; } else { if (i === CITIES_HOUSED_MAX_GUESSES) { alert('You didn\'t guess another city I\'ve lived in other than Seattle. The cities I\'ve lived in other than Seattle are Portland, St. Johns and St. Louis.'); } else { alert(guess + ' isn\'t a city I\'ve lived in.'); } } } return tally; } <file_sep># lab02 Code 201 Lab 02 repository ## Acknowledgements Thank you for all the great work done to get the project here made.
af35c7998de50e6bc5fcae52bdb52c44c39ffe85
[ "JavaScript", "Markdown" ]
2
JavaScript
biniamsea2/code-201-lab-02
07ebb3c96e2329b73f2c10adf8fac5197f3735a4
a61b779dfb348eaca0f479a010bfc868767a2a2a
refs/heads/master
<repo_name>zuoshangjiaoyu/jqkt<file_sep>/README.md # jinqiuzhiku 金秋课堂APP <file_sep>/src/components/tabBar/tabBar.js import React, { Component } from 'react'; import {View, Button, Text} from 'react-native'; <file_sep>/src/components/search/searchInput.js import React, { Component } from 'react'; import {View, Text, Image, TextInput, StyleSheet, TouchableHighlight, TouchableOpacity} from "react-native"; import {scaleHeight, setSpText2, scaleSize } from "../../lib/styleAdaptation"; import PropTypes from 'prop-types'; // import searchStyle from './searchStyle' class SearchInput extends Component { static propTypes = { whereToGo: PropTypes.func, canNavigate: PropTypes.bool, placeholderTxt: PropTypes.string, inputStyle: PropTypes.object, searchContainer: PropTypes.object }; constructor (props){ super(props) } renderNavigationToSearch() { if (this.props.whereToGo === undefined) return; return this.props.whereToGo(); } render(): React.ReactNode { return ( <View style={[inputStyle.inputContainer,this.props.searchContainer]}> <Image style={inputStyle.searchIcon} source={require('../../images/search_icon.png')} resizeMode={'stretch'}/> {this.props.canNavigate && <TouchableOpacity onPress={()=>{this.renderNavigationToSearch()}} > <Text>{this.props.placeholderTxt}</Text> </TouchableOpacity> } {!this.props.canNavigate && <TextInput placeholder={this.props.placeholderTxt} style={[inputStyle.placeholderFontStyle]} /> } </View> ); } } const inputStyle = StyleSheet.create({ inputContainer: { height: scaleHeight(32), justifyContent: 'center', flexDirection: 'row', alignItems: 'center', backgroundColor: '#F0F1F2FF', borderRadius: scaleSize(16), }, searchIcon: { width: scaleSize(15), height: scaleHeight(16), marginRight: scaleSize(6) }, placeholderFontStyle: { fontSize: setSpText2(14), fontFamily: 'PingFang-SC-Medium', fontWeight: '500', color:'rgba(136,136,136,1)', margin: 0, padding: 0 }, }) export default SearchInput; <file_sep>/src/components/search/searchStyle.js import { StyleSheet } from 'react-native'; import {scaleHeight, setSpText2, scaleSize } from "../../lib/styleAdaptation"; const searchStyle = StyleSheet.create({ }) export default searchStyle; <file_sep>/src/containers/thinking/thinkScreen.js import React, { Component } from 'react'; import { View, Text, StyleSheet, Image, ScrollView, Alert, TouchableOpacity, Button, TouchableHighlight} from 'react-native'; import thinkStyle from './thinkStyle'; import TopScreen from "../../components/topScreen/topScreen"; class ThinkScreen extends Component { render(){ return ( <View> <TopScreen title={'思维课'} leftItem={() => this.props.navigation.goBack()} rightTxt={'课程介绍'} rightItem={() => {this.props.navigation.navigate('ThinkIntroduction')}} /> <ScrollView style={thinkStyle.container} > <View style={thinkStyle.banner}> <Image style={[thinkStyle.image]} resizeMode='stretch' source={require('../../images/testOne.png')} /> </View> <View style={[thinkStyle.itemList]}> <View style={[thinkStyle.item]} > <TouchableOpacity activeOpacity={1} onPress={()=>{this.props.navigation.navigate('Think')}}> <Image style={[thinkStyle.itemImage]} resizeMode='stretch' source={require('../../images/testOne.png')} /> <Text style={[thinkStyle.itemSee]}>580人观看</Text> <View style={[thinkStyle.itemContent]}> <Text style={[thinkStyle.itemTitle]}>变现商学院的价值</Text> <Text style={[thinkStyle.itemName]}>李攀 | 变现商学院创始人</Text> <View style={[thinkStyle.itemSign]}> <Text style={[thinkStyle.itemSignText]}>供应链</Text> <Text style={[thinkStyle.itemSignText]}>资源优化</Text> </View> </View> </TouchableOpacity> </View> <View style={[thinkStyle.item]}> <Image style={[thinkStyle.itemImage]} resizeMode='stretch' source={require('../../images/testOne.png')} /> <Text style={[thinkStyle.itemSee]}>2万人观看</Text> <View style={[thinkStyle.itemContent]}> <Text style={[thinkStyle.itemTitle]}>变现商学院的价值</Text> <Text style={[thinkStyle.itemName]}>李攀 | 变现商学院创始人</Text> <View style={[thinkStyle.itemSign]}> <Text style={[thinkStyle.itemSignText]}>供应链</Text> <Text style={[thinkStyle.itemSignText]}>资源优化</Text> </View> </View> </View> <View style={[thinkStyle.item]}> <Image style={[thinkStyle.itemImage]} resizeMode='stretch' source={require('../../images/testOne.png')} /> <Text style={[thinkStyle.itemSee]}>2千人观看</Text> <View style={[thinkStyle.itemContent]}> <Text style={[thinkStyle.itemTitle]}>变现商学院的价值</Text> <Text style={[thinkStyle.itemName]}>李攀 | 变现商学院创始人</Text> <View style={[thinkStyle.itemSign]}> <Text style={[thinkStyle.itemSignText]}>供应链</Text> <Text style={[thinkStyle.itemSignText]}>资源优化</Text> </View> </View> </View> </View> </ScrollView> </View> ); } } export default ThinkScreen; <file_sep>/src/containers/home/indexScreen.js import React, { Component } from 'react'; import indexStyle from './indexStyle'; import BannerComponent from '../../components/banner/bannerComponent'; import FileUpload from "../../components/upload/fileUpload"; import MapScreen from '../../components/map/mapScreen'; import AliPay from '../../components/payment/aliPay' import { Text, View, Alert, ScrollView, TouchableOpacity, Modal, Button } from 'react-native'; import ShowToast from "../../components/showToast/showToast"; class IndexScreen extends Component { constructor(props) { super(props); this.state = { text: 'Useless Placeholder', searchIcon: require('../../images/search_icon.png'), isShow: false, modal: false }; } changeShowToast (){ this.setState({ isShow: false }) } _aliPay() { let data = '1234'; AliPay.pay(data) } render(): React.ReactNode { console.log(['indexScreen',this.state.isShow]) return ( <View> <ScrollView > <ShowToast isShow={this.state.isShow} changeToast={this.changeShowToast.bind(this)}/> <TouchableOpacity onPress={()=> this.setState({ isShow: true })}> <Text >调用showToast</Text> </TouchableOpacity> <TouchableOpacity onPress={this._aliPay}> <Text >调用支付宝支付</Text> </TouchableOpacity> </ScrollView> </View> ); } } export default IndexScreen; <file_sep>/src/components/map/mapScreen.js import React, { Component } from 'react'; import ActionSheet from 'react-native-general-actionsheet'; import { Platform, StyleSheet, Text, View, TouchableOpacity, NativeModules, Alert, ScrollView, ActionSheetIOS } from 'react-native'; let lon = '121.2477511168'; // ---经度 121.248078 let lat = '31.0913734181'; // ---纬度 31.091769 let name = '上海松江王家厍路55弄';// let UtilMapManager = NativeModules.UtilMap; class MapScreen extends Component { constructor(props) { super(props); this.state = { text: 'Useless Placeholder', searchIcon: require('../../images/search_icon.png') }; } iosmap() { // console.error(Platform); let array = []; UtilMapManager.findEvents(lon, lat, name, (events) => { events.map((index, item) => { array.push(index.title); }) if(Platform.OS === 'ios'){ if (array.length > 2) { ActionSheetIOS.showActionSheetWithOptions({ options: array, cancelButtonIndex: array.length - 1, maskClosable: true, }, (buttonIndex) => { //跳到原生方法对应的app地图导航内 UtilMapManager.addEvent(events[buttonIndex].title, events[buttonIndex].url, lon, lat, name);//lon是经度,,,log是维度 }); } else if (array.length == 2) { if (events.length == 2 && events[0].url == 'ios') { //只针对ios平台 UtilMapManager.addEvent(events[0].title, events[0].url, lon, lat, name); } else { console.log(['android',array]) ActionSheetIOS.showActionSheetWithOptions({ options: array, cancelButtonIndex: array.length - 1, maskClosable: true, }, (buttonIndex) => { //跳到原生方法对应的app地图导航内 UtilMapManager.addEvent(events[buttonIndex].title, events[buttonIndex].url, lon, lat, name);//lon是经度,log是维度 }); } } else {//只适用于android平台 Alert.alert('没有可用的地图软件!'); } }else { ActionSheet.useActionSheetIOS = false; ActionSheet.showActionSheetWithOptions({ options: array, cancelButtonIndex: array.length - 1, maskClosable: true, },(buttonIndex) => { console.log(['buttonIndex',buttonIndex,lon,lat,name]) //跳到原生方法对应的app地图导航内 UtilMapManager.addEvent(events[buttonIndex].title, events[buttonIndex].url, lon, lat, name);//lon是经度,log是维度 }); } }) } render(): React.ReactNode { return ( <View style={styles.container}> <TouchableOpacity style={{ marginTop: 50 }} onPress={this.iosmap.bind(this)}> <Text>打开导航软件</Text> </TouchableOpacity> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); export default MapScreen; <file_sep>/src/containers/login/loginStyle.js import {scaleHeight, scaleSize, setSpText2} from "../../lib/styleAdaptation"; import { StyleSheet } from 'react-native'; import BaseStyle from '../../lib/baseStyle'; const LoginStyle = StyleSheet.create({ container: { flex: 1, backgroundColor: BaseStyle.themeColor, }, logoContainer: { alignSelf: 'center', marginTop: scaleHeight(40) }, logoImgStyle: { width: scaleSize(70), height: scaleSize(70), marginBottom: scaleHeight(13), backgroundColor: '#fff', borderRadius: scaleSize(70), }, logoTxt: { fontSize: setSpText2(20), fontFamily: 'PingFang-SC-Bold', fontWeight: 'bold', color: 'rgba(52,57,78,1)', lineHeight: scaleHeight(36) }, testStyle: { width: scaleSize(70), height: scaleSize(70), backgroundColor: '#fff', borderRadius: scaleSize(70) } }) export default LoginStyle; <file_sep>/src/lib/baseStyle.js import {StyleSheet} from "react-native"; import Dimen from './dimen'; import {Platform} from 'react-native'; import deviceInfo from './deviceInfo'; const BaseStyle = { /** color **/ clear: 'transparent', /** 主题色 **/ themeColor: '#f2f5f7', // 默认文本主色调 (黄) textMainColor: '#F0B95BFF', // 默认背景颜色 bgColor: '#f2f3f5ff', // 默认背景辅颜色 (HOT) bgFuColor: '#F54E36FF', // 默认标题第一级颜色 (黑) textTitleColor: '#333333FF', // 默认标题第一级半颜色 textFirstTitleColor: '#3A3A3AFF', // 默认标题第二级颜色 textSecTitleColor: '#666666FF', // 默认标题第二级颜色 textThirdTitleColor: '#999999FF', // 默认红色颜色 redColor: '#F54E36FF', // 默认分割线颜色 lineColor: 'rgba(0,0,0,0.1)', // 默认placeholder颜色 placeholderTextColor: '#c8c8cd', /** space **/ // 上边距 marginTop: 10, // 左边距 marginLeft: 10, // 下边距 marginBotton: 10, // 右边距 marginRight: 10, // 内边距 padding: 10, // 左padding paddingLeft: 15, // 导航的leftItem的左间距 navMarginLeft: 15, // 导航的rightItem的右间距 navMarginRight: 15, /** width **/ // 导航栏左右按钮image宽度 navImageWidth: 25, // 边框线宽度 borderWidth: 1, // 分割线高度 lineWidth: 0.8, /** height **/ // 导航栏的高度 navHeight: Platform.OS === 'ios' ? (deviceInfo.isIphoneX ? 88 : 64) : 56, // 导航栏顶部的状态栏高度 navStatusBarHeight: Platform.OS === 'ios' ? (deviceInfo.isIphoneX ? 44 : 20) : 0, // 导航栏除掉状态栏的高度 navContentHeight: Platform.OS === 'ios' ? 44 : 56, // tabBar的高度 tabBarHeight: Platform.OS === 'ios' ? (deviceInfo.isIphoneX ? 83 : 49) : 49, // 底部按钮高度 bottonBtnHeight: 44, // 通用列表cell高度 cellHeight: 44, // 导航栏左右按钮image高度 navImageHeight: 25, /** font **/ // 默认文字字体 textFont: 14, // 默认按钮文字字体 btnFont: 15, btnFontSmall: 13, // 导航title字体 navTitleFont: 17, // tabBar文字字体 barBarTitleFont: 12, // 占位符的默认字体大小 placeholderFont: 13, // 导航左按钮的字体 navRightTitleFont: 15, // 导航右按钮字体 navLeftTitleFont: 15, /** opacity **/ // mask modalOpacity: 0.3, // touchableOpacity taOpacity: 0.1, /** 定位 **/ absolute: 'absolute', /** flex **/ around: 'space-around', between: 'space-between', center: 'center', row: 'row', }; export default BaseStyle; <file_sep>/src/components/topScreen/topScreen.js import React, { Component } from 'react'; import PropTypes from 'prop-types' import { Platform, StyleSheet, TouchableOpacity, View, Text, Image, } from 'react-native'; import {scaleSize, setSpText2, ifIphoneX, scaleHeight} from "../../lib/styleAdaptation"; //公共类 export default class TopScreen extends Component { static propTypes = { leftItem: PropTypes.func, title: PropTypes.string, rightTxt: PropTypes.string, rightItem: PropTypes.func, }; constructor(props){ super(props); } renderLeftItem(){ if (this.props.leftItem === undefined) return; return this.props.leftItem(); } renderRightItem(){ if (this.props.rightItem === undefined) return; return this.props.rightItem(); } render() { let statusBar = Platform.select({ ios: ifIphoneX() ? 44 : 20, android: 0, }); return ( <View style={[ styles.header, {margin: 0, paddingTop: statusBar, height: statusBar + 44}]}> <TouchableOpacity activeOpacity={1} onPress={()=>{this.renderLeftItem()}}> <View style={styles.headerReturnIcon}> <Text> { '<' } </Text> </View> </TouchableOpacity> <Text style={this.props.rightTxt ? styles.title : styles.centerTitle}> {this.props.title} </Text> {this.props.rightTxt && <TouchableOpacity onPress={()=>{this.renderRightItem()}}> <View style={styles.doneText}> <Text>{this.props.rightTxt}</Text> </View> </TouchableOpacity> } </View> ) } } const styles = StyleSheet.create({ header: { flexDirection: 'row', paddingHorizontal: scaleHeight(15), justifyContent: 'space-between', alignItems: 'center', backgroundColor: '#FFFFFFFF' }, headerNoRight: { flexDirection: 'row', paddingHorizontal: scaleHeight(15), }, headerReturnIcon: { justifyContent: 'flex-start', textAlign: 'left' }, title: { justifyContent: 'center', textAlign: 'center', fontSize: setSpText2(18), fontFamily: 'PingFang-SC-Bold', fontWeight: 'bold', color: '#333333FF' }, centerTitle: { width:scaleSize(335), textAlign: 'center', fontSize: setSpText2(18), fontFamily: 'PingFang-SC-Bold', fontWeight: 'bold', color: '#333333FF' }, doneText: { justifyContent: 'flex-end', textAlign: 'right', fontSize: setSpText2(17), fontFamily: 'PingFang-SC-Medium', fontWeight: '500', color: '#333333FF' } }); <file_sep>/src/containers/login/loginScreen.js import React, { Component } from 'react'; import { View, Text, TextInput, Image, StyleSheet } from "react-native"; import loginStyle from './loginStyle'; class LoginScreen extends Component { render(): React.ReactNode { return ( <View style={loginStyle.container}> <View style={loginStyle.logoContainer}> <Image roundAsCircle={true} style={loginStyle.logoImgStyle} source={require('../../images/logo.png')}/> <Text style={loginStyle.logoTxt}>佐商学院</Text> </View> </View> ); } } export default LoginScreen; <file_sep>/src/components/banner/bannerStyle.js import { StyleSheet } from 'react-native'; import {scaleHeight, setSpText2, scaleSize } from "../../lib/styleAdaptation"; const bannerStyle = StyleSheet.create({ bannerSize: { height: scaleHeight(155), }, imageSize: { width: scaleSize(375), height: scaleHeight(155), }, bulletOneStyle: { width: 5, height: 5, borderRadius: 5, borderColor: '#dddddd', backgroundColor: '#dddddd', }, chooseBulletStyle: { width: 11, height: 5, borderRadius: 2, backgroundColor: '#ffffff' } }) export default bannerStyle; <file_sep>/android/app/src/main/java/com/jinqiuzhiku/alipay/AlipayModule.java package com.jinqiuzhiku.alipay; import com.alipay.sdk.app.EnvUtils; import com.alipay.sdk.app.PayTask; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.WritableMap; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import java.io.IOException; import java.util.Map; public class AlipayModule extends ReactContextBaseJavaModule { public AlipayModule(ReactApplicationContext reactContext) { super(reactContext); } @Override public String getName() { return "Alipay"; } @ReactMethod public void pay(final String orderInfo, final Promise promise) { EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX); Runnable payRunnable = new Runnable() { @Override public void run() { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("http://www.zxqc2019.cn:7777/pay-php-sdk/index.php") .header("User-Agent", "OkHttp Headers.java") .addHeader("Accept", "application/json; q=0.5") .addHeader("Accept", "application/vnd.github.v3+json") .build(); String result1 = ""; try { Response response = client.newCall(request).execute(); result1 = response.body().string(); System.out.println(result1); } catch (IOException e) { e.printStackTrace(); } WritableMap map = Arguments.createMap(); PayTask alipay = new PayTask(getCurrentActivity()); Map<String, String> result = alipay.payV2(result1, true); for (Map.Entry<String, String> entry : result.entrySet()) map.putString(entry.getKey(), entry.getValue()); promise.resolve(map); } }; // 必须异步调用 Thread payThread = new Thread(payRunnable); payThread.start(); } } <file_sep>/src/containers/search/searchScreen.js import React, { Component } from 'react'; import { View, Text, StyleSheet, TouchableOpacity} from 'react-native'; import SearchInput from '../../components/search/searchInput' import {scaleHeight, scaleSize} from "../../lib/styleAdaptation"; class SearchScreen extends Component { render(): React.ReactNode { return( <View> <View style={searchStyle.searchStyle}> <SearchInput searchContainer={searchStyle.searchContainer} placeholderTxt={'搜索课程、讲师'} /> <TouchableOpacity activeOpacity={1} onPress={()=>{this.props.navigation.goBack()}}> <Text>取消</Text> </TouchableOpacity> </View> <Text>this is search</Text> </View> ); } } const searchStyle = StyleSheet.create({ searchStyle: { flexDirection: 'row', paddingHorizontal: scaleSize(15), paddingVertical: scaleHeight(8), width: scaleSize(375), alignItems: 'center', }, searchContainer: { width: scaleSize(300), justifyContent: 'flex-start', marginRight: scaleSize(13), paddingLeft: scaleSize(16) } }) export default SearchScreen; <file_sep>/src/containers/homeScreen.js import React, { Component } from 'react'; import { View, Text, Alert, TouchableOpacity} from 'react-native'; import fetchRequest from '../lib/request' class HomeScreen extends Component { constructor () { super() this.state = { test: '' } } _pressButton() { // fetch('http://192.168.1.187:8181/wxapi/courses/',) // .then((responseJson) =>{ // console.log(responseJson); // }) // .catch((error) => { // console.log(error); // }) fetchRequest('appApi/test','POST').then((res) =>{ console.error(['res homeScreen',123]) // this.setState({ // test: res.data.baseUrl // }) }) } render(): React.ReactNode { return ( <View> <TouchableOpacity onPress={this._pressButton.bind(this,1)} > <Text>{this.state.test? this.state.test : 'this is home'}</Text> </TouchableOpacity> <Text>{this.state.test}</Text> </View> ); } } export default HomeScreen;
c18306d5e6edc2ca30710011d724bf569b97ee99
[ "Markdown", "Java", "JavaScript" ]
15
Markdown
zuoshangjiaoyu/jqkt
c89b434a8e753644fe2037ea2bfaaeeea1e37430
3a5e0577a551fe91efc5ab8b4421e6ab1d5ab479
refs/heads/master
<file_sep>using System; namespace ConsoleApp1 { public class MatrixProblem { public static int days = 0; public static void Main(string[] args) { int[,] test1 = new int[4, 4]; int[,] test2 = new int[10, 10]; int[,] test3 = new int[20, 20]; FarmMatrix(4, 4, test1, 1); FarmMatrix(10, 10, test2, 2); FarmMatrix(20, 20, test3, 1); Print(4, 4, test1); Print(10, 10, test2); Print(20, 20, test3); var result1 = CountDays(4, 4, test1); Print(4, 4, test1); days = 0; var result2 = CountDays(10, 10, test2); days = 0; Print(10, 10, test2); var result3 = CountDays(20, 20, test3); Print(20, 20, test3); days = 0; Console.Write("Number of days: " + result1 + "\n"); Console.Write("Number of days: " + result2 + "\n"); Console.Write("Number of days: " + result3); Console.ReadKey(); } public static void FarmMatrix(int columns, int rows, int[,] arr, int caseType) { switch (caseType) { case 1: for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if (i == j) arr[i, j] = 1; else arr[i, j] = 0; } } break; case 2: for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if (i == 5) arr[i, j] = 1; else arr[i, j] = 0; } } break; case 3: for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if (i == 0) arr[i, j] = 1; else arr[i, j] = 0; } } break; } } public static void Print(int columns, int rows, int[,] arr) { for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { Console.Write(arr[i, j] + " "); } Console.Write("\n"); } Console.WriteLine(); } public static bool CheckMatrixIsDone(int columns, int rows, int[,] arr) { for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if (arr[i, j] == 0) { return false; } } } return true; } public static int[,] DisseminateArchive(int rows, int columns, int[,] matrix) { for (int row = 0; row < rows; row++) { for (int column = 0; column < columns; column++) { //if first line if (row == 0 && column == 0 && matrix[row, column] == 1) { matrix[row + 1, column] = 1;//down matrix[row, column + 1] = 1;// right Print(rows, columns, matrix); } else if (row == 0 && column == columns-1 && matrix[row, column] == 1) { matrix[row + 1, column] = 1; // down matrix[row, column - 1] = 1;// left Print(rows, columns, matrix); } else if (row == 0 && column > 0 && column < columns-1 && matrix[row, column] == 1) { matrix[row + 1, column] = 1;// de baixo matrix[row, column + 1] = 1;// right matrix[row, column - 1] = 1;// left Print(rows, columns, matrix); }//if borders left and right else if (column == 0 && row > 0 && row < rows-1 && matrix[row, column] == 1) { matrix[row - 1, column] = 1;// up matrix[row + 1, column] = 1;// down matrix[row, column + 1] = 1;// right Print(rows, columns, matrix); } else if (column == columns-1 && row > 0 && row < rows-1 && matrix[row, column] == 1) { matrix[row - 1, column] = 1;// up matrix[row + 1, column] = 1;// down matrix[row, column - 1] = 1;// left Print(rows, columns, matrix); } else if(row == rows-1 && columns == 0 && matrix[row, column] == 1) { matrix[row - 1, column] = 1;// up matrix[row, column + 1] = 1;// right Print(rows, columns, matrix); } else if(row == rows-1 && column == columns-1 && matrix[row, column] == 1) { matrix[row - 1, column] = 1;// up matrix[row, column - 1] = 1;// left Print(rows, columns, matrix); } else if(row == rows-1 && column > 0 && column < columns-1 && matrix[row, column] == 1) { matrix[row, column + 1] = 1;// right matrix[row, column - 1] = 1;// left matrix[row - 1, column] = 1;// up Print(rows, columns, matrix); } else if(row > 0 && column > 0 && row < rows-1 && column < columns-1 && matrix[row, column] == 1) { matrix[row - 1, column] = 1;// up matrix[row + 1, column] = 1;// down matrix[row, column + 1] = 1;// right matrix[row, column - 1] = 1;// left Print(rows, columns, matrix); } Print(rows, columns, matrix); } Print(rows, columns, matrix); } return matrix; } public static int CountDays(int rows, int columns, int[,] matrix) { var ModifiedMatrix = DisseminateArchive(rows, columns, matrix); var result = CheckMatrixIsDone(rows, columns, ModifiedMatrix); if (result) { days++; return days; } else { days++; CountDays(rows, columns, ModifiedMatrix); return days; } } } }
9902cad4ee4ee198a7f464b802e688b6666d6dc8
[ "C#" ]
1
C#
rafael-hs/2DmatrixProblem
2ad8860cf352fc45a9d804540ef8d555dc54cac6
20a3f0c0930c7de0944364abe02587db71e90293
refs/heads/master
<repo_name>cambieri/ironika-calosso<file_sep>/fab_deploy.sh source /home/workspace-django/virtualenvs/ironika-calosso/bin/activate cd /home/workspace-django/projects/ironika-calosso/calosso/ fab live prepare_deploy fab live deploy deactivate <file_sep>/calosso/apps/main/migrations/0005_auto__add_field_galleria_homepage.py # encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Galleria.homepage' db.add_column(u'main_galleria', 'homepage', self.gf('django.db.models.fields.related.ForeignKey')(default=1, to=orm['main.Homepage']), keep_default=False) def backwards(self, orm): # Deleting field 'Galleria.homepage' db.delete_column(u'main_galleria', 'homepage_id') models = { u'main.articolo': { 'Meta': {'ordering': "['titolo']", 'object_name': 'Articolo'}, 'descrizione': ('django.db.models.fields.TextField', [], {'max_length': '400', 'blank': 'True'}), 'galleria': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['main.Galleria']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'immagine': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}), 'miniatura': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}), 'posizione': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'titolo': ('django.db.models.fields.CharField', [], {'max_length': '80'}) }, u'main.galleria': { 'Meta': {'ordering': "['pk']", 'object_name': 'Galleria'}, 'articolo_principale': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'+'", 'unique': 'True', 'null': 'True', 'to': u"orm['main.Articolo']"}), 'homepage': ('django.db.models.fields.related.ForeignKey', [], {'default': '1', 'to': u"orm['main.Homepage']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'menu': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'posizione': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'slogan': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}), 'titolo': ('django.db.models.fields.CharField', [], {'max_length': '30'}) }, u'main.homepage': { 'Meta': {'object_name': 'Homepage'}, 'descrizione': ('django.db.models.fields.CharField', [], {'max_length': '300', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'occhiello': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}), 'slogan': ('django.db.models.fields.CharField', [], {'max_length': '50'}) } } complete_apps = ['main'] <file_sep>/calosso/urls.py from django.conf import settings from django.conf.urls import patterns, include, url from django.contrib import admin # from django.views.generic.base import TemplateView admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^$', 'main.views.index'), # url(r'^chi_siamo$', TemplateView.as_view(template_name="chi_siamo.html", get_context_data=lambda:{'sezione': 'chi_siamo'})), url(r'^chi_siamo$', 'main.views.chi_siamo'), # url(r'^contatti$', TemplateView.as_view(template_name="contatti.html", get_context_data=lambda:{'sezione': 'contatti'})), url(r'^contatti$', 'main.views.contatti'), url(r'^gallery/(?P<gallery_id>\d)$', 'main.views.gallery'), ) # static media if settings.DEBUG: urlpatterns += patterns('', (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) # handler500 = 'main.views.nondefault_500_error' <file_sep>/calosso/apps/main/templatetags/template_debug.py from django.template import Library, Node register = Library() class PydevDebugNode(Node): def render(self, context): try: import pydevd #@UnresolvedImport pydevd.connected = True pydevd.settrace() return '' except: # It might be more clear to just let this exception pass through return 'Debugger was not turned on' @register.tag def template_debug(parser, token): return PydevDebugNode() <file_sep>/calosso/apps/main/models.py # -*- coding: utf-8 -*- from django.db import models ### GESTIONE CARICAMENTO E CANCELLAZIONE IMMAGINI ARTICOLI (inizio) ### import os from django.core.files.storage import FileSystemStorage from django.conf import settings class OverwriteFileStorage(FileSystemStorage): def get_available_name(self, name): if self.exists(name): os.remove(os.path.join(settings.MEDIA_ROOT, name)) return name def get_miniatura_path(instance, filename): return 'img/{0}/piccole/{1}'.format(instance.galleria.pk, filename) def get_immagine_path(instance, filename): return 'img/{0}/{1}'.format(instance.galleria.pk, filename) from django.db.models.fields.files import FieldFile from django.db.models.signals import pre_delete def file_cleanup(sender, instance, *args, **kwargs): ''' Deletes the file(s) associated with a model instance. The model is not saved after deletion of the file(s) since this is meant to be used with the pre_delete signal. Se vuote, cancella anche la directory contenitore e la sua parent. ''' for field_name, _ in list(instance.__dict__.iteritems()): field = getattr(instance, field_name) if issubclass(field.__class__, FieldFile) and field.name: dir_path = os.path.join(settings.MEDIA_ROOT, os.path.dirname(field.name)) field.delete(save=False) if os.path.isdir(dir_path) and not os.listdir(dir_path): parent_dir_path = os.path.dirname(dir_path) os.rmdir(dir_path) if os.path.isdir(parent_dir_path) and not os.listdir(parent_dir_path): os.rmdir(parent_dir_path) ### GESTIONE CARICAMENTO E CANCELLAZIONE IMMAGINI ARTICOLI (fine) ### class Homepage(models.Model): slogan = models.CharField('Slogan', max_length=50, blank=False) descrizione = models.CharField('Descrizione', max_length=300, blank=True) occhiello = models.CharField('Occhiello', max_length=50, blank=True) immagine = models.ImageField('Immagine', blank=False, upload_to='img/home', storage=OverwriteFileStorage()) # galleria_principale = models.OneToOneField('Galleria') class Meta: verbose_name = "HOMEPAGE" verbose_name_plural = "Homepage" def __unicode__(self): return u"Gestione HOMEPAGE" class Galleria(models.Model): POSIZIONE_SCELTE = ( (0,'Disabilitato'), (1,'Galleria Principale'), (2,'Riga 1 - SX'), (3,'Riga 1 - C'), (4,'Riga 1 - DX'), (5,'Riga 2 - SX'), (6,'Riga 2 - C'), (7,'Riga 2 - DX'), ) homepage = models.ForeignKey(Homepage, default=1, editable=False) menu = models.CharField('Voce di menù', max_length=50, blank=False) slogan = models.CharField('Slogan', max_length=50, blank=True) titolo = models.CharField('Titolo', max_length=30, blank=False) articolo_principale = models.OneToOneField('Articolo', on_delete=models.SET_NULL, blank=True, null=True, related_name='+') # nessuna backwards relation posizione = models.PositiveSmallIntegerField('Posizione in homepage', blank=False, default=0, choices=POSIZIONE_SCELTE) class Meta: verbose_name = "GALLERIA" verbose_name_plural = "Gallerie" ordering = ['posizione', 'pk'] def __unicode__(self): return u'{0} - {1}'.format(self.posizione, self.menu) class Articolo(models.Model): POSIZIONE_SCELTE = ( (0,'Disabilitato'), (1,'Riga 1 - SX'), (2,'Riga 1 - C'), (3,'Riga 1 - DX'), (4,'Riga 2 - SX'), (5,'Riga 2 - C'), (6,'Riga 2 - DX'), (7,'Riga 3 - SX'), (8,'Riga 3 - C'), (9,'Riga 3 - DX'), (10,'Riga 4 - SX'), (11,'Riga 4 - C'), (12,'Riga 4 - DX'), (13,'Riga 5 - SX'), (14,'Riga 5 - C'), (15,'Riga 5 - DX'), (16,'Riga 6 - SX'), (17,'Riga 6 - C'), (18,'Riga 6 - DX'), ) galleria = models.ForeignKey(Galleria) miniatura = models.ImageField('Miniatura', blank=False, upload_to=get_miniatura_path, storage=OverwriteFileStorage()) immagine = models.ImageField('Immagine', blank=False, upload_to=get_immagine_path, storage=OverwriteFileStorage()) titolo = models.CharField('Titolo', max_length=80, blank=False) descrizione = models.TextField('Descrizione', max_length=400, blank=True) posizione = models.PositiveSmallIntegerField('Posizione in galleria', blank=False, default=0, choices=POSIZIONE_SCELTE) class Meta: verbose_name = "ARTICOLO" verbose_name_plural = "Articoli" ordering = ['posizione', 'pk'] def __unicode__(self): return u'{0} - {1}'.format(self.posizione, self.titolo) pre_delete.connect(file_cleanup, sender=Articolo) class Varie(models.Model): immagine_chi_siamo = models.ImageField('Immagine sezione "chi siamo"', blank=False, upload_to='img/varie', storage=OverwriteFileStorage()) testo_chi_siamo = models.TextField('Testo sezione "chi siamo"', blank=False) testo_contatti = models.TextField('Testo sezione "contatti"', blank=False) class Meta: verbose_name = "VARIE" verbose_name_plural = "Varie" def __unicode__(self): return u"Gestioni VARIE" <file_sep>/calosso/apps/main/migrations/0002_auto__add_articolo__add_galleria__add_homepage.py # encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Articolo' db.create_table(u'main_articolo', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('galleria', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['main.Galleria'])), ('miniatura', self.gf('django.db.models.fields.files.ImageField')(max_length=100)), ('immagine', self.gf('django.db.models.fields.files.ImageField')(max_length=100)), ('titolo', self.gf('django.db.models.fields.CharField')(max_length=80)), ('descrizione', self.gf('django.db.models.fields.TextField')(max_length=400, blank=True)), ('posizione', self.gf('django.db.models.fields.PositiveSmallIntegerField')()), )) db.send_create_signal(u'main', ['Articolo']) # Adding model 'Galleria' db.create_table(u'main_galleria', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('slogan', self.gf('django.db.models.fields.CharField')(max_length=50, blank=True)), ('titolo', self.gf('django.db.models.fields.CharField')(max_length=30)), ('articolo_principale', self.gf('django.db.models.fields.related.OneToOneField')(blank=True, related_name='+', unique=True, null=True, to=orm['main.Articolo'])), )) db.send_create_signal(u'main', ['Galleria']) # Adding model 'Homepage' db.create_table(u'main_homepage', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('slogan', self.gf('django.db.models.fields.CharField')(max_length=50)), ('descrizione', self.gf('django.db.models.fields.CharField')(max_length=300, blank=True)), ('occhiello', self.gf('django.db.models.fields.CharField')(max_length=50, blank=True)), ('galleria_principale', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['main.Galleria'], unique=True)), )) db.send_create_signal(u'main', ['Homepage']) def backwards(self, orm): # Deleting model 'Articolo' db.delete_table(u'main_articolo') # Deleting model 'Galleria' db.delete_table(u'main_galleria') # Deleting model 'Homepage' db.delete_table(u'main_homepage') models = { u'main.articolo': { 'Meta': {'ordering': "['titolo']", 'object_name': 'Articolo'}, 'descrizione': ('django.db.models.fields.TextField', [], {'max_length': '400', 'blank': 'True'}), 'galleria': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['main.Galleria']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'immagine': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}), 'miniatura': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}), 'posizione': ('django.db.models.fields.PositiveSmallIntegerField', [], {}), 'titolo': ('django.db.models.fields.CharField', [], {'max_length': '80'}) }, u'main.galleria': { 'Meta': {'ordering': "['titolo']", 'object_name': 'Galleria'}, 'articolo_principale': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'+'", 'unique': 'True', 'null': 'True', 'to': u"orm['main.Articolo']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'slogan': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}), 'titolo': ('django.db.models.fields.CharField', [], {'max_length': '30'}) }, u'main.homepage': { 'Meta': {'object_name': 'Homepage'}, 'descrizione': ('django.db.models.fields.CharField', [], {'max_length': '300', 'blank': 'True'}), 'galleria_principale': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['main.Galleria']", 'unique': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'occhiello': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}), 'slogan': ('django.db.models.fields.CharField', [], {'max_length': '50'}) } } complete_apps = ['main'] <file_sep>/calosso/apps/main/admin.py from django.db import models from django.contrib import admin from django.forms.models import ModelForm from django.forms.widgets import Textarea from models import Homepage, Galleria, Articolo, Varie from admin_image_widget import AdminImageWidget custom_charfield_widget = {'widget': Textarea(attrs={'cols':40, 'rows':2})} custom_textfield_widget = {'widget': Textarea(attrs={'cols':80, 'rows':3})} custom_image_widget = {'widget': AdminImageWidget} widget_overrides = { models.CharField: custom_charfield_widget, models.TextField: custom_textfield_widget, models.ImageField: custom_image_widget, } class ArticoloInline(admin.TabularInline): model = Articolo max_num = 18 formfield_overrides = widget_overrides class GalleriaForm(ModelForm): def __init__(self, *args, **kwargs): super(GalleriaForm, self).__init__(*args, **kwargs) self.fields['articolo_principale'].queryset = Articolo.objects.filter(galleria__exact=self.instance.pk) self.exclude = ['homepage'] class GalleriaAdmin(admin.ModelAdmin): form = GalleriaForm fields = ['menu', 'posizione', 'articolo_principale', 'slogan', 'titolo'] inlines = [ArticoloInline, ] formfield_overrides = widget_overrides def get_readonly_fields(self, request, obj=None): if request.user.is_superuser: return () return ('menu', ) class GalleriaInline(admin.TabularInline): model = Galleria form = GalleriaForm fields = ['posizione', 'articolo_principale', 'slogan', 'titolo'] formfield_overrides = widget_overrides class HomepageAdmin(admin.ModelAdmin): formfield_overrides = { models.CharField: {'widget': Textarea(attrs={'cols':60, 'rows':3})}, } inlines = [GalleriaInline, ] class VarieAdmin(admin.ModelAdmin): formfield_overrides = { models.ImageField: custom_image_widget, } admin.site.register(Homepage, HomepageAdmin) admin.site.register(Galleria, GalleriaAdmin) # admin.site.register(Articolo) admin.site.register(Varie, VarieAdmin) <file_sep>/calosso/apps/main/views.py from django.template import loader import sys from django import http from django.template.context import Context from django.shortcuts import render, get_object_or_404 from models import Galleria from calosso.apps.main.models import Homepage, Varie def nondefault_500_error(request, template_name='500nondefault.html'): """ 500 error handler for debug. Templates: `500.html` Context: sys.exc_info() results """ t = loader.get_template(template_name) # You need to create a 500.html template. ltype,lvalue,ltraceback = sys.exc_info() sys.exc_clear() #for fun, and to point out I only -think- this hasn't happened at #this point in the process already return http.HttpResponseServerError(t.render(Context({'type':ltype,'value':lvalue,'traceback':ltraceback}))) def main_menu_context_processor(request): voci_menu = Galleria.objects.exclude(menu__iexact = '(nascosta)').values('pk', 'menu') return {'voci_menu':voci_menu} def index(request): homepage = Homepage.objects.all()[:1].get() try: principale = Galleria.objects.get(posizione__exact = 1); except: principale = None try: gallerie = Galleria.objects.filter(posizione__gt = 1).order_by('posizione'); except: gallerie = Galleria() args = { 'sezione': '', 'homepage': homepage, 'principale': principale, 'gallerie': gallerie, } return render(request, 'index.html', args) def gallery(request, gallery_id): galleria = get_object_or_404(Galleria, pk = gallery_id) try: principale = galleria.articolo_principale.posizione except: principale = 0 args = {'sezione': galleria.menu, 'galleria': galleria, 'principale': principale} return render(request, 'gallery.html', args) def chi_siamo(request): varie = Varie.objects.all()[:1].get() args = { 'sezione': 'chi_siamo', 'immagine': varie.immagine_chi_siamo, 'testo': varie.testo_chi_siamo, } return render(request, 'chi_siamo.html', args) def contatti(request): varie = Varie.objects.all()[:1].get() args = { 'sezione': 'contatti', 'testo': varie.testo_contatti, } return render(request, 'contatti.html', args)
43783280acdf6eae743d92135a0255eb704fa1af
[ "Python", "Shell" ]
8
Shell
cambieri/ironika-calosso
3466da071320ed2c1f204fed4642812939d42240
2ae2dee1158f1a83fff82c58d1b144ebc235df6b
refs/heads/master
<file_sep>package biz.pdxtech.daap.ledger.util; import io.protostuff.LinkedBuffer; import io.protostuff.ProtostuffIOUtil; import io.protostuff.Schema; import io.protostuff.runtime.RuntimeSchema; import java.util.concurrent.ConcurrentHashMap; /** * Created by bochenlong on 16-11-3. */ public class MessageCodec { private static ConcurrentHashMap<Class<?>, Schema<?>> cschema = new ConcurrentHashMap(); public static <T> byte[] toBytes(T t) { LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE); Class clazz = t.getClass(); Schema schema = cschema.computeIfAbsent(clazz, a -> RuntimeSchema.createFrom(clazz)); return ProtostuffIOUtil.toByteArray(t, schema, buffer); } public static <T> T toObject(byte[] bytes, Class<T> clazz) { try { T obj = clazz.newInstance(); ProtostuffIOUtil.mergeFrom(bytes, obj, (Schema<T>) cschema.getOrDefault(clazz, RuntimeSchema.createFrom(clazz))); return obj; } catch (Exception e) { e.printStackTrace(); } return null; } } <file_sep># daap-ledger ## PDX DaaP ledger application ### 1. maven工程创建 pom.xml 配置 #### 配置 maven repo <repository> <id>pdx-release</id> <name>biz.pdxtech</name> <url>http://daap.pdx.life:8081/nexus/content/repositories/releases</url> </repository> #### 配置PDX BlockChain Driver API 依赖 <!-- bcdriver api --> <dependency> <groupId>biz.pdxtech.daap</groupId> <artifactId>daap-bcdriver</artifactId> <version>1.2.5</version> </dependency> #### 配置Default Ethereum BlockChain Driver实现 依赖 <!-- Default Ethereum BlockChain Driver --> <dependency> <groupId>biz.pdxtech.daap</groupId> <artifactId>daap-ethbcdriver</artifactId> <version>1.2.5</version> </dependency> ### 2. BcDriver实例 **实例化BcDriver** 调用BcDriver首先需要实例化Driver.主要是两个参数。一个是协议栈类型;另一个是用户私钥。缺省情况下,协议栈类型为ethereum, 私钥会由BcDriver自动生成。调用者也可以通 过如下两个方法之一自己进行参数设置。 #### 2.1通过环境变量实例化 BlockChainDriver driver = BlockChainDriverFactory.get(); PDX_DAAP_CHAIN_TYPE // 协议栈类型,默认 ethereum (以太坊) PDX_DAAP_PRIVATEKEY //【可选】ECC私钥,HEX格式 #### 2.2通过property配置实例化 BlockChainDriver driver = BlockChainDriverFactory.get(property); #blockchain Type type=ethereum #privateKey privateKey=******************************************** ### 3.BcDriver调用 通过BcDriver以下方法调用链上或者远端合约: query apply 参见DaapLedgerCaller 例子 通过设置Transaction 中属性指定contract 地址和自定义逻辑等 dst -->合约地址 meta -->元数据,可查询 body -->自定义数据结构 #### 3.1 ledger-query方法详细说明 Ledger查询分为两类;两类查询都可以通过设置Transaction.meta属性进行查询或者Transaction.body属性进行查询 **设置Transaction.meta属性查询** 1 查询交易 * 根据交易ID查询;设置meta - ("DaaP-Query-TXID","txidtext".getBytes()) * 根据自定义信息meta查询 设置meta - ("name","nametext") 可设置多个,但认为它们是与的关系 2 查询合约状态 * 根据交易ID查询;设置meta - ("DaaP-Query-STATE-TXID","txidtext".getBytes());此处查询出来的结果为此次交易执行完的合约状态 * 根据合约查询 设置meta - ("DaaP-Query-STATE-DST","dsttext") **设置Transaction.body属性进行查询,这时候你需要传入一个exp表达式,表达式形如:"${tx:body[bodytext]}".getBytes())** 1 查询交易 * 根据交易ID查询 设置body表达式 `"${tx:txid[txidtext]}".getBytes() ` * 根据自定义信息meta查询 设置body表达式 `"${tx:meta[metak,metav]||meta[metak,metav]}".getBytes()` *注意:metav是将原byte[] Hex序列化过的文本* *辅助查询条件页码 设置body表达式 "${tx:txid[txidtext]&&pageno[2]}".getBytes() 不写默认为1页,每页固定1000记录* 2 查询合约状态 * 根据交易Id查询 设置body表达式 "${state:txid[txidtext]}".getBytes() * 根据合约查询 设置body表达式 "${state:dst[dsttext]}".getBytes() *辅助查询条件页码 设置body表达式 "${state:dst[dsttext]&&pageno[2]}".getBytes() 不写默认为1页,每页固定1000记录* ##### 查询请注意: 1 如果查询条件中含有txid的条件,则默认只根据txid查询 2 exp表达式中必须以${tx:}/${state:}的形式 <file_sep>package biz.pdxtech.daap.ledger; import biz.pdxtech.daap.api.contract.Transaction; import biz.pdxtech.daap.bcdriver.BlockChainDriver; import biz.pdxtech.daap.bcdriver.BlockChainDriverFactory; import biz.pdxtech.daap.ledger.util.ContractState; import biz.pdxtech.daap.ledger.util.HexUtil; import biz.pdxtech.daap.ledger.util.MessageCodec; import org.apache.commons.lang3.StringUtils; import java.net.URI; import java.net.URISyntaxException; import java.util.*; public class DaapLedgerCaller { public static void main(String[] args) { /*1 setting props*/ Properties props = new Properties(); props.setProperty("privateKey", "623aacd6be3174d096711814e27487f26ce0126279ab3c85823cd3b2e86da28d"); /*2 setting testKey*/ setTestKey("2017-01-14T15:18:50.528"); /*3 setting contract dst*/ setContractDst("daap://default_pdx_chain/pdxdev/pdx.dapp/example"); /*4 query from pdx*/ BlockChainDriver driver = BlockChainDriverFactory.get(props); queryTx(driver, testKey); queryState(driver, testKey); } private static String testKey; private static String contractDst; /** * Ledger查询分为两类;两类查询都可以通过设置Transaction.meta属性进行查询或者Transaction.body属性进行查询 * <p> * ### 设置Transaction.meta属性查询 * 1 查询交易 * ① 根据交易ID查询;设置meta - ("DaaP-Query-TXID","txidtext".getBytes()) * ② 根据自定义信息meta查询 设置meta - ("name","nametext") 可设置多个,但认为它们是与的关系 * <p> * 2 查询合约状态 * ① 根据交易ID查询;设置meta - ("DaaP-Query-STATE-TXID","txidtext".getBytes());此处查询出来的结果为此次交易执行完的合约状态 * ② 根据合约查询 设置meta - ("DaaP-Query-STATE-DST","dsttext") * <p> * 2 设置Transaction.body属性进行查询,这时候你需要传入一个exp表达式,表达式形如:"${tx:body[bodytext]}".getBytes()) * <p> * ### 设置Transaction.body属性查询 * 1 查询交易 * ① 根据交易ID查询 设置body表达式 "${tx:txid[txidtext]}".getBytes() * ② 根据自定义信息meta查询 设置body表达式 "${tx:meta[metak,metav]||meta[metak,metav]}".getBytes() 注意:metav是将原byte[] Hex序列化过的文本 * 辅助查询条件页码 设置body表达式 "${tx:txid[txidtext]&&pageno[2]}".getBytes() 不写默认为1页,每页固定1000记录 * <p> * 2 查询合约状态 * ① 根据交易Id查询 设置body表达式 "${state:txid[txidtext]}".getBytes() * ② 根据合约查询 设置body表达式 "${state:dst[dsttext]}".getBytes() * 辅助查询条件页码 设置body表达式 "${state:dst[dsttext]&&pageno[2]}".getBytes() 不写默认为1页,每页固定1000记录 * <p> * 查询请注意: * 1 如果查询条件中含有txid的条件,则默认只根据txid查询 * 2 exp表达式中必须以${tx:}/${state:}的形式 * * @param driver */ private static void queryTx(BlockChainDriver driver, String testKey) { assert StringUtils.isNotEmpty(testKey); /**1 设置Transaction.meta属性查询交易*/ /** 根据交易ID查询*/ Transaction tx = new Transaction(); Map<String, byte[]> map = new LinkedHashMap<>(); map.put("DaaP-Query-TX-TXID", "e4ebcbd2f017ab188d0b828cdf1568d17d1ab4ce5a0dcf63418656d8740b813e".getBytes()); tx.setMeta(map); queryTx(tx, driver); /** 根据自定义信息查询*/ tx = new Transaction(); map = new LinkedHashMap<>(); map.put("name", DaapCaller.addTestKey("kangxinghao", testKey).getBytes()); map.put("age", DaapCaller.addTestKey("22", testKey).getBytes()); tx.setMeta(map); queryTx(tx, driver); /**2 设置Transaction.body属性进行查询*/ /** 根据交易ID查询*/ tx = new Transaction(); tx.setBody("${tx:txid[e4ebcbd2f017ab188d0b828cdf1568d17d1ab4ce5a0dcf63418656d8740b813e]}".getBytes()); queryTx(tx, driver); /** 根据自定义信息查询*/ String exp = ("${tx:meta[name," + HexUtil.toHex(DaapCaller.addTestKey("kangxinghao", testKey).getBytes()) + "]||meta[age," + HexUtil.toHex(DaapCaller.addTestKey("22", testKey).getBytes()) + "]}"); tx.setBody(exp.getBytes()); queryTx(tx, driver); } private static void queryState(BlockChainDriver driver, String testKey) { assert StringUtils.isNotEmpty(testKey); /**1 设置Transaction.meta属性查询合约状态*/ Transaction tx = new Transaction(); Map<String, byte[]> map = new LinkedHashMap<>(); map.put("DaaP-Query-STATE-TXID", "e4ebcbd2f017ab188d0b828cdf1568d17d1ab4ce5a0dcf63418656d8740b813e".getBytes()); tx.setMeta(map); queryState(tx, driver); /**2 设置Transaction.body属性进行查询*/ /** 根据交易ID查询*/ tx = new Transaction(); tx.setBody("${state:txid[e4ebcbd2f017ab188d0b828cdf1568d17d1ab4ce5a0dcf63418656d8740b813e]}".getBytes()); queryState(tx, driver); /** 根据合约地址查询*/ tx = new Transaction(); String exp = ("${state:dst[" + contractDst + "]"); tx.setBody(exp.getBytes()); queryState(tx, driver); } private static void queryTx(Transaction tx, BlockChainDriver driver) { try { tx.setDst(new URI("daap://tender-pdx/pdx.dapp/ledger")); List<Transaction> res = driver.query(tx); if (res != null && res.size() > 0) { res.stream().forEach(a -> System.out.println(new String(a.getBody()))); } } catch (URISyntaxException e) { e.printStackTrace(); } } private static void queryState(Transaction tx, BlockChainDriver driver) { try { tx.setDst(new URI("daap://tender-pdx/pdx.dapp/ledger")); List<Transaction> res = driver.query(tx); if (res != null && res.size() > 0) { res.stream().forEach(a -> { if(a.getBody() != null && a.getBody().length != 0) { ContractState state = MessageCodec.toObject(a.getBody(), ContractState.class); state.getMap().entrySet().stream().forEach(b -> { System.out.println("key : " + b.getKey()); System.out.println("value : " + new String(b.getValue())); }); } }); } } catch (URISyntaxException e) { e.printStackTrace(); } } public static String getTestKey() { return testKey; } public static void setTestKey(String testKey) { DaapLedgerCaller.testKey = testKey; } private static void setContractDst(String dst) { contractDst = dst; } public static String getContractDst() { return contractDst; } } <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>biz.pdxtech.daap</groupId> <artifactId>daap-ledger</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>daap-ledger</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <jdk.version>1.8</jdk.version> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <driver.version>1.2.5</driver.version> <protostuff.version>1.5.2</protostuff.version> </properties> <dependencies> <!-- bcdriver api --> <dependency> <groupId>biz.pdxtech.daap</groupId> <artifactId>daap-bcdriver</artifactId> <version>${driver.version}</version> </dependency> <!-- ethbcdriver --> <dependency> <groupId>biz.pdxtech.daap</groupId> <artifactId>daap-ethbcdriver</artifactId> <version>${driver.version}</version> </dependency> <!-- protoStuff --> <dependency> <groupId>io.protostuff</groupId> <artifactId>protostuff-core</artifactId> <version>${protostuff.version}</version> </dependency> <dependency> <groupId>io.protostuff</groupId> <artifactId>protostuff-runtime</artifactId> <version>${protostuff.version}</version> </dependency> </dependencies> <repositories> <repository> <id>pdx-release</id> <name>biz.pdxtech</name> <url>http://daap.pdx.life:8081/nexus/content/repositories/releases</url> </repository> </repositories> </project>
6100ffb8f6ce961782bfd43ffe9e19bb9a13b049
[ "Markdown", "Java", "Maven POM" ]
4
Java
PDXTechnologies/daap-ledger
dc0e9ac18a1b86d4041ecf94247e4d77abee2611
d9b2c5f4fb1437ec1e10e58c01c1de2987d378c7
refs/heads/master
<repo_name>wlingxiao/Flasky-FrontEnd<file_sep>/src/app/app.js import angular from 'angular'; import '@uirouter/angularjs' import 'bootstrap/dist/css/bootstrap.min.css' import apiConfig from './api.config' import routesConfig from './routes.config' import './home' import './login' import './signup' import './user' import './post' import './daily' const app = angular.module('app', ['ui.router', 'home', 'login', 'signup', 'user', 'post', 'daily']); app.config(apiConfig); app.config(routesConfig);<file_sep>/src/app/user/users.service.js export default function ($http, $httpParamSerializerJQLike) { this.listUsers = function (filter) { const usersUrl = '/users'; return $http.get(usersUrl, { params: $httpParamSerializerJQLike(filter) }) } }<file_sep>/mock/posts.js const faker = require('faker') faker.locale = 'zh_CN'; module.exports = function () { const posts = { size: 100, data: [] }; for (let i = 0; i < 10; i++) { posts.data.push({ id: i, title: faker.lorem.sentence(), content: faker.lorem.text(), 'create_time': Date.parse(faker.date.past()), 'image': faker.image.nature() }) } return posts }()<file_sep>/mock/db.js module.exports = function () { return { posts: require('./posts'), users: require('./users') } }<file_sep>/src/app/daily/index.js import augular from 'angular' import viewDailyDirective from './viewDaily.directive' import dailyService from './daily.service' import './news.css' export default augular.module('daily', []) .directive('viewNews', viewDailyDirective) .service('dailyService', dailyService);<file_sep>/src/app/api.config.js // api interceptor import _ from 'lodash' export default function ($httpProvider) { $httpProvider.interceptors.push(function ($q) { return { 'request': function (config) { if (!_.endsWith(config.url, '.html')) { config.url = '/api/v1' + config.url; } return config || $q.when(config); } } }) }<file_sep>/src/app/signup/index.js import augular from 'angular' import signupDirective from './signup.directive' import {validateUsernameExist, validateEmailExist, hasSuccessOrError} from './validation.directive' export default angular.module('signup', []) .directive('signUp', signupDirective) .filter('validateUsernameExist', validateUsernameExist) .filter('validateEmailExist', validateEmailExist) .filter('hasSuccessOrError', hasSuccessOrError);<file_sep>/src/app/user/datepicker.js import $ from 'jquery' import 'bootstrap-datepicker' import 'bootstrap-datepicker/dist/css/bootstrap-datepicker.min.css' export const initDatePicker = function () { initDatePicker($('#last-login-time .input-daterange')); initDatePicker($('#sign-up-time .input-daterange')); function initDatePicker(jqeuryElement) { jqeuryElement.datepicker({ format: 'yyyy-mm-dd', clearBtn: true, language: 'zh-CN', todayHighlight: true }) } }; export const clearDateRanger = function () { $('.input-daterange input').each(function () { $(this).datepicker('clearDates'); }); }; <file_sep>/src/app/user/userManager.directive.js import userManagerTpl from './user-manager.tpl.html' import {initDatePicker, clearDateRanger} from './datepicker' export default function (usersService, $log) { return { restrict: 'E', scope: {}, template: userManagerTpl, link: function (scope, element) { initDatePicker() usersService.listUsers({}).then(function (response) { if (response['status'] === 200) { transformUsers(response, scope) } })['catch'](function (response) { $log.error(response) }); } } } function transformUsers(response, $scope) { const data = response['data']; $scope.totalItems = data['size']; const responseUsers = data['data']; $scope.totalPage = parseInt($scope.totalItems / 10) + 1; const users = []; for (let i = 0; i < responseUsers.length; i++) { const item = responseUsers[i]; users.push({ id: item['id'], username: item['username'], email: item['email'], signUpTime: item['sign_up_time'], lastVisitTime: item['last_visit_time'] }) } $scope.users = users; }<file_sep>/src/app/home/home.directive.js import indexTpl from './home.tpl.html' export default function ($http, postsService, $log) { return { restrict: 'E', template: indexTpl, scope: {}, link: function (scope, element) { postsService.listPosts().then(function (response) { if (response['status'] === 200) { const responseData = response['data']; scope.totalItems = responseData['size']; scope.currentPage = 1; scope.maxSize = 5; scope.posts = transformPosts(responseData['data']); } })['catch'](function (error) { $log.error(error) }) } } } function transformPosts(rawPosts) { const posts = []; rawPosts.map(function (post) { posts.push({ id: post['id'], title: post['title'], summary: post['summary'], createTime: post['create_time'], image: post['image'] }) }); return posts; }<file_sep>/src/app/post/posts.service.js export default function ($http, $httpParamSerializerJQLike) { const postUrl = "/posts"; this.loadPosts = function (postId) { if (postId) { return $http.get(postUrl + "/" +postId); } else { return $http.get(postUrl); } } this.createPost = function (post) { return $http({ method: 'POST', url: postUrl, headers: {'Content-Type': 'application/json;charset=UTF-8'} }) } }<file_sep>/src/app/daily/daily.service.js export default function ($http, $httpParamSerializerJQLike) { const dailyNews = '/dailies/news'; this.getNewsById = function (newsId) { return $http.get(dailyNews + '/' + newsId) }; }<file_sep>/src/app/home/index.js import augular from 'angular' import homeDirective from './home.directive' import postsService from './posts.service' import './home.css' export default augular.module('home', []) .directive('home', homeDirective) .service('postsService', postsService);<file_sep>/README.md #### run json mock server `cd mock` `json-server db.js` #### run posts server `json-server --watch posts.json`<file_sep>/mock/README.md #### run mock server `json-server db.js`<file_sep>/src/app/signup/validation.directive.js const validateUsernameExist = function ($http, $q) { return { require: 'ngModel', link: function (scope, element, attributes, ngModel) { ngModel.$asyncValidators.validateUsernameExist = function (modleValue, viewValue) { var validateUsernameUrl = '/auth/validate_username/'; return $http({ method: 'POST', url: validateUsernameUrl + modleValue }).then(function (response) { if (response.data['code'] === 200) { return true; } else { return $q.reject(response['msg']); } })['catch'](function (response) { return $q.reject('请求错误') }); } } } }; const validateEmailExist = function ($http, $q) { return { require: 'ngModel', link: function (scope, element, attributes, ngModel) { ngModel.$asyncValidators.validateEmailExist = function (modelValue, viewValue) { var validateEmailUrl = '/auth/validate_email/'; return $http({ method: 'POST', url: validateEmailUrl + modelValue }).then(function (response) { if (response.data['code'] === 200) { return true } else { return $q.reject(response['msg']) } })['catch'](function (response) { return $q.reject('请求错误'); }) } } } }; const hasSuccessOrError = function () { return function (input, hasSuccess, hasError) { return input ? hasSuccess : hasError; } }; export {validateUsernameExist, validateEmailExist, hasSuccessOrError}<file_sep>/src/app/routes.config.js export default function ($stateProvider, $locationProvider) { $locationProvider.html5Mode(true); const homeState = { name: 'home', url: '/', template: '<home></home>' }; const signUpState = { name: 'signUp', url: '/sign_up', template: '<sign-up></sign-up>' }; const loginState = { name: 'login', url: '/login', template: '<login></login>' }; const userState = { name: 'viewUser', url: '/view_user', template: '<user-manager></user-manager>' }; const postState = { name: 'post', url: '/post/:postId', template: '<view-post post-id="{{ postId }}"></view-post>', controller: function ($scope, $stateParams) { $scope.postId = $stateParams.postId } }; const createPostState = { name: 'createPost', url: '/create_post', template: '<create-post></create-post>' }; const viewDailyState = { name: 'viewDaily', url: '/view_news/:newsId', template: '<view-news news-id="{{ newsId }}"></view-news>', controller: function ($scope, $stateParams) { $scope.newsId = $stateParams.newsId } } $stateProvider.state(homeState); $stateProvider.state(loginState); $stateProvider.state(signUpState); $stateProvider.state(userState); $stateProvider.state(postState); $stateProvider.state(createPostState); $stateProvider.state(viewDailyState); }<file_sep>/src/app/post/comments.service.js export default function ($http, $httpParamSerializerJQLike) { const postUrl = "/comments"; this.loadComments = function (postId) { if (postId) { return $http.get(postUrl + "?postId=" + postId); } else { return $http.get(postUrl); } } }<file_sep>/src/app/login/index.js import augular from 'angular' import 'angular-messages' import loginDirective from './login.directive' export default angular.module('login', ['ngMessages']) .directive('login', loginDirective)<file_sep>/src/app/post/commentToUser.directive.js import commnetToUserTpl from './comment-to-user.tpl.html' export default function () { return function () { return { replace: true, scope: false, restrict: 'E', template: commnetToUserTpl, link: function (scope, element) { } } } }
cad07a139752232c1d1a2d9e43192e6c7d6b7c68
[ "JavaScript", "Markdown" ]
20
JavaScript
wlingxiao/Flasky-FrontEnd
68f67e9ed014e11de0da9fd86debce4273fa34bd
db2cb2701ca9bfaba2fe189977535d000bec4e19
refs/heads/main
<file_sep># ab_log_inserter ##Create db and table ``` CREATE DATABASE ab_log_db; CREATE TABLE weather ( w_id serial not null primary key, temp_val float NOT NULL, hum_val float NOT NULL, w_date timestamp default NULL ); ``` <file_sep>package main import ( "fmt" "strings" "net/http" "io/ioutil" "database/sql" _ "github.com/lib/pq" "time" ) const ( DB_USER = "postgres" DB_PASSWORD = "" DB_NAME = "ab_log_db" ) func main() { temp, hum :=getLight("http://192.168.71.74/sec/?pt=32&cmd=get") //fmt.Println(light) inserter(temp, hum) } func inserter(temp_val string,hum_val string) { dbinfo := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable", DB_USER, DB_PASSWORD, DB_NAME) db, err := sql.Open("postgres", dbinfo) checkErr(err) defer db.Close() fmt.Println("# Inserting values") dt := time.Now() var lastInsertId int err = db.QueryRow("INSERT INTO weather (temp_val,hum_val,w_date) VALUES($1,$2,$3) returning w_id;", temp_val,hum_val, dt).Scan(&lastInsertId) checkErr(err) //fmt.Println("last inserted id =", lastInsertId) } func getLight(host string )(temp_val string, hum_val string){ resp, err := http.Get(host) if err != nil { fmt.Println(err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err) return } //fmt.Println(string(body)) temphum := strings.Replace(string(body),"/",":",-1) temphum22 := strings.Split(temphum,":") temp_val = temphum22[1] hum_val = temphum22[3] fmt.Println(temp_val, hum_val) return temp_val, hum_val } func checkErr(err error) { if err != nil { panic(err) } }
3b02dc297de5215ad134afa2f6ee33544cd0c174
[ "Markdown", "Go" ]
2
Markdown
enzo1920/ab_log_dht22
b0333ad4bb1c298fee3fe63cb83586007b569009
c89fb56820ed1672692cd06457519731cfe20eed
refs/heads/main
<file_sep>require 'serverspec' # Required by serverspec set :backend, :exec describe file('/usr/bin/go') do it { should be_executable } end describe file('/usr/bin/gofmt') do it { should be_executable } end describe file('/usr/bin/godoc') do it { should be_executable } end describe command('go version') do its(:stdout) { should match /go version/ } its(:exit_status) { should eq 0 } end
4b034e3f529e0c3ab46e61a65b4fa07cc49def4a
[ "Ruby" ]
1
Ruby
juju4/ansible-golang
cd0cc0718b79b8e6e332e829ef30ad033813eb23
b0674a29d23ce24c33885ac787b46e1350bc26f0
refs/heads/master
<repo_name>AlaricZeng/AlaricLightStory<file_sep>/constants.py # Uploaded image path UPLOAD_IMG_FOLDER = 'static/images/' UPLOAD_ZOOM_IMG_FOLDER = 'static/images/thumbnails' UPLOAD_STORY_FOLDER = 'static/stories/' ALLOWED_IMG_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) ALLOWED_STORY_EXTENSIONS = set(['md']) MARKDOWN_EXTENSION = '.md' #Mysql config MYSQL_USER = 'root' MYSQL_PASSWORD = '<PASSWORD>' MYSQL_DB = 'AlaricLightStory' MYSQL_HOST = 'localhost' #Admin logic ADMIN_USER = 'AlaricZeng' ADMIN_PASSWORD ='<PASSWORD>' #Display picture DISPLAY_PICTURE = "1" NOT_DISPLAY_PICTURE = "0"<file_sep>/migrationScript/create_stories_table.sql CREATE TABLE IF NOT EXISTS stories ( id INT AUTO_INCREMENT, title VARCHAR(255) NOT NULL, created_at DATETIME, PRIMARY KEY(id) );<file_sep>/migrationScript/create_photos_table.sql CREATE TABLE IF NOT EXISTS photos ( id INT AUTO_INCREMENT, name VARCHAR(255) NOT NULL, tag VARCHAR(50), linked_page_index VARCHAR(255), uploaded_at DATETIME, created_at DATETIME, iso VARCHAR(20), aperture VARCHAR(20), shutter_speed VARCHAR(20), display BOOLEAN, PRIMARY KEY(id) );<file_sep>/static/stories/Olympic National Park Tour.md # This is the story ``` Pass a code here Code ``` * Item1 * Item2 * Item3 `Test` ![](static/images/DSC01482-M.jpg)<file_sep>/static/js/admin-component.js new Vue({ el: '#image-management-container', data: { select: null, storyTitles: ['None'], stories: {}, imageTableHeaders: [ { text: 'Pictures', align: 'left', sortable: false, value: 'url' }, { text: 'Linked Story', align: 'left', value: 'story' }, { text: 'Display?', align: 'left', value: 'display' }, { text: 'Actions', value: 'url', sortable: false } ], imageInfo: [], editDialog:false, editedIndex: -1, editedItem: { id: '', url: '', story: '', display: false }, defaultItem: { id: '', url: '', story: '', display: false }, }, mounted: function() { var that = this; $.get( "http://127.0.0.1:5000/admin/get_story_list") .done(function(data) { data.forEach(function(value, index) { that.stories[value[0]] = value[1] that.storyTitles.push(that.generateStoryTitle(value[0], value[1])); }); }); $.get( "http://127.0.0.1:5000/admin/get_image_list") .done(function(data) { data.forEach(function(value, index) { that.imageInfo.push({ id: value[0], url: '/static/images/thumbnails/' + value[1], story: that.stories[value[2]] ? that.generateStoryTitle(value[2], that.stories[value[2]]) : 'none', display: value[3] }); }); }); }, methods: { submit: function() { $('#upload-image-form').submit(); }, editItem: function(item) { this.editedIndex = this.imageInfo.indexOf(item); this.editedItem = Object.assign({}, item); this.editDialog = true; }, deleteItem: function(item) { const index = this.imageInfo.indexOf(item); var confirmed = confirm('Are you sure you want to delete this item?'); var that = this; if (confirmed) { $.post( "http://127.0.0.1:5000/admin/delete_image", {id: item.id}) .done(function(data) { that.imageInfo.splice(index, 1) }); } }, save: function() { if (this.editedIndex > -1) { var that = this; $.post( "http://127.0.0.1:5000/admin/edit_image_info", {id: that.editedItem.id, storyTitle: that.editedItem.story, display: that.editedItem.display}) .done(function(data) { Object.assign(that.imageInfo[that.editedIndex], that.editedItem); }); } else { this.imageInfo.push(this.editedItem); } this.close(); }, close: function() { this.editDialog = false; setTimeout(() => { this.editedItem = Object.assign({}, this.defaultItem); this.editedIndex = -1; }, 300); }, generateStoryTitle: function(storyIndex, storyTitle) { return storyIndex + ' - ' + storyTitle } } }); new Vue({ el: '#story-management-container', data: { storyTableHeaders: [ { text: 'Id', align: 'left', value: 'id' }, { text: 'Title', align: 'left', value: 'title' }, { text: 'Actions', value: 'id', sortable: false } ], storyInfo: [], editDialog:false, editedIndex: -1, editedItem: { id: '', title: '' }, defaultItem: { id: '', title: '' }, rules: { required: value => !!value || 'Required.' }, uploadedStoryFile: '', uploadedStoryTitle: '', editedStoryFile: '' }, mounted: function() { var that = this; $.get( "http://127.0.0.1:5000/admin/get_story_list") .done(function(data) { data.forEach(function(value, index) { that.storyInfo.push({ id: value[0], title: value[1] }) }); }); }, computed: { uploadNewStoryFormIsValid: function() { return this.uploadedStoryTitle && this.uploadedStoryFile; }, uploadExistStoryFormIsValid: function() { return this.editedItem.title && this.editedStoryFile; }, }, methods: { updateNewStoryFile: function(event) { this.uploadedStoryFile = event.target.files; }, updateExistStoryFile: function(event) { this.editedStoryFile = event.target.files; }, submit: function() { $('#upload-story-form').submit(); }, editItem: function(item) { this.editedIndex = this.storyInfo.indexOf(item); this.editedItem = Object.assign({}, item); this.editDialog = true; }, deleteItem: function(item) { const index = this.storyInfo.indexOf(item); var confirmed = confirm('Are you sure you want to delete this story?'); var that = this; if (confirmed) { $.post( "http://127.0.0.1:5000/admin/delete_story", {id: item.id}) .done(function(data) { that.storyInfo.splice(index, 1) }); } }, save: function() { if (this.editedIndex > -1) { $('#edit-story-form').submit(); Object.assign(that.storyInfo[that.editedIndex], that.editedItem); } else { this.storyInfo.push(this.editedItem); } this.close(); }, downloadItem: function(item) { $.post( "http://127.0.0.1:5000/admin/download_story", {title: item.title}) .done(function(data) { window.location.href = data; }); }, close: function() { this.editDialog = false; setTimeout(() => { $('#update-exist-file').val(''); this.editedStoryFile = ''; this.editedItem = Object.assign({}, this.defaultItem); this.editedIndex = -1; }, 300); } } });<file_sep>/AlaricLightStory.wsgi import sys sys.path.insert(0, '/var/www/html/AlaricLightStory') from AlaricLightStory import app as application<file_sep>/try.py import markdown from flask import Flask from flask import render_template from flask import Markup app = Flask(__name__) @app.route('/') def index(): content = """ Chapter ======= Section ------- * Item 1 * Item 2 """ content = Markup(markdown.markdown(content)) return render_template('index.html', **locals()) app.run(debug=True)<file_sep>/AlaricLightStory.py from __future__ import print_function import sys import os from flask import Flask, render_template, request, redirect, url_for, send_from_directory, jsonify, Markup, send_file from flask_mysqldb import MySQL from datetime import datetime from werkzeug import secure_filename import markdown2 from constants import * app = Flask(__name__) app.config['MYSQL_USER'] = 'root' app.config['MYSQL_PASSWORD'] = '<PASSWORD>' app.config['MYSQL_DB'] = 'AlaricLightStory' app.config['MYSQL_HOST'] = 'localhost' app.config['UPLOAD_IMG_FOLDER'] = UPLOAD_IMG_FOLDER app.config['UPLOAD_ZOOM_IMG_FOLDER'] = UPLOAD_ZOOM_IMG_FOLDER app.config['UPLOAD_STORY_FOLDER'] = UPLOAD_STORY_FOLDER app.config['ALLOWED_IMG_EXTENSIONS'] = ALLOWED_IMG_EXTENSIONS app.config['ALLOWED_STORY_EXTENSIONS'] = ALLOWED_STORY_EXTENSIONS mysql = MySQL(app) def allowed_img_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in app.config['ALLOWED_IMG_EXTENSIONS'] def allowed_story_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in app.config['ALLOWED_STORY_EXTENSIONS'] @app.route('/') def first_page(): cur = mysql.connection.cursor() fetch_all_images_query = "SELECT name, tag, linked_page_index FROM photos WHERE display=True" cur.execute(fetch_all_images_query) all_images = cur.fetchall() fetch_all_stories_query = "SELECT id, title, created_at FROM stories" cur.execute(fetch_all_stories_query) all_stories = cur.fetchall() cur.close() return render_template('index.html', images = all_images, stories = all_stories) @app.route('/stories') def get_story_content(): story_id = request.args.get("story_id") cur = mysql.connection.cursor() fetch_story_title_query = "SELECT title FROM stories WHERE id =" + story_id cur.execute(fetch_story_title_query) story_title = cur.fetchone()[0] fetch_next_story_title_query = "SELECT id, title FROM stories WHERE id >" + story_id + " ORDER BY id" cur.execute(fetch_next_story_title_query) next_story = cur.fetchone() if next_story: next_story_id = next_story[0] next_story_title = next_story[1] else: fetch_first_story_title_query = "SELECT id, title FROM stories ORDER BY id" cur.execute(fetch_first_story_title_query) next_story = cur.fetchone() next_story_id = next_story[0] next_story_title = next_story[1] cur.close() with open(UPLOAD_STORY_FOLDER + story_title + ".md", "r") as f: content = f.read() content = Markup(markdown2.markdown(content, extras=["fenced-code-blocks"])) return render_template("story.html", content = content, next_story_id = next_story_id, next_story_title = next_story_title) @app.route('/display') def display_photos(): cur = mysql.connection.cursor() query = "SELECT name, tag FROM photos" cur.execute(query) data = cur.fetchall() cur.close() return jsonify(data) @app.route('/login') def login_page(): return render_template('login.html') @app.route('/admin', methods = ['POST']) def admin_default(): username = request.form.get('username') password = request.form.get('<PASSWORD>') is_logged_in = request.args.get('is_logged_in') if is_logged_in: return render_template('admin.html') elif username == ADMIN_USER and password == <PASSWORD>: return render_template('admin.html') else: return render_template('login.html') @app.route('/admin/get_story_list') def get_story_list(): cur = mysql.connection.cursor() query = "SELECT id, title FROM stories" cur.execute(query) data = cur.fetchall() cur.close() return jsonify(data) @app.route('/admin/get_image_list') def get_image_list(): cur = mysql.connection.cursor() query = "SELECT id, name, linked_page_index, display FROM photos" cur.execute(query) data = cur.fetchall() cur.close() return jsonify(data) @app.route('/admin/edit_image_info', methods = ['POST']) def edit_image_info(): id = request.form.get('id') storyTitle = request.form.get('storyTitle') display = request.form.get('display') if (storyTitle == 'None'): linked_page_index = 'NULL' else: linked_page_index = storyTitle.split("-")[0].strip() cur = mysql.connection.cursor() query = "UPDATE photos SET linked_page_index = " + linked_page_index + ", display = " + display + " WHERE id = " + id; cur.execute(query) mysql.connection.commit() cur.close() return jsonify(id) @app.route('/admin/delete_image', methods = ['POST']) def delete_image(): id = request.form.get('id') cur = mysql.connection.cursor() query = "DELETE FROM photos WHERE id = " + id cur.execute(query) mysql.connection.commit() cur.close() return jsonify(id) @app.route('/admin/upload_image', methods = ['POST']) def upload_image(): file = request.files['file'] tag = request.form.get('tag') zoom_file = request.files['zoom_file'] linked_page = request.form.get('linked_page') if (linked_page == 'None'): linked_page_index = None else: linked_page_index = linked_page.split("-")[0].strip() if request.form.get('display') == "display": display = DISPLAY_PICTURE else: display = NOT_DISPLAY_PICTURE if file and allowed_img_file(file.filename) and zoom_file and allowed_img_file(zoom_file.filename): filename = secure_filename(file.filename) zoom_filename = secure_filename(zoom_file.filename) file.save(os.path.join(app.config['UPLOAD_IMG_FOLDER'], filename)) zoom_file.save(os.path.join(app.config['UPLOAD_ZOOM_IMG_FOLDER'], zoom_filename)) cur = mysql.connection.cursor() query = "INSERT INTO photos (name, tag, linked_page_index, created_at, display) VALUES('" + filename + "', '" + tag + "', '" + linked_page_index + "', '" + datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "', '" + display + "')" cur.execute(query) mysql.connection.commit() cur.close() return redirect(url_for('admin_default', is_logged_in = True), code=307) @app.route('/admin/upload_story', methods = ['POST']) def upload_story(): file = request.files['file'] title = request.form.get('title') if file and allowed_story_file(file.filename): filename = title + MARKDOWN_EXTENSION file.save(os.path.join(app.config['UPLOAD_STORY_FOLDER'], filename)) cur = mysql.connection.cursor() query = "INSERT INTO stories (title, created_at) VALUES('" + title + "', '" + datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "')" cur.execute(query) mysql.connection.commit() cur.close() return redirect(url_for('admin_default', is_logged_in = True), code=307) @app.route('/admin/edit_story_info', methods = ['POST']) def edit_story_info(): id = request.form.get('id') file = request.files['file'] title = request.form.get('title') if file and allowed_story_file(file.filename): filename = title + MARKDOWN_EXTENSION file.save(os.path.join(app.config['UPLOAD_STORY_FOLDER'], filename)) cur = mysql.connection.cursor() query = "UPDATE stories SET title = '" + title + "' WHERE id = " + id; print(query, file=sys.stderr) cur.execute(query) mysql.connection.commit() cur.close() return redirect(url_for('admin_default', is_logged_in = True), code=307) @app.route('/admin/delete_story', methods = ['POST']) def delete_story(): id = request.form.get('id') cur = mysql.connection.cursor() query = "UPDATE photos SET linked_page_index = NULL WHERE linked_page_index = " + id; cur.execute(query) query = "DELETE FROM stories WHERE id = " + id cur.execute(query) mysql.connection.commit() cur.close() return jsonify(id) @app.route('/admin/download_story', methods = ['POST']) def download_story(): title = request.form.get('title') filename = title + MARKDOWN_EXTENSION file = os.path.join(app.config['UPLOAD_STORY_FOLDER'], filename) return file if __name__ == '__main__': app.run()
04c44054ca6e7a554fdbba0bdb99403192cb454e
[ "Markdown", "SQL", "Python", "JavaScript" ]
8
Python
AlaricZeng/AlaricLightStory
124520611098e808c8865bf629e7f8870d103d9c
115a59c7968be605bf3afa72d983f0feed694918
refs/heads/master
<file_sep># Starting with Selenium-Java <file_sep>package Pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; public class SignInPage extends BasePage{ public SignInPage(WebDriver driver) { super(driver); } public AuthenticationPage newUser(){ driver.findElement(By.xpath("//*[@id=\"header\"]/div[2]/div/div/nav/div[1]/a")).click(); return new AuthenticationPage(driver); } }
7598b07b83a7b962596434535d674ec7bd5b3b13
[ "Markdown", "Java" ]
2
Markdown
robertoferraz02/Testing-with-Selenium-and-Java
c069a1734b33954dcf8cceed6421b8f2cb3a88b1
f611fc96cc24ae6682884ec70bf98594ad33d5f2
refs/heads/master
<repo_name>patsonm/Algo_Python<file_sep>/dynArray.py import ctypes #implementing a dynamic array class DynamicArray(object): def __init__(self): self.n=0 self.cap=1 self.A = self.make_array(self.cap) def __len__(self): return self.n def __getitem__(self, k): if not 0 <=k < self.n: return IndexError('K is out of bounds') return self.A[k] def append(self, ele): if self.n == self.cap: self._resize(2*self.cap) #double if end of array self.A[self.n]=ele self.n+=1 def _resize(self, new_cap): B = self.make_array(new_cap) for k in range(self.n): B[k]=self.A[k] self.A=B self.cap=new_cap def make_array(self, new_cap): return (new_cap*ctypes.py_object)() ### Testing arr= DynamicArray() arr.append(1) print(len(arr))
8d2d804037a099afe364c630df1e88da56b80ec5
[ "Python" ]
1
Python
patsonm/Algo_Python
7cfda2b007747d9ef591ea1a4c36f8144935c9c3
eff187c834416ba29ef357cf16d3de6e0284b0aa
refs/heads/master
<file_sep>//This code is from TechTalk.SpecFlow/StringExtensions.cs //The pre-release version of specflow 3 had these as public and we started using them in our testing. //They were set to internal in Specflow commit #1408 using System; namespace SeleniumSpecFlow.Classes { public static class StringExtensions { public static bool IsNullOrEmpty(this string value) { return string.IsNullOrEmpty(value); } public static bool IsNotNullOrEmpty(this string value) { return !string.IsNullOrEmpty(value); } public static bool IsNullOrWhiteSpace(this string value) { if (value == null) return true; for (int i = 0; i < value.Length; i++) { if (!char.IsWhiteSpace(value[i])) return false; } return true; } public static bool IsNotNullOrWhiteSpace(this string value) { return !value.IsNullOrWhiteSpace(); } public static string StripWhitespaces(this string value) { return value.Replace(" ", "").Replace("\n", "").Replace("\r", ""); } /// <summary> /// Returns empty string if the value is null, othervise the original value. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>Empty string or the orinal value.</returns> public static string AsEmpty(this string value) { return string.IsNullOrEmpty(value) ? string.Empty : value; } /// <summary> /// Returns null if the value is empty, othervise the original value. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>Null or the orinal value.</returns> public static string AsNull(this string value) { return string.IsNullOrEmpty(value) ? null : value; } } } <file_sep>using OpenQA.Selenium; using System; namespace PageObjects { public class AukroHomePage : BasePage { private bool aukroOfferPopUpClosed; private IWebDriver _webDriver; private string _baseUrl; private const string PageUrl = "http://www.aukro.cz/"; public AukroHomePage(IWebDriver webDriver, string baseUrl) { _baseUrl = baseUrl; _webDriver = webDriver; webDriver.Url = baseUrl + PageUrl; webDriver.Navigate(); _webDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(3); if (!this.IsVisible()) { throw new InvalidOperationException(String.Format("The current browser window is not on the expected page.")); } } #region Constructors #endregion #region Public Methods public bool IsVisible() { return _webDriver.Url.Contains("aukro.cz"); } public bool VerifyReturnMoneyAllOffers() { var allOffers = _webDriver.FindElement(By.TagName("list-view")).FindElements(By.TagName("list-card")); bool result = true; for (int i = 1; i <= allOffers.Count; i++) { if ((i == 5)||(i==45)) i++; try { if(!aukroOfferPopUpClosed) this.CloseAukroOfferPopUpWindow(); if (!_webDriver.FindElement(By.CssSelector($"list-card.propagation-bold-title:nth-child({i}) > div:nth-child(1) > div:nth-child(2) > div:nth-child(6) > div:nth-child(1) > div:nth-child(4) > span:nth-child(1) > svg-icon:nth-child(1) > div:nth-child(1) > svg:nth-child(1) > circle:nth-child(2)")).Displayed) throw new Exception($"Offer with index {i} does not contain money back guarantee."); } catch (Exception) { try { this.CloseAukroOfferPopUpWindow(); if (!_webDriver.FindElement(By.CssSelector($"list-card.hot-auction:nth-child({i}) > div:nth-child(1) > div:nth-child(2) > div:nth-child(6) > div:nth-child(1) > div:nth-child(4) > span:nth-child(1) > svg-icon:nth-child(1) > div:nth-child(1) > svg:nth-child(1) > circle:nth-child(2)")).Displayed) throw new Exception($"Offer with index {i} does not contain money back guarantee."); } catch (Exception) { if (!aukroOfferPopUpClosed) this.CloseAukroOfferPopUpWindow(); if (!_webDriver.FindElement(By.CssSelector($".product-sorting > list-view:nth-child(4) > list-card:nth-child({i}) > div:nth-child(1) > div:nth-child(2) > div:nth-child(6) > div:nth-child(1) > div:nth-child(4) > span:nth-child(1) > svg-icon:nth-child(1) > div:nth-child(1) > svg:nth-child(1) > circle:nth-child(2)")).Displayed) throw new Exception($"Offer with index {i} does not contain money back guarantee."); } } } return result; } public void CloseAukroOfferPopUpWindow() { try { if (_webDriver.FindElement(By.CssSelector("i.vertical-bottom")).Displayed) { aukroOfferPopUpClosed = true; _webDriver.FindElement(By.CssSelector("i.vertical-bottom")).Click(); } } catch (Exception) { } } public void ClickToAgreementButton() { agreementButton.Click(); } public void ClickToAukroIcon() { aukroIcon.Click(); } public void ClickToCategoryButton() { categoryButton.Click(); } public void ClickToCollectiblesOption() { collectiblesOption.Click(); } public void ClickToAntiquesAndArtOption() { antiquesAndArtOption.Click(); } public void SelectReturnMoneyGuaranteeCheckbox() { var elem = _webDriver.FindElement(By.CssSelector(".filter-sidebar-wrapper > filter:nth-child(1) > parameters:nth-child(2) > filter-parameter-attribute:nth-child(3) > span:nth-child(1)")); IJavaScriptExecutor js = (IJavaScriptExecutor)_webDriver; string title = (string)js.ExecuteScript("arguments[0].scrollIntoView(true);", elem); returnMoneyGuaranteeCheckbox.Click(); } public void SelectFreeShippingCheckbox() { freeShippingCheckbox.Click(); } #endregion #region Private private IWebElement agreementButton { get { return _webDriver.FindElement(By.CssSelector(".fc-cta-consent")); } } private IWebElement aukroIcon { get { return _webDriver.FindElement(By.CssSelector("#Layer_1")); } } private IWebElement categoryButton { get { return _webDriver.FindElement(By.CssSelector("#ssr-done > app-header > div:nth-child(3) > div > div.display-inline-block-min-tablet > button")); } } private IWebElement collectiblesOption { get { return _webDriver.FindElement(By.CssSelector("div.nav-section:nth-child(4) > top-level-category:nth-child(1) > div:nth-child(1) > a:nth-child(2)")); } } private IWebElement antiquesAndArtOption { get { return _webDriver.FindElement(By.CssSelector("div.nav-section:nth-child(4) > top-level-category:nth-child(2) > div:nth-child(1) > a:nth-child(2)")); } } private IWebElement returnMoneyGuaranteeCheckbox { get { return _webDriver.FindElement(By.CssSelector("#mat-checkbox-6 > label:nth-child(1) > span:nth-child(2) > span:nth-child(2)")); } } private IWebElement freeShippingCheckbox { get { return _webDriver.FindElement(By.CssSelector("#mat-checkbox-7 > label:nth-child(1) > span:nth-child(2) > span:nth-child(2)")); } } #endregion } } <file_sep>using System; namespace PageObjects { public class BasePage { } } <file_sep>using System; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Firefox; namespace SeleniumSpecFlow { /// <summary> /// Class to generate WebDriver /// </summary> public static class WebDriverFactory { private static IWebDriver _webDriver; public static IWebDriver WebDriver { get { return _webDriver; } } public static void Initialize(BrowserType browserType) { switch (browserType) { case BrowserType.Chrome: ChromeOptions options = new ChromeOptions(); options.AddArgument("--start-maximized"); _webDriver = new ChromeDriver(options); break; case BrowserType.Firefox: FirefoxOptions firefoxBrowser = new FirefoxOptions(); firefoxBrowser.AddArgument("--start-maximized"); _webDriver = new FirefoxDriver(firefoxBrowser); break; default: throw new Exception("Unknown browser type"); } } public static void CloseBrowser(BrowserType browserType) { switch (browserType) { case BrowserType.Chrome: _webDriver.Quit(); break; case BrowserType.Firefox: _webDriver.Quit(); break; default: throw new Exception("Unknown browser type"); } } } public enum BrowserType { Chrome, Firefox } } <file_sep>using PageObjects; using TechTalk.SpecFlow; namespace SeleniumSpecFlow.metadata { [Binding] public class BaseSteps { public BasePage CurrentPage { get; set; } [BeforeTestRun] public static void BeforeTest() { //WebDriverFactory.Initialize(BrowserType.Chrome); WebDriverFactory.Initialize(BrowserType.Firefox); } [AfterScenario] public static void AfterScenario() { //WebDriverFactory.CloseBrowser(BrowserType.Chrome); WebDriverFactory.CloseBrowser(BrowserType.Firefox); } } }<file_sep>using PageObjects; using TechTalk.SpecFlow; using SeleniumSpecFlow.metadata; using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace SeleniumSpecFlow.Features { [Binding] public class AukroHomePageTestSteps : BaseSteps { [Given(@"Load Current page")] public void GivenLoadCurrentPage() { CurrentPage = new AukroHomePage(WebDriverFactory.WebDriver, string.Empty); } [Given(@"Close pop up Agreement")] public void GivenClosePopUpAgreement() { if (!(CurrentPage is AukroHomePage)) throw new System.Exception("Bad page"); ((AukroHomePage)this.CurrentPage).ClickToAgreementButton(); } [Given(@"Close pop up Aukro Offer")] public void GivenClosePopUpAukroOffer() { if (!(CurrentPage is AukroHomePage)) throw new System.Exception("Bad page"); ((AukroHomePage)this.CurrentPage).ClickToAukroIcon(); } [When(@"I select Category Button")] public void WhenISelectCategoryButton() { if (!(CurrentPage is AukroHomePage)) throw new System.Exception("Bad page"); ((AukroHomePage)this.CurrentPage).ClickToCategoryButton(); } [When(@"I select ""(.*)"" Option")] public void WhenISelectOption(string aukroOption) { switch (aukroOption) { case "Collectibles": if (!(CurrentPage is AukroHomePage)) throw new System.Exception("Bad page"); ((AukroHomePage)this.CurrentPage).ClickToCollectiblesOption(); break; case "AntiquesAndArt": if (!(CurrentPage is AukroHomePage)) throw new System.Exception("Bad page"); ((AukroHomePage)this.CurrentPage).ClickToAntiquesAndArtOption(); break; default: throw new Exception(string.Format("{0} not supported value.", aukroOption)); } } [When(@"I select Parameter Options Checkboxes")] public void WhenISelectParameterOptionsCheckboxes(Table table) { if (table.ContainsColumn("ReturnMoneyGuarantee") && table.Rows[0]["ReturnMoneyGuarantee"].Contains("check")) { if (!(CurrentPage is AukroHomePage)) throw new System.Exception("Bad page"); ((AukroHomePage)this.CurrentPage).SelectReturnMoneyGuaranteeCheckbox(); } if (table.ContainsColumn("FreeShipping ") && table.Rows[0]["FreeShipping"].Contains("check")) { if (!(CurrentPage is AukroHomePage)) throw new System.Exception("Bad page"); ((AukroHomePage)this.CurrentPage).SelectFreeShippingCheckbox(); } if (table.ContainsColumn("PersonalTakeover ") && table.Rows[0]["PersonalTakeover"].Contains("check")) { if (!(CurrentPage is AukroHomePage)) throw new System.Exception("Bad page"); // ToDO PersonalTakeover } if (table.ContainsColumn("TransportWithCashOnDelivery ") && table.Rows[0]["TransportWithCashOnDelivery"].Contains("check")) { if (!(CurrentPage is AukroHomePage)) throw new System.Exception("Bad page"); // ToDO TransportWithCashOnDelivery } if (table.ContainsColumn("AukroPlus") && table.Rows[0]["AukroPlus"].Contains("check")) { if (!(CurrentPage is AukroHomePage)) throw new System.Exception("Bad page"); // ToDO AukroPlus } } [Then(@"Verify that all offers include Aukro Return Money Guarantee")] public void ThenVerifyThatAllOffersIncludeAukroReturnMoneyGuarantee() { if (!(CurrentPage is AukroHomePage)) throw new System.Exception("Bad page"); Assert.IsTrue(((AukroHomePage)this.CurrentPage).VerifyReturnMoneyAllOffers(), "Aukro money return guarantee is not present for all offers."); } } } <file_sep>using System.Collections.Generic; using System.Linq; using TechTalk.SpecFlow; namespace SeleniumSpecFlow.Classes { public static class TableRowExtensions { public static bool ContainsNonEmptyKey(this TableRow row, string key) { return row.ContainsKey(key) && !string.IsNullOrEmpty(row[key]); } public static bool IsEmpty(this TableRow row) { return row.Values.All(x => x.IsNullOrEmpty()); } } }
72ba7be5a13424c7782178b5b4553834c1245407
[ "C#" ]
7
C#
Mchalek8/SeleniumSpecFlow
8a6d2f0dd02ba135681a9cec23d65d46b1fb4405
03330078579b7e0cb982be9c84a289bfd133e92c
refs/heads/master
<repo_name>sauravsrijan/collective.collectionfilter<file_sep>/src/collective/collectionfilter/testing.py # -*- coding: utf-8 -*- from datetime import datetime from datetime import timedelta from plone import api from plone.app.contenttypes.testing import PLONE_APP_CONTENTTYPES_FIXTURE from plone.app.robotframework.testing import REMOTE_LIBRARY_BUNDLE_FIXTURE from plone.app.testing import FunctionalTesting from plone.app.testing import IntegrationTesting from plone.app.testing import PloneSandboxLayer from plone.app.testing import applyProfile from plone.app.textfield.value import RichTextValue from plone.testing import z2 class CollectiveCollectionFilterLayer(PloneSandboxLayer): defaultBases = (PLONE_APP_CONTENTTYPES_FIXTURE,) def setUpZope(self, app, configurationContext): # Load any other ZCML that is required for your tests. # The z3c.autoinclude feature is disabled in the Plone fixture base # layer. import plone.app.mosaic self.loadZCML(package=plone.app.mosaic) import collective.geolocationbehavior self.loadZCML(package=collective.geolocationbehavior) import collective.collectionfilter self.loadZCML(package=collective.collectionfilter) self.loadZCML(package=collective.collectionfilter.tests) def setUpPloneSite(self, portal): applyProfile(portal, 'plone.app.mosaic:default') applyProfile(portal, 'collective.geolocationbehavior:default') applyProfile(portal, 'collective.collectionfilter:default') applyProfile(portal, 'collective.collectionfilter.tests:testing') with api.env.adopt_roles(['Manager']): portal.invokeFactory( 'Collection', id='testcollection', title=u'Test Collection', query=[{ 'i': 'portal_type', 'o': 'plone.app.querystring.operation.selection.any', 'v': ['Document', 'Event'] }], ) portal.invokeFactory( 'Event', id='testevent', title=u'Test Event', start=datetime.now() + timedelta(days=1), end=datetime.now() + timedelta(days=2), subject=[u'Süper', u'Evänt'], ) portal.invokeFactory( 'Document', id='testdoc', title=u'Test Document 😉', text=RichTextValue(u'Ein heißes Test Dokument'), subject=[u'Süper', u'Dokumänt'], ) doc = portal['testdoc'] # doc.geolocation.latitude = 47.4048832 # doc.geolocation.longitude = 9.7587760701108 doc.reindexObject() COLLECTIVE_COLLECTIONFILTER_FIXTURE = CollectiveCollectionFilterLayer() COLLECTIVE_COLLECTIONFILTER_INTEGRATION_TESTING = IntegrationTesting( bases=(COLLECTIVE_COLLECTIONFILTER_FIXTURE,), name='CollectiveCollectionFilterLayer:IntegrationTesting', ) COLLECTIVE_COLLECTIONFILTER_FUNCTIONAL_TESTING = FunctionalTesting( bases=(COLLECTIVE_COLLECTIONFILTER_FIXTURE,), name='CollectiveCollectionFilterLayer:FunctionalTesting', ) COLLECTIVE_COLLECTIONFILTER_ACCEPTANCE_TESTING = FunctionalTesting( bases=( COLLECTIVE_COLLECTIONFILTER_FIXTURE, REMOTE_LIBRARY_BUNDLE_FIXTURE, z2.ZSERVER_FIXTURE, ), name='CollectiveCollectionFilterLayer:AcceptanceTesting', ) <file_sep>/src/collective/collectionfilter/tests/test_filteritems.py # -*- coding: utf-8 -*- """Setup tests for this package.""" import unittest from collective.collectionfilter.testing import COLLECTIVE_COLLECTIONFILTER_INTEGRATION_TESTING # noqa from collective.collectionfilter.filteritems import get_filter_items def get_data_by_val(result, val): for r in result: if r['value'] == val: return r class TestFilteritems(unittest.TestCase): layer = COLLECTIVE_COLLECTIONFILTER_INTEGRATION_TESTING def setUp(self): """Custom shared utility setup for tests.""" self.portal = self.layer['portal'] self.collection = self.portal['testcollection'] self.collection_uid = self.collection.UID() def test_filteritems(self): self.assertEqual(len(self.collection.results()), 2) result = get_filter_items( self.collection_uid, 'Subject', cache_enabled=False) self.assertEqual(len(result), 4) self.assertEqual(get_data_by_val(result, 'all')['count'], 2) self.assertEqual(get_data_by_val(result, 'all')['selected'], True) self.assertEqual(get_data_by_val(result, u'Süper')['count'], 2) self.assertEqual(get_data_by_val(result, u'Evänt')['count'], 1) self.assertEqual(get_data_by_val(result, u'Dokumänt')['count'], 1) result = get_filter_items( self.collection_uid, 'Subject', request_params={'Subject': u'Süper'}, cache_enabled=False) self.assertEqual(len(result), 4) self.assertEqual(get_data_by_val(result, u'Süper')['selected'], True) result = get_filter_items( self.collection_uid, 'Subject', request_params={'Subject': u'Dokumänt'}, cache_enabled=False) self.assertEqual(len(result), 4) self.assertEqual( get_data_by_val(result, u'Dokumänt')['selected'], True) # test narrowed down results narrowed_down_result = get_filter_items( self.collection_uid, 'Subject', request_params={'Subject': u'Dokumänt'}, narrow_down=True, show_count=True, cache_enabled=False) self.assertEqual( len(narrowed_down_result), 3, msg=u"narrowed result length should be 3") self.assertEqual( get_data_by_val(narrowed_down_result, u'Dokumänt')['selected'], True, # noqa msg=u"Test that 'Dokumänt' is selected, matching the query") self.assertEqual( get_data_by_val(narrowed_down_result, u'all')['count'], 2, msg=u"Test that there are 2 Subjects") def test_portal_type_filter(self): self.assertEqual(len(self.collection.results()), 2) result = get_filter_items( self.collection_uid, 'portal_type', cache_enabled=False) self.assertEqual(len(result), 3) self.assertEqual(get_data_by_val(result, 'all')['count'], 2) self.assertEqual(get_data_by_val(result, 'all')['selected'], True) self.assertEqual(get_data_by_val(result, u'Event')['count'], 1) self.assertEqual(get_data_by_val(result, u'Document')['count'], 1) result = get_filter_items( self.collection_uid, 'portal_type', request_params={'portal_type': u'Event'}, cache_enabled=False) self.assertEqual(len(result), 3) self.assertEqual(get_data_by_val(result, u'Event')['selected'], True) # test narrowed down results result = get_filter_items( self.collection_uid, 'portal_type', request_params={'portal_type': u'Event'}, narrow_down=True, show_count=True, cache_enabled=False) self.assertEqual(len(result), 2) self.assertEqual( get_data_by_val(result, u'all')['count'], 2, msg=u"Test that the number of portal_types in the collection is 2") self.assertEqual( get_data_by_val(result, u'Event')['selected'], True, msg=u"Test that Event portal_type is selected matching the query")
a7c930d1303d43b297f1978ba5405b2ba3538d24
[ "Python" ]
2
Python
sauravsrijan/collective.collectionfilter
22fe68309e6a4cd056dea44a84796d9477464cc1
c4ca8ee7d4457b47ecbccea236d67da40f735064
refs/heads/master
<file_sep>import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import argparse LOGDIR = "/tmp/mnist_tutorial/" mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) def weight_variable(shape): '''Create a weight variable with initialization''' return tf.Variable(tf.truncated_normal(shape, stddev=0.1), name="W") def bias_variable(shape): '''Create a bias variable with initialization''' return tf.Variable(tf.constant(0.1, shape=shape), name="B") def conv2d(x, weights): '''Perform 2d convolution with specified weights''' return tf.nn.conv2d(input=x, filter=weights, strides=[1,1,1,1], padding='SAME') def max_pool(x): '''Perform max pooling''' return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME') def conv_layer(input, kernel_size, in_channels, out_channels, batch_norm=False, name='conv'): '''Convolutional layer with 2d convolution, relu activation, and max pooling''' with tf.name_scope(name): w = weight_variable([kernel_size, kernel_size, in_channels, out_channels]) b = bias_variable([out_channels]) if not batch_norm: activation = tf.nn.relu(conv2d(input, w) + b) else: activation = tf.nn.relu(tf.nn.batch_normalization(conv2d(input, w)+b, 0,1,0.1,10,0.0001)) tf.summary.histogram("Weights", w) tf.summary.histogram("Biases", b) tf.summary.histogram("Activations", activation) pool = max_pool(activation) return pool def fc_layer(input, in_channels, out_channels, name='fc'): '''Fully connected layer''' with tf.name_scope(name): w = weight_variable([in_channels, out_channels]) b = bias_variable([out_channels]) out = tf.matmul(input, w) + b tf.summary.histogram("Weights", w) tf.summary.histogram("Biases", b) tf.summary.histogram("Activations", out) return out def train(): parser = argparse.ArgumentParser() parser.add_argument('--test', default=False, type=bool) parser.add_argument('--batch_norm', default=False, type=bool) args = parser.parse_args() tf.reset_default_graph() sess = tf.Session() # Input flattened image x = tf.placeholder(tf.float32, shape=[None, 784], name='x') # Class label y = tf.placeholder(tf.float32, shape=[None, 10], name='y') x_image = tf.reshape(x, [-1,28,28,1]) # Model conv_out1 = conv_layer(x_image, 5, 1, 32, args.batch_norm, "conv1") conv_out2 = conv_layer(conv_out1, 5, 32, 64, args.batch_norm, "conv2") flattened_out = tf.reshape(conv_out2, [-1, 7*7*64]) fc_out1 = fc_layer(flattened_out, 7*7*64, 1024, "fc1") relu = tf.nn.relu(fc_out1) dropout = tf.layers.dropout(inputs=relu, rate=0.4) logits = fc_layer(dropout, 1024, 10, "fc2") loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y)) tf.summary.scalar("Loss", loss) optimizer = tf.train.AdamOptimizer(0.001) train_step = optimizer.minimize(loss) correct_prediction = tf.equal(tf.argmax(logits,1), tf.argmax(y,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) train_acc = tf.summary.scalar('Accuracy', accuracy) validation_acc = tf.summary.scalar('Validation_accuracy', accuracy) merged_summary = tf.summary.merge_all() sess.run(tf.global_variables_initializer()) writer = tf.summary.FileWriter('/tmp/mnist_tutorial') writer.add_graph(sess.graph) for epoch in range(2001): batch = mnist.train.next_batch(50) if epoch % 100 == 0: [summary, train_accuracy] = sess.run([train_acc, accuracy], \ feed_dict={x: batch[0], y: batch[1]}) writer.add_summary(summary, epoch) print('Epoch %d, train accuracy: %f'%(epoch, train_accuracy)) [validation_summary, val_accuracy] = sess.run([validation_acc, accuracy], \ feed_dict={x: mnist.validation.images, y:mnist.validation.labels}) writer.add_summary(validation_summary, epoch) print('Epoch %d, validation accuracy: %f'%(epoch, val_accuracy)) sess.run(train_step, feed_dict={x: batch[0], y: batch[1]}) if args.test: if epoch == 801: break if args.test: print('Test accuracy: %g'%accuracy.eval(session=sess, \ feed_dict={x: mnist.test.images, y:mnist.test.labels})) writer.close() train() <file_sep>import numpy as np import pandas as pd import matplotlib.pyplot as plt from mlxtend.preprocessing import standardize from sklearn.cross_validation import train_test_split import random import argparse from process import * parser = argparse.ArgumentParser() parser.add_argument('--num_epochs', default=50, type=int) parser.add_argument('--num_steps', default=300, type=int) parser.add_argument('--eval_steps', default=30, type=int, help='compute the accuracy of the current classifier on the set held out for the epoch every 30 steps') parser.add_argument('--batch_size', default=1, type=int) parser.add_argument('--m', default=1, type=float, help='parameter for learning rate') parser.add_argument('--n', default=0.1, type=float, help='parameter for learning rate') parser.add_argument('--lamda', default=0.001, type=float, help='regularization parameter') parser.add_argument('--num_held_out', default=50, type=int) parser.add_argument('--test', default=False, type=bool) parser.add_argument('--path', default='yuchecw2_prediction.csv', type=str) args = parser.parse_args() train_data = pd.read_csv("train.data.csv") label_list = [i for i in train_data['class']] label = np.empty(len(label_list)) for i in range(label.shape[0]): if (label_list[i] == ' >50K'): label[i] = 1 else: label[i] = -1 feature = pd.DataFrame.as_matrix(train_data)[:, :-1] # Preprocess the data feature = preprocess(feature) # Standardize columns in train_feature feature = standardize(feature) # Train-validation split train_feature, val_feature, train_label, val_label = train_test_split( feature, label, test_size=0.1) plt.figure() for lamda in [0.001, 0.01, 0.1, 1]: # Initialize a, b a = np.random.randn(train_feature.shape[1], 1) # shape=(14, 1) b = 0 accuracy_list = [] mag_list = [] loss_list = [] for epoch in range(args.num_epochs): actual_train_feature, held_out_feature, actual_train_label, held_out_label = train_test_split(train_feature, train_label, test_size=args.num_held_out/train_feature.shape[0], random_state=epoch) actual_train_size = actual_train_feature.shape[0] for step in range(args.num_steps): lr = compute_lr(args.m, args.n, epoch) batch_num = random.sample(range(actual_train_size), args.batch_size) a = update_a(a, b, actual_train_feature, actual_train_label, batch_num, lr, lamda) b = update_b(b, a, actual_train_feature, actual_train_label, batch_num, lr, lamda) if (step%args.eval_steps == 0): eval_dict = evaluate(held_out_feature, held_out_label, a, b, lamda) accuracy_list.append(eval_dict['accuracy']) mag_list.append(eval_dict['mag']) loss_list.append(eval_dict['loss']) if (args.test): test_data = pd.read_csv("test.data.csv") test_feature = pd.DataFrame.as_matrix(test_data) test_feature = preprocess(test_feature) test_feature = standardize(test_feature) prediction = predict(test_feature, a, b) prediction[prediction['Label'] == '>'] = ">50K" prediction[prediction['Label'] == '<'] = "<=50K" prediction.to_csv(args.path) step_list = range(len(accuracy_list)) for step in step_list: step *= args.num_steps label = 'λ = {}'.format(lamda) plt.plot(step_list, mag_list, label=label, linewidth=0.8) plt.ylim(0, 100) plt.xlabel('step number') plt.ylabel('magnitude') plt.title('Magnitude vs step number', fontsize=12, fontweight='bold') plt.legend(loc='lower right') plt.show() <file_sep>import os import numpy as np from sklearn.preprocessing import StandardScaler from sklearn.cluster import KMeans from sklearn.cross_validation import train_test_split from sklearn.ensemble import RandomForestClassifier import matplotlib.pyplot as plt import argparse def class_confusion_matrix(predict, actual): confusion_matrix = np.zeros((14,14)) # len(name_label_dict.keys()) = 14 for i in range(len(predict)): confusion_matrix[predict[i], actual[i]] += 1 return confusion_matrix # Can also be used to obtain test_data, test_label def get_data_label(train_data_dict, data_dict, name_label_dict): train_data = np.vstack(train_data_dict['Brush_teeth']) train_label = [name_label_dict['Brush_teeth']]*train_data.shape[0] for key in data_dict.keys(): if key is not 'Brush_teeth': current_train_data = np.vstack(train_data_dict[key]) train_data = np.vstack([train_data, current_train_data]) train_label += [name_label_dict[key]]*current_train_data.shape[0] return train_data, train_label def build_name_label_dict(data_dict): name_label_dict = {} for i, key in enumerate(data_dict.keys()): name_label_dict[key] = i return name_label_dict def split_data_dict(data_dict, test_size=0.20, random_state=42): train_data_dict = {} test_data_dict = {} for label in data_dict.keys(): train_data, test_data = train_test_split(data_dict[label], test_size=test_size, random_state=random_state) train_data_dict[label] = train_data test_data_dict[label] = test_data return train_data_dict, test_data_dict # (label, data(shape: (n_samples, n_features))) pair def build_data_dict(folders, dim, overlap): data_dict = {} for folder in folders: if folder in data_dict.keys(): data_dict[folder] += [preprocess('HMP_Dataset/'+folder+'/'+file, dim, overlap) for file in os.listdir('HMP_Dataset/'+folder) if not file.startswith('.')] else: key_exists = False for key in data_dict.keys(): if folder.startswith(key): key_exists = True data_dict[key] += [preprocess('HMP_Dataset/'+folder+'/'+file, dim, overlap) for file in os.listdir('HMP_Dataset/'+folder) if not file.startswith('.')] if not key_exists: data_dict[folder] = [preprocess('HMP_Dataset/'+folder+'/'+file, dim, overlap) for file in os.listdir('HMP_Dataset/'+folder) if not file.startswith('.')] return data_dict # Build frequency histogram with length n_clusters def build_histogram(labels, n_clusters): histogram = [0]*n_clusters total = 0 for label in labels: histogram[label] += 1 total += 1 X = np.array(histogram).reshape(1,-1) X = X / total return X # Build a histogram of shape (n_clusters,) def prediction(kmeans, train_data_dict, n_clusters, name_label_dict): predict_hist = [] predict_label = [] for key in train_data_dict.keys(): for data in train_data_dict[key]: hist = build_histogram(kmeans.predict(data), n_clusters) predict_hist.append(hist) predict_label.append(name_label_dict[key]) predict_hist = np.array(predict_hist).squeeze(1) return predict_hist, predict_label def preprocess(file, dim, overlap): signal = np.loadtxt(file) signal_patches = cut_signal(signal, dim, overlap) return np.vstack(signal_patches) def cut_signal(signal, dim, overlap): i=0 signal_patches = [] while(i+dim < signal.shape[0]): signal_patches.append(signal[i:i+dim, :].reshape(1, -1)) i += (int)(dim*(1-overlap)) # no overlap if i < signal.shape[0]: signal_patches.append(signal[-dim:, :].reshape(1, -1)) return signal_patches def main(dim, n_clusters, overlap, fig): folders = os.listdir('HMP_Dataset') folders.pop(0) # Remove '.DS_Store' data_dict = build_data_dict(folders, dim, overlap) name_label_dict = build_name_label_dict(data_dict) train_data_dict, test_data_dict = split_data_dict(data_dict) train_data, train_label = get_data_label(train_data_dict, data_dict, name_label_dict) #train_data[i,:] -> train_label[i] test_data, test_label = get_data_label(test_data_dict, data_dict, name_label_dict) kmeans = KMeans(n_clusters=n_clusters, init='k-means++', n_init=5).fit(train_data) predict_hist, predict_label = prediction(kmeans, train_data_dict, n_clusters, name_label_dict) clf = RandomForestClassifier(n_estimators=20, max_depth=10, random_state=0) clf.fit(predict_hist, predict_label) #Test test_predict_hist, test_actual_label = prediction(kmeans, test_data_dict, n_clusters, name_label_dict) test_predict_label = clf.predict(test_predict_hist) n_correct = len(test_predict_label[test_predict_label==test_actual_label]) accuracy = n_correct / len(test_predict_label) print('Accuracy: {}'.format(accuracy)) confusion_matrix = class_confusion_matrix(test_predict_label, test_actual_label) for key_num, key in enumerate(train_data_dict.keys()): sample = np.zeros((1,dim*3)) for i in range(len(train_data_dict[key])): for j in range(train_data_dict[key][i].shape[0]): sample = np.vstack((sample, train_data_dict[key][i][j,:].reshape(1,dim*3))) hist = build_histogram(kmeans.predict(sample[1:,:]), n_clusters) ax = fig.add_subplot(3,5,key_num+1) ax.bar(np.arange(1, n_clusters+1)-0.4, hist.squeeze(0).tolist(), width=0.8) ax.set_xlabel('Cluster number', fontsize=8) ax.set_ylabel('Frequency', fontsize=8) ax.set_title('Histogram for {}'.format(key), fontsize=8) ax.grid() print(confusion_matrix) fig = plt.figure(figsize=(13,7)) confusion_matrix = main(dim=5, n_clusters=50, overlap=0.5, fig=fig) fig.tight_layout() plt.show() # np.savetxt("confusion_matrix.csv", confusion_matrix, delimiter='') <file_sep>import numpy as np import pandas as pd from sklearn.naive_bayes import BernoulliNB from sklearn.naive_bayes import GaussianNB import random import math def preprocess(data, test): box_size = 20 original_size = 28 if not test: streched_data = np.empty((data.shape[0], box_size*box_size+1)) else: # No label column streched_data = np.empty((data.shape[0], box_size*box_size)) for k in range(data.shape[0]): # Label if not test: streched_data[k, 0] = data[k, 0] # Find the margin bottom = find_bottom(data, k, original_size) top = find_top(data, k, original_size) num_rows = bottom-top+1 right = find_right(data, k, original_size, test) left = find_left(data, k, original_size, test) num_cols = right-left+1 # Find the bounding box bounding_box = np.empty((num_rows, num_cols)) for j in range(top, bottom+1): for i in range(left, right+1): if not test: bounding_box[j-top, i-left] = data[k, original_size*j+i+1] else: bounding_box[j-top, i-left] = data[k, original_size*j+i] # plt.subplot(1,2,1) # plt.matshow(bounding_box) # plt.title("#%d bounding box"%(k)) # Resize the bounding box streched_bounding_box = resize_matrix(bounding_box, box_size, box_size) for i in range(box_size): for j in range(box_size): if not test: streched_data[k, box_size*i+j+1] = streched_bounding_box[i, j] else: streched_data[k, box_size*i+j] = streched_bounding_box[i,j] return streched_data def resize_matrix(mat, n_row_out, n_col_out): n_row_in = mat.shape[0] n_col_in = mat.shape[1] mat_out = np.empty((n_row_out, n_col_out)) row_ratio = n_row_in/n_row_out col_ratio = n_col_in/n_col_out for i in range(n_row_out): for j in range(n_col_out): mat_out[i, j] = mat[math.floor(i*row_ratio), math.floor(j*col_ratio)] return mat_out def find_top(data, num, original_size): for i in range(1, len(data[num, :])): if data[num, i].item() is not 0: return math.floor(i/original_size) def find_bottom(data, num, original_size): for i in range(len(data[num, :]) - 1, 0, -1): if data[num, i].item() is not 0: return math.floor(i/original_size) def find_left(data, num, original_size, test): for left in range(original_size): for j in range(original_size): if not test: if data[num, original_size*j+left+1].item() is not 0: return left else: if data[num, original_size*j+left].item() is not 0: return left def find_right(data, num, original_size, test): for right in range(original_size-1,-1,-1): for j in range(original_size): if not test: if data[num, original_size*j+right+1].item() is not 0: return right else: if data[num, original_size*j+right].item() is not 0: return right <file_sep># Part 1d library(caret) library(e1071) library(klaR) # Read CSV into R data = read.csv(file="pima-indians-diabetes.csv", header=TRUE, sep=",") attributes = c(3, 4, 6, 8) #blood pressure, skin thickness, BMI, age accuracy_vec = seq(1, 10, by=1) for(seed in seq(1, 10)) { # Test train split set.seed(seed) in_train = createDataPartition(data[,9], p=0.8, list=FALSE) train_data = data[in_train, ] test_data = data[-in_train, ] test_label = test_data[,9] # Train the model feature = train_data[, attributes] label = as.factor(train_data[,9]) model = svmlight(feature, label, pathsvm="/Users/jeffreywang/Desktop/AML/svm_light") prediction = predict(model, test_data[, attributes]) predict_label = prediction$class correct = test_label == predict_label accuracy = length(correct[correct==TRUE])/length(correct) accuracy_vec[seed] = accuracy } print(accuracy_vec) print(mean(accuracy_vec)) <file_sep>setwd('/Users/jeffreywang/Desktop/AML/HW7') library(gdata) data <- read.csv('blogData_train.csv') library(glmnet) library("rlist") library(data.table) xmat = as.matrix(data[,-281]) ymat = as.matrix(data[,281]) # Poisson generalized model with lasso model <- cv.glmnet(xmat, ymat, family='poisson',nfolds=10, alpha=1) # A plot of cross-validated deviance against the regularization variable plot(model) # A scatter plot of true values vs predicted values for training data predicted = predict(model, newx=xmat, s="lambda.1se") plot(predicted, ymat, main="Training data\nPredicted v.s. True", xlab="Predicted value", ylab="True value") reg <- lm(ymat~predicted) # R squared = 0.1398 abline(reg, col='red') # A scatter plot of true values vs predicted values for testing data test_data_files = list.files(path="BlogFeedback") # Load test data from csv files test_data <- read.csv(paste("BlogFeedback/", test_data_files[1], sep="")) for (i in 2:60) { test_data = rbindlist(list(test_data, read.csv(paste("BlogFeedback/", test_data_files[i], sep="")))) } # Split test data to x_test and y_test par(mfrow=c(1,1)) x_test = as.matrix(test_data[,-281]) y_test = as.matrix(test_data[,281]) predicted_test = predict(model, x_test, s="lambda.1se") plot(predicted_test, y_test, main="Testing data\nPredicted v.s. True", xlab="Predicted value", ylab="True value") reg_test <- lm(y_test~predicted_test) abline(reg_test, col='red') <file_sep>import numpy as np from PIL import Image from sklearn.cluster import KMeans from collections import Counter import matplotlib.pyplot as plt def load_image(filename): img = Image.open(filename) img_arr = np.asarray(img, dtype='int32') img_ravel = np.concatenate((img_arr[:,:,0].ravel().reshape(-1,1), img_arr[:,:,1].ravel().reshape(-1,1), img_arr[:,:,2].ravel().reshape(-1,1)), axis=1) return img_arr, img_ravel, img_scaled # (H*W, C) # Perform EM Algorithm to segement image def image_segmentation(image_name, filename, n_segments, random_seed): # Initialization orig_img, unscaled_img, img = load_image(filename) nrows, ncols, _ = orig_img.shape kmeans = KMeans(n_clusters=n_segments, random_state=random_seed).fit(img) blob_weight = np.zeros(n_segments) # pi, i.e. weight of each blob counter = Counter(kmeans.labels_) for i in range(n_segments): blob_weight[i] = counter[i] / img.shape[0] blob_center = kmeans.cluster_centers_ # mu, i.e. mean of each normal distribution w = np.zeros((img.shape[0], n_segments)) Q_prev = 0 num_epochs = 30 epsilon = 0.1 # EM Algorithm for epoch in range(num_epochs): # E step for i in range(img.shape[0]): total = 0 for j in range(n_segments): w[i,j] = np.exp(-0.5*(np.dot(img[i,:]-blob_center[j,:], img[i,:]-blob_center[j,:])))*blob_weight[j] total += w[i,j] w[i,:] = w[i,:] / total # M step for j in range(n_segments): total = np.zeros((1,3)) for i in range(img.shape[0]): total += img[i,]*w[i,j] total = total/(np.sum(w[:,j])) blob_center[j] = total blob_weight[j] = np.sum(w[:,j]) / img.shape[0] # Calculate Q Q = 0 for i in range(img.shape[0]): for j in range(n_segments): Q += (-0.5*(np.dot(img[i,:]-blob_center[j,:], img[i,:]-blob_center[j,:])) + np.log(blob_weight[j]))*w[i,j] # Check if converge or not if np.abs(Q - Q_prev) < epsilon: break Q_prev = Q # plt.figure() # plt.plot(list(range(len(Q_list))), Q_list, 'b-') # plt.xlabel('Epoch') # plt.ylabel('Q') # plt.title('Q v.s. Epoch {}-{}'.format(image_name, n_segments)) # plt.show() cluster_index = [np.argsort(w[i,:])[-1] for i in range(img.shape[0])] segmented_img_ravel = np.zeros(img.shape) for i in range(img.shape[0]): segmented_img_ravel[i,:] = blob_center[cluster_index[i],:] segmented_img = np.zeros(orig_img.shape) for i in range(img.shape[0]): segmented_img[i//ncols, i%ncols, :] = segmented_img_ravel[i,:] segmented_img = Image.fromarray(segmented_img.astype(np.uint8),'RGB') segmented_img.save('{}_segment-{}_seed-{}.jpg'.format(image_name, n_segments, random_seed)) def main(): image_name = ['RobertMixed03','smallsunset','smallstrelitzia', 'tree'] filename = [i+'.jpg' for i in image_name] n_segments_list = [10,20,50] for i in range(4): for n_segments in n_segments_list: image_segmentation(image_name[i], filename[i], n_segments, 0) print('Image: {}, num_segments: {}'.format(image_name[i], n_segments)) for random_seed in [1,2,3,4,5]: image_segmentation(image_name[3], filename[3], 20, random_seed) print('Tree image with random seed: {}'.format(random_seed)) main() <file_sep>import numpy as np import gzip import struct import matplotlib.pyplot as plt from mlxtend.data import loadlocal_mnist def extract_images(filename, num_images): with gzip.open(filename) as f: zero, data_type, dims = struct.unpack('>HBB', f.read(4)) shape = tuple(struct.unpack('>I', f.read(4))[0] for d in range(dims)) images = np.fromstring(f.read(), dtype=np.uint8).reshape(shape) images = np.divide(images, 255.0) return images[:num_images, :, :] def binarize(images): bi_images = np.zeros(images.shape) for k in range(images.shape[0]): for i in range(images.shape[1]): for j in range(images.shape[2]): if images[k,i,j] >= 0.5: bi_images[k,i,j] = 1.0 else: bi_images[k,i,j] = -1.0 return bi_images def create_noisy(images): noisy_images = np.copy(images) size = images.shape[1] * images.shape[2] flip_size = (int)(size*0.02) for k in range(images.shape[0]): choice = np.random.permutation(np.arange(size))[:flip_size].tolist() for i in range(size): if i in choice: noisy_images[k, i//images.shape[1], i%images.shape[1]] \ = -images[k, i//images.shape[1], i%images.shape[1]] return noisy_images def denoise(noisy_images, theta_hh=0.2): # theta_hh = 0.2 theta_hx = 0.2 epsilon = 0.001 num_epochs = 20 # Initialize diff list diff = [[] for _ in range(noisy_images.shape[0])] for i in diff: i.append(0) length = noisy_images.shape[1] images = np.copy(noisy_images) for k in range(images.shape[0]): # Initialize edge weights pi pi = np.random.rand(length, length) prev_pi = np.copy(pi) for epoch in range(num_epochs): exponent = np.zeros((length, length)) for i in range(images.shape[1]): for j in range(images.shape[2]): if i is not 0: # Not on the top edge exponent[i,j] += theta_hh*(2*pi[i-1,j]-1) + theta_hx*noisy_images[k,i-1,j] if i is not images.shape[1]-1: # Not on the bottom edge exponent[i,j] += theta_hh*(2*pi[i+1,j]-1) + theta_hx*noisy_images[k,i+1,j] if j is not 0: # Not on the left edge exponent[i,j] += theta_hh*(2*pi[i,j-1]-1) + theta_hx*noisy_images[k,i,j-1] if j is not images.shape[1]-1: # Not on the right edge exponent[i,j] += theta_hh*(2*pi[i,j+1]-1) + theta_hx*noisy_images[k,i,j+1] # Update edge weights pi[i,j] = np.exp(exponent[i,j]) / (np.exp(exponent[i,j]) + np.exp(-exponent[i,j])) if pi[i,j] < 0.5: images[k,i,j] = -1.0 else: images[k,i,j] = 1.0 # diff[k].append(np.linalg.norm(pi-prev_pi,2)) diff[k].append(np.sum(np.power(pi-prev_pi,2))) prev_pi = np.copy(pi) if diff[k][-1] < epsilon: break return images def accuracy(binary_images,denoise_images): accuracy_list = np.zeros((binary_images.shape[0],1)) for k in range(binary_images.shape[0]): n_incorrect = np.count_nonzero(binary_images[k,:,:]-denoise_images[k,:,:]) accuracy_list[k] = 1 - (n_incorrect / (binary_images.shape[1]*binary_images.shape[2])) return accuracy_list def confusion(binary_images, denoise_images): true_positive_list = np.zeros((binary_images.shape[0],1)) false_positive_list = np.zeros((binary_images.shape[0],1)) for k in range(binary_images.shape[0]): true_positive = 0 false_positive = 0 for i in range(binary_images.shape[1]): for j in range(binary_images.shape[2]): if denoise_images[k,i,j] == 1.0: if binary_images[k,i,j] == 1.0: true_positive += 1 else: false_positive += 1 true_positive_list[k] = true_positive / (binary_images.shape[1]**2) false_positive_list[k] = false_positive / (binary_images.shape[1]**2) return np.mean(true_positive_list), np.mean(false_positive_list) def main(): # img_filename = 'train-images-idx3-ubyte.gz' # images = extract_images(img_filename, 500) images, labels = loadlocal_mnist(images_path='train-images-idx3-ubyte', labels_path='train-labels-idx1-ubyte') images = images.reshape(-1,28,28)[:500,:,:] labels = labels[:500] label_img_dict = {} for i in range(labels.shape[0]): if labels[i] not in label_img_dict.keys(): label_img_dict[labels[i]] = images[i,:,:].reshape(-1,28,28) else: label_img_dict[labels[i]] = np.concatenate((label_img_dict[labels[i]], images[i,:,:].reshape(-1,28,28)), axis=0) # Sample images for each digit plt.figure(figsize=(4.5,15)) for num in range(10): orig_img = label_img_dict[num] binary_img = binarize(orig_img) plt.subplot(10,3,num*3+1) plt.imshow(binary_img[0,:,:], cmap='gray') noisy_img = create_noisy(binary_img) plt.subplot(10,3,num*3+2) plt.imshow(noisy_img[0,:,:], cmap='gray') denoise_img = denoise(noisy_img) plt.subplot(10,3,num*3+3) plt.imshow(denoise_img[0,:,:], cmap='gray') plt.savefig('samples.png') binary_images = binarize(images) noisy_images = create_noisy(binary_images) denoise_images = denoise(noisy_images) accuracy_list = accuracy(binary_images, denoise_images) avg_accuracy = sum(accuracy_list[:500]) / 500 print('Average accuracy on the first 500 images: {}'.format(avg_accuracy)) plt.figure() plt.scatter(list(range(accuracy_list.shape[0])), accuracy_list) plt.xlabel('Image Number') plt.ylabel('Accuracy') plt.ylim(0.9, 1.0) plt.title('Fraction of correct pixels') plt.savefig('accuracy.png') # Most accurate max_idx = np.argmax(accuracy_list) plt.figure() plt.imshow(binary_images[max_idx,:,:]) plt.title('Most accurate binary image') plt.savefig('most_accurate_binary_image.png') plt.figure() plt.imshow(noisy_images[max_idx,:,:]) plt.title('Most accurate noisy image') plt.savefig('most_accurate_noisy_image.png') plt.figure() plt.imshow(denoise_images[max_idx,:,:]) plt.title('Most accurate denoised image') plt.savefig('most_accurate_denoised_image.png') # Least accurate min_idx = np.argmin(accuracy_list) plt.figure() plt.imshow(binary_images[min_idx,:,:]) plt.title('Least accurate binary image') plt.savefig('least_accurate_binary_image.png') plt.figure() plt.imshow(noisy_images[min_idx,:,:]) plt.title('Least accurate noisy image') plt.savefig('least_accurate_noisy_image.png') plt.figure() plt.imshow(denoise_images[min_idx,:,:]) plt.title('Least accurate denoised image') plt.savefig('least_accurate_denoised_image.png') # ROC denoise_images_list = [] accuracies = [] true_positive_list = [] false_positive_list = [] for theta_hh in [-1,0,0.2,1,2]: denoise_images_list.append(denoise(noisy_images, theta_hh)) accuracies.append(accuracy(binary_images, denoise_images)) true_positive, false_positive = confusion(binary_images, denoise_images_list[-1]) true_positive_list.append(true_positive) false_positive_list.append(false_positive) txt_list = [-1,0,0.2,1,2] fig, ax = plt.subplots() ax.scatter(false_positive_list, true_positive_list) for i, txt in enumerate(txt_list): ax.annotate(txt, (false_positive_list[i], true_positive_list[i])) ax.set_xlabel('False Positive Rate') ax.set_ylabel('True Positive Rate') plt.title('Receiver Operating Curve') plt.savefig('roc.png') main() <file_sep>import numpy as np from sklearn.decomposition import PCA from sklearn.metrics import mean_squared_error import matplotlib.pyplot as plt from scipy.spatial.distance import euclidean # from skbio.stats.ordination import pcoa from adjustText import adjust_text def unpickle(file): import pickle with open(file, 'rb') as fo: dict = pickle.load(fo, encoding='bytes') return dict meta_data = unpickle('cifar-10-batches-py/batches.meta') data_file = ['cifar-10-batches-py/data_batch_%d'%i for i in range(1,6)] # Key: label, value: a list of images with that label label_data_dict = {i:[] for i in range(10)} for file_num in range(1,6): original_dict = unpickle(data_file[file_num-1]) for i, key in enumerate(original_dict[b'labels']): label_data_dict[key].append(original_dict[b'data'][i,:]) # Stack all images of a category into a single 2D numpy array # Key: label, value: a matrix of images with that label label_matrix_dict = {} for i in range(10): label_matrix_dict[i] = np.empty((len(label_data_dict[i]), 3072)) for j in range(len(label_data_dict[i])): label_matrix_dict[i][j,:] = label_data_dict[i][j] mean_image_list = [] pca_list = [PCA(n_components=20) for i in range(10)] recon_image_list = [] mse_list = [] for i in range(10): mean_image_list.append(np.mean(label_matrix_dict[i], axis=0)) pca_list[i].fit(label_matrix_dict[i]) recon_image_list.append(pca_list[i].inverse_transform(pca_list[i].transform(label_matrix_dict[i]))) mse_list.append(mean_squared_error(label_matrix_dict[i], recon_image_list[i])) plt.figure(1) plt.bar(list(range(10)), mse_list) plt.xlabel('Label') plt.ylabel('MSE Loss') plt.title('Error of each category') plt.show() distance_matrix = np.empty((10, 10)) for i in range(10): for j in range(10): distance_matrix[i,j] = euclidean(mean_image_list[i], mean_image_list[j]) # Principle Coordinate Analysis A = np.identity(10) - 1/10 * np.ones((10,10)) W = -1/2 * np.dot(np.dot(A, distance_matrix), A.T) eigen_value, eigen_vector = np.linalg.eig(W) y = np.dot(eigen_vector[:,0:2], np.sqrt(np.diag(eigen_value[0:2]))) labels = np.array([str(x)[2:-1] for x in meta_data[b'label_names']]) fig, ax = plt.subplots() plt.plot(y[:,0], y[:,1], 'bo') texts = [plt.text(y[i,0], y[i,1], labels[i], ha='center', va='center') for i in range(labels.shape[0])] adjust_text(texts) plt.title('2D Map obtained from PCoA') plt.show() # ordination_result = pcoa(distance_matrix) # ordination_result.proportion_explained <file_sep>Part 1 Run hw1a.R, hw1b.R, hw1d.R by $ Rscript hw1a.R to obtain the accuracy of each prediction Part2 Run hw2a.py by $ python hw2a.py To change models and preprocess images, specify it by adding command line arguments. Options: --model_name ['Gaussian', 'Bernoulli', 'Random Forest'] Select a model for training. --preprocess bool Preprocess the image by finding its bounding box and crop it. --num_epochs int Number of epochs where each epoch has different train-validatio splits. --test bool Test or not. If true, prediction labels will be written into a csv file and mean images will be shown. --path str Specify the path where the csv file containing prediction labels is stored. --n_estimators int Number of estimators in the random forest model. --max_depth int The max depth for each tree in the random forest model. <file_sep>import numpy as np import pandas as pd from sklearn.preprocessing import StandardScaler from sklearn.metrics import mean_squared_error from sklearn.decomposition import PCA import argparse parser = argparse.ArgumentParser() parser.add_argument('--data_file', default='hw3-data/iris.csv', type=str, help='data for calculating mean and covmat') parser.add_argument('--data_file_noisy', default='hw3-data/dataV.csv', type=str, help='data for resconstruction') parser.add_argument('--save_reconstruct', default=False, type=bool) args = parser.parse_args() data = pd.read_csv(args.data_file) data = pd.DataFrame.as_matrix(data) data_noisy = pd.read_csv(args.data_file_noisy) data_noisy = pd.DataFrame.as_matrix(data_noisy) num_principal_components = list(range(5)) # num_principal_components = [2] # For reconstructing dataII with two principle components for n_components in num_principal_components: pca_noiseless = PCA(n_components=n_components) pca_noiseless.fit(data) recon_noiseless = pca_noiseless.inverse_transform(pca_noiseless.transform(data_noisy)) mse_noiseless = mean_squared_error(data, recon_noiseless) pca_noise = PCA(n_components=n_components) pca_noise.fit(data_noisy) recon_noise = pca_noise.inverse_transform(pca_noise.transform(data_noisy)) if (args.save_reconstruct): pd.DataFrame(recon_noise).to_csv('yuchecw2-recon.csv') mse_noise = mean_squared_error(data, recon_noise) print('n_components: {}, mse_noiseless: {}, mse_noise: {}'.format(n_components, mse_noiseless, mse_noise)) <file_sep># Read CSV into R # Part 1A data = read.csv(file="Desktop/pima-indians-diabetes.csv") accuracy_vec = seq(1, 10, by=1) train_ratio = 0.8 attribute = 1 for (iter in seq(1, 10, by=1)) { # Test-train spilts train_test_list = test_train_split(data, train_ratio, iter) train_data = train_test_list[[1]] test_data = train_test_list[[2]] # Calculate prior probabilities outcome = train_data[,9] n_positive = length(outcome[outcome==1]) n_negative = length(outcome[outcome==0]) P_positive = n_positive/length(outcome) P_negative = n_negative/length(outcome) # Calculate likelihood feature = train_data[,1] positive_feature_mean = mean(feature[outcome==1]) positive_feature_var = var(feature[outcome==1]) negative_feature_mean = mean(feature[outcome==0]) negative_feature_var = var(feature[outcome==0]) confusion_matrix = estimate(test_data, positive_feature_mean, positive_feature_var, negative_feature_mean, negative_feature_var, P_positive, P_negative) n_correct = confusion_matrix[1,1] + confusion_matrix[2,2] accuracy = n_correct / nrow(test_data) accuracy_vec[iter] = accuracy } print(accuracy_vec) # Evaluate on test data and return the confusion matrix estimate = function(test_data, positive_mean, positive_var, negative_mean, negative_var, P_positive, P_negative) { true_positive = 0 false_positive = 0 true_negative = 0 false_negative = 0 logP_positive = log(P_positive) logP_negative = log(P_negative) for(index in seq(1, nrow(test_data), by=1)) { positive_log_p = evaluate_log_p(test_data[index,1], positive_mean, positive_var) negative_log_p = evaluate_log_p(test_data[index,1], negative_mean, negative_var) if (logP_positive + positive_log_p > logP_negative + negative_log_p) { if (test_data[index, 9] == 1) { true_positive = true_positive + 1 } else { false_positive = false_positive + 1 } } else { if (test_data[index, 9] == 0) { true_negative = true_negative + 1 } else { false_negative = false_negative + 1 } } } confusion_matrix = matrix( c(true_positive, false_positive, false_negative, true_negative), nrow = 2, ncol = 2, byrow = TRUE ) return(confusion_matrix) } # Split the data test_train_split = function(data, train_ratio, seed) { set.seed(seed) sample = sample(seq_len(nrow(data)), size=floor(train_ratio*nrow(data))) train_data = data[sample,] test_data = data[-sample,] return(list(train_data, test_data)) } # Evalute log probability evaluate_log_p = function(feature, feature_mean, feature_var) { log_p = - ((feature - feature_mean)^2)/(2*feature_var) log_p = log_p + log(1/sqrt(2*pi*feature_var)) return(log_p) } <file_sep>import numpy as np import pandas as pd import math # Input: feature matrix of shape (43958, 14) def preprocess(train_feature): workclass = {' Private': 0, ' Self-emp-not-inc': 1, ' Self-emp-inc': 2, ' Federal-gov': 3, ' Local-gov': 4, ' State-gov': 5, ' Without-pay': 6, ' Never-worked': 7}; education = {' Bachelors': 0, ' Some-college': 1, ' 11th': 2, ' HS-grad': 3, ' Prof-school': 4, ' Assoc-acdm': 5, ' Assoc-voc': 6, ' 9th': 7, ' 7th-8th': 8, ' 12th': 9, ' Masters': 10, ' 1st-4th': 11, ' 10th': 12, ' Doctorate': 13, ' 5th-6th': 14, ' Preschool': 15}; martial_status = {' Married-civ-spouse': 0, ' Divorced': 1, ' Never-married': 2, ' Separated': 3, ' Widowed': 4, ' Married-spouse-absent': 5, ' Married-AF-spouse': 6}; occupation = {' Tech-support': 0, ' Craft-repair': 1, ' Other-service': 2, ' Sales': 3, ' Exec-managerial': 4, ' Prof-specialty': 5, ' Handlers-cleaners': 6, ' Machine-op-inspct': 7, ' Adm-clerical': 8, ' Farming-fishing': 9, ' Transport-moving': 10, ' Priv-house-serv': 11, ' Protective-serv': 12, ' Armed-Forces': 13}; relationship = { ' Wife': 0, ' Own-child': 1, ' Husband': 2, ' Not-in-family': 3, ' Other-relative': 4, ' Unmarried': 5}; race = {' White': 0, ' Asian-Pac-Islander': 1, ' Amer-Indian-Eskimo': 2, ' Other': 3, ' Black': 4}; sex = {' Female': 0, ' Male': 1}; native_country ={' United-States': 0, ' Cambodia': 1, ' England': 2, ' Puerto-Rico': 3, ' Canada': 4, ' Germany': 5, ' Outlying-US(Guam-USVI-etc)': 6, ' India': 7, ' Japan': 8, ' Greece': 9, ' South': 10, ' China': 11, ' Cuba': 12, ' Iran': 13, ' Honduras': 14, ' Philippines': 15, ' Italy': 16, ' Poland': 17, ' Jamaica': 18, ' Vietnam': 19, ' Mexico': 20, ' Portugal': 21, ' Ireland': 22, ' France': 23, ' Dominican-Republic': 24, ' Laos': 25, ' Ecuador': 26, ' Taiwan': 27, ' Haiti': 28, ' Columbia': 29, ' Hungary': 30, ' Guatemala': 31, ' Nicaragua': 32, ' Scotland': 33, ' Thailand': 34, ' Yugoslavia': 35, ' El-Salvador': 36, ' Trinadad&Tobago': 37, ' Peru': 38, ' Hong': 39, ' Holand-Netherlands': 40}; missing_workclass = [] has_workclass = [] missing_education = [] has_education = [] missing_martial_status = [] has_martial_status = [] missing_martial_status = [] has_martial_status = [] missing_occupation = [] has_occupation = [] missing_relationship = [] has_relationship = [] missing_race = [] has_race = [] missing_sex = [] has_sex = [] missing_native_country = [] has_native_country = [] for i in range(train_feature.shape[0]): # workclass if not train_feature[i, 1] == ' ?': train_feature[i, 1] = workclass[train_feature[i, 1]] has_workclass.append(i) else: missing_workclass.append(i) # education if not train_feature[i, 3] == ' ?': train_feature[i, 3] = education[train_feature[i, 3]] has_education.append(i) else: missing_education.append(i) # martial_status if not train_feature[i, 5] == ' ?': train_feature[i, 5] = martial_status[train_feature[i, 5]] has_martial_status.append(i) else: missing_martial_status.append(i) # occupation if not train_feature[i, 6] == ' ?': train_feature[i, 6] = occupation[train_feature[i, 6]] has_martial_status.append(i) else: missing_occupation.append(i) # relationship if not train_feature[i, 7] == ' ?': train_feature[i, 7] = relationship[train_feature[i, 7]] has_relationship.append(i) else: missing_relationship.append(i) # race if not train_feature[i, 8] == ' ?': train_feature[i, 8] = race[train_feature[i, 8]] has_race.append(i) else: missing_race.append(i) # sex if not train_feature[i, 9] == ' ?': train_feature[i, 9] = sex[train_feature[i, 9]] has_sex.append(i) else: missing_sex.append(i) # native_country if not train_feature[i, 13] == ' ?': train_feature[i, 13] = native_country[train_feature[i, 13]] has_native_country.append(i) else: missing_native_country.append(i) substitue_val = {} substitue_val['workclass'] = round(train_feature[:, 1][has_workclass].mean()) for j in missing_workclass: train_feature[j,1] = substitue_val['workclass'] substitue_val['education'] = round(train_feature[:, 3][has_education].mean()) for j in missing_education: train_feature[j,3] = substitue_val['education'] substitue_val['martial_status'] = round(train_feature[:, 5][has_martial_status].mean()) for j in missing_martial_status: train_feature[j,5] = substitue_val['martial_statu'] substitue_val['occupation'] = round(train_feature[:, 6][has_occupation].mean()) for j in missing_occupation: train_feature[j,6] = substitue_val['occupation'] substitue_val['relationship'] = round(train_feature[:, 7][has_relationship].mean()) for j in missing_relationship: train_feature[j,7] = substitue_val['relationship'] substitue_val['race'] = round(train_feature[:, 8][has_race].mean()) for j in missing_race: train_feature[j,8] = substitue_val['race'] substitue_val['sex'] = round(train_feature[:, 9][has_sex].mean()) for j in missing_sex: train_feature[j,9] = substitue_val['sex'] substitue_val['native_country'] = round(train_feature[:, 13][has_native_country].mean()) for j in missing_native_country: train_feature[j,13] = substitue_val['native_country'] return train_feature # Input # a: numpy array of size (14, 1) # feature: numpy array of size (14, 1) # b: double # Output # gamma: double def compute_gamma(a, feature, b): gamma = np.matmul(np.transpose(a), feature).item() + b return gamma # Input # gamma: numpy array of size (14, 1) def cost_function(gamma, label): cost = max(0, 1-label*gamma) return cost # Input # batch_num: a list consists of indices of training feature, supposed to be length of 1 # train_feature: numpy array of shape (43958, 14) # train_label: numpy array of shape (43958, ) def hinge_loss(batch_num, train_feature, train_label, a, b): loss = 0 for i in batch_num: feature_i = np.expand_dims(train_feature[i,:], axis=1) # shape=(14,1) gamma = compute_gamma(a, feature_i, b) loss += cost_function(gamma, train_label[i]) loss /= len(batch_num) return loss # Input # lamda: regularization parameter # a: numpy array of shape (14, 1) def regularization_loss(lamda, a): return 0.5*lamda*(np.matmul(np.transpose(a), a).item()) # This is the loss we're going to minimize using stochastic gradient descent def total_loss(batch_num, train_feature, train_label, a, b, lamda): return hinge_loss(batch_num, train_feature, train_label, a, b) + regularization_loss(lamda, a) # Output # u: numpy array of shape (15, 1) def obtain_u(a, b): b_arr = np.expand_dims(np.array([b]), axis=1) u = np.concatenate((a, b_arr), axis=0) return u def compute_lr(m, n, epoch): return m/(n+epoch) # Input # current_a: numpy array of shape (14, 1) # current_b: double def update_a(current_a, current_b, train_feature, train_label, batch_num, lr, lamda): grad = np.zeros(current_a.shape) for i in batch_num: if (cost_function(compute_gamma(current_a, train_feature[i,:], current_b), train_label[i]) == 0): grad += lamda*current_a else: grad = grad + (lamda*current_a - np.expand_dims(train_label[i]*train_feature[i, :], axis=1)) grad /= len(batch_num) return current_a - lr*grad def update_b(current_b, current_a, train_feature, train_label, batch_num, lr, lamda): grad = 0 for i in batch_num: if (cost_function(compute_gamma(current_a, train_feature[i, :], current_b), train_label[i]) == 0): continue else: grad += (-train_label[i]) grad /= len(batch_num) return current_b - lr*grad def evaluate(held_out_feature, held_out_label, a, b, lamda): n_correct = 0 for i in range(held_out_feature.shape[0]): gamma_i = compute_gamma(a, held_out_feature[i,:], b) if gamma_i*held_out_label[i] > 0: n_correct += 1 accuracy = n_correct / held_out_feature.shape[0] mag = math.sqrt(np.matmul(a.T, a).item() + b**2) loss = total_loss(range(held_out_feature.shape[0]), held_out_feature, held_out_label, a, b, lamda) return {'accuracy': accuracy, 'mag': mag, 'loss': loss} def predict(test_feature, a, b): test_label = np.empty((test_feature.shape[0]), dtype=str) for i in range(test_feature.shape[0]): gamma = compute_gamma(a, np.expand_dims(test_feature[i,:], axis=1), b) if (gamma > 0): test_label[i] = ">50K" else: test_label[i] = "<=50K" return pd.DataFrame(data={'Label': test_label}, dtype=str) <file_sep>''' Autoencoder for MNIST dataset''' from __future__ import division, print_function, absolute_import import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import numpy as np import matplotlib.pyplot as plt import argparse def weight_variable(shape, name): return tf.Variable(tf.truncated_normal(shape, stddev=0.1), name=name) def bias_variable(shape, name): return tf.Variable(tf.constant(0.1, shape=shape), name=name) def encoder(x, in_channels, hid_channels_1, hid_channels_2, name='encoder'): with tf.name_scope(name): w1 = weight_variable([in_channels, hid_channels_1], name='w1') b1 = bias_variable([hid_channels_1], name='b1') hid_out_1 = tf.nn.sigmoid(tf.matmul(x, w1) + b1) w2 = weight_variable([hid_channels_1, hid_channels_2], name='w2') b2 = bias_variable([hid_channels_2], name='b2') hid_out_2 = tf.nn.sigmoid(tf.matmul(hid_out_1, w2) + b2) return hid_out_2 def decoder(x, hid_channels_2, hid_channels_1, out_channels, name='decoder'): with tf.name_scope(name): w1 = weight_variable([hid_channels_2, hid_channels_1], name='w1') b1 = bias_variable([hid_channels_1], name='b1') hid_out_1 = tf.nn.sigmoid(tf.matmul(x, w1) + b1) w2 = weight_variable([hid_channels_1, out_channels], name='w2') b2 = bias_variable([out_channels], name='b2') hid_out_2 = tf.nn.sigmoid(tf.matmul(hid_out_1, w2) + b2) return hid_out_2 def train(): mnist = input_data.read_data_sets('/tmp/data', one_hot=True) img_test = mnist.test.images label_test = mnist.test.labels label_img_dict = {} for i in range(label_test.shape[0]): num = np.argmax(label_test[i,:]) if num not in label_img_dict.keys(): label_img_dict[num] = img_test[i,:] else: label_img_dict[num] = np.vstack((label_img_dict[num], img_test[i,:])) # Network parameters in_channels = 784 # = out_channels hid_channels_1 = 256 hid_channels_2 = 32 # Training parameters learning_rate = 0.01 num_epochs = 100000 display_epoch = 1000 batch_size = 1 x = tf.placeholder(tf.float32, shape=[None, in_channels], name='x') # Input image a.k.a groud truth y = tf.placeholder(tf.float32, shape=[None, hid_channels_2], name='y') # Encoder output # Auto-encoder Model encoder_out = encoder(x, in_channels, hid_channels_1, hid_channels_2) # Latent representation decoder_out = decoder(y, hid_channels_2, hid_channels_1, in_channels) # Reconstructed image # Calculate loss loss = tf.losses.mean_squared_error(x, decoder_out) optimizer = tf.train.RMSPropOptimizer(learning_rate).minimize(loss) # Initialize the variables init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) print('Start session!') # Training loss_list = [] for epoch in range(num_epochs+1): batch = mnist.train.next_batch(batch_size) en_out = sess.run(encoder_out, feed_dict={x: batch[0]}) _, mse_loss = sess.run([optimizer, loss], feed_dict={x: batch[0], y: en_out}) loss_list.append(mse_loss) if epoch % display_epoch == 0: print('Epoch %d, loss: %.3f'%(epoch, mse_loss)) plt.figure() plt.plot(list(range(len(loss_list))), loss_list) plt.xlabel('Epoch number') plt.ylabel('Loss') plt.title('Loss v.s. Epoch') plt.show() # Testing for are_same_digits in [True, False]: plt.figure(figsize=(20,18)) for digit in range(10): digit1, digit2 = None, None if are_same_digits: # Same digits digit_arr = label_img_dict[digit] # Randomly select two same digits same_digits = digit_arr[np.random.choice(digit_arr.shape[0], 2, replace=False), :] digit1 = same_digits[0,:].reshape(1,-1) digit2 = same_digits[1,:].reshape(1,-1) else: # Different digits # Randomly select two different digits permutation_arr = np.random.permutation(10) num1 = permutation_arr[0] num2 = permutation_arr[1] digit1 = label_img_dict[num1][np.random.choice(label_img_dict[num1].shape[0], 1, replace=False), :] digit2 = label_img_dict[num2][np.random.choice(label_img_dict[num2].shape[0], 1, replace=False), :] # Calculate corresponding codes code1 = sess.run(encoder_out, feed_dict={x: digit1}) code2 = sess.run(encoder_out, feed_dict={x: digit2}) reconstructed_img = [None]*9 reconstructed_img[0], reconstructed_img[8] = digit1, digit2 # Compute 7 evenly spaced linear interpolates for t in range(1, 8): code = ((8-t)/8)*code1 + (t/8)*code2 reconstructed_img[t] = sess.run(decoder_out, feed_dict={y: code}) for idx in range(9): plt.subplot(10,9,9*digit+idx+1) plt.imshow(reconstructed_img[idx].reshape(28,28), cmap='gray') if are_same_digits: plt.savefig('same.png') else: plt.savefig('different.png') train() <file_sep># Part 1B # Read CSV into R data = read.csv(file="Desktop/pima-indians-diabetes.csv") accuracy_vec = seq(1, 10, by=1) train_ratio = 0.8 attributes = c(3, 4, 6, 8) #blood pressure, skin thickness, BMI, age param = matrix(, nrow=8, ncol=4) for (iter in seq(1, 10, by=1)) { # Test-train spilts train_test_list = test_train_split(data, train_ratio, iter) train_data = train_test_list[[1]] test_data = train_test_list[[2]] # Calculate prior probabilities outcome = train_data[,9] n_positive = length(outcome[outcome==1]) n_negative = length(outcome[outcome==0]) P_positive = n_positive/length(outcome) P_negative = n_negative/length(outcome) # Calculate likelihood # Calculate normal distribution parameter for each feature for (attribute in attributes) { feature = train_data[,attribute] # Ignore zero entries aka missing values # I don't change 0 entries to NA, ignore those entries in this step remain_outcome = outcome[feature!=0] feature = feature[feature!=0] param[attribute, 1] = mean(feature[remain_outcome==1]) # positive_feature_mean param[attribute, 2] = var(feature[remain_outcome==1]) # positive_feature_var param[attribute, 3] = mean(feature[remain_outcome==0]) # negative_feature_mean param[attribute, 4] = var(feature[remain_outcome==0]) # negative_feature_var } confusion_matrix = estimate(test_data, param, attribute, P_positive, P_negative) n_correct = confusion_matrix[1,1] + confusion_matrix[2,2] accuracy = n_correct / nrow(test_data) accuracy_vec[iter] = accuracy } print(accuracy_vec) print(mean(accuracy_vec)) # Evaluate on test data and return the confusion matrix estimate = function(test_data, param, attribute, P_positive, P_negative) { true_positive = 0 false_positive = 0 true_negative = 0 false_negative = 0 logP_positive = log(P_positive) logP_negative = log(P_negative) for(index in seq(1, nrow(test_data), by=1)) { positive_log_p = 0 negative_log_p = 0 # Calculate log likelihood for (attribute in attributes) { if (test_data[index, attribute] == 0) { # Ignore this attribute next } else { positive_log_p = positive_log_p + evaluate_log_p(test_data[index,attribute], param[attribute, 1], param[attribute, 2]) negative_log_p = negative_log_p + evaluate_log_p(test_data[index,attribute], param[attribute, 3], param[attribute, 4]) } } if (logP_positive + positive_log_p > logP_negative + negative_log_p) { if (test_data[index, 9] == 1) { true_positive = true_positive + 1 } else { false_positive = false_positive + 1 } } else { if (test_data[index, 9] == 0) { true_negative = true_negative + 1 } else { false_negative = false_negative + 1 } } } confusion_matrix = matrix( c(true_positive, false_positive, false_negative, true_negative), nrow = 2, ncol = 2, byrow = TRUE ) return(confusion_matrix) } # Split the data test_train_split = function(data, train_ratio, seed) { set.seed(seed) sample = sample(seq_len(nrow(data)), size=floor(train_ratio*nrow(data))) train_data = data[sample,] test_data = data[-sample,] return(list(train_data, test_data)) } # Evalute log probability evaluate_log_p = function(feature, feature_mean, feature_var) { log_p = - ((feature - feature_mean)^2)/(2*feature_var) log_p = log_p + log(1/sqrt(2*pi*feature_var)) return(log_p) } <file_sep>library(caret) library(e1071) library(klaR) # Read CSV into R data = read.csv(file="Desktop/AML/pima-indians-diabetes.csv", header=TRUE, sep=",") accuracy_vec = seq(1, 10, by=1) for(seed in seq(1, 10)) { # Test train split set.seed(seed) in_train = createDataPartition(data[,9], p=0.8, list=FALSE) train_data = data[in_train, ] test_data = data[-in_train, ] # Train the model feature = train_data[,-9] label = as.factor(train_data[,9]) model = train(feature, label, 'nb', trControl=trainControl(method='cv', number=10)) prediction = predict(model$finalModel, test_data[,-9]) label_prediction = prediction$class # Calculate confusion matrix true_positive = 0 false_positive = 0 true_negative = 0 false_negative = 0 for(i in seq(1, nrow(test_data))) { if (label_prediction[i] == "Yes") { if (test_data[i,9] == 1) { true_positive = true_positive + 1 } else { false_positive = false_positive + 1 } } else { if (test_data[i, 9] == 0) { true_negative = true_negative + 1 } else { false_negative = false_negative + 1 } } } confusion_matrix = matrix( c(true_positive, false_positive, false_negative, true_negative), nrow = 2, ncol = 2, byrow = TRUE ) # print(confusion_matrix) n_correct = true_positive + true_negative accuracy = n_correct/nrow(test_data) accuracy_vec[seed] = accuracy } print(accuracy_vec) print(mean(accuracy_vec)) <file_sep>import numpy as np import numpy.linalg as la import pandas as pd import seaborn as sns import scipy.stats as stats import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from statsmodels.stats.outliers_influence import OLSInfluence import statsmodels.api as sm import statsmodels.formula.api as smf # Load the data data = np.loadtxt('data.txt') df = pd.DataFrame(data) # Linear regression X = data[:,:13] y = data[:,13].reshape(-1,1) # Method 1 lm = sm.OLS(y, sm.add_constant(X)).fit() # Method 2 reg = LinearRegression().fit(X, y) r_squared = reg.score(X,y) # Generate influence plot fig, ax = plt.subplots(figsize=(9,6)) fig = sm.graphics.influence_plot(lm, alpha=0.001, ax=ax, criterion='cooks') fig.show() #################### # Calculate leverage #################### beta_hat = np.dot(la.inv(np.dot(X.T, X)), np.dot(X.T, y)) hat_matrix = [email protected](np.dot(X.T, X))@(X.T) # plt.bar(list(range(hat_matrix.shape[0])),np.diag(hat_matrix)) # plt.boxplot(np.diag(hat_matrix)) leverage = np.diag(hat_matrix) # Remove leverage outliers and record their indices outliers_num_leverage= [] for i in range(leverage.shape[0]): if (leverage[i] > np.percentile(leverage, 75)+1.5*stats.iqr(leverage)): outliers_num_leverage.append(i) leverage_remove_outliers = leverage[leverage <= np.percentile(leverage, 75)+1.5*stats.iqr(leverage)] # Calculate residuals and mean square error y_predicted = X@beta_hat # Fitted value e = y - X@beta_hat N = y.shape[0] mean_squared_error = np.dot(e.T, e)/N # r_squred = np.var(X@beta_hat)/np.var(y) ########################################### # Calculate the cook distance for each data ########################################### cook_distance = np.zeros((y.shape[0],1)) for i in range(y.shape[0]): X_remove = np.delete(X, i, 0) y_remove = np.delete(y, i, 0) beta_i = np.dot(la.inv(np.dot(X_remove.T, X_remove)), np.dot(X_remove.T, y_remove)) y_p = [email protected](np.dot(X_remove.T, X_remove))@(X_remove.T)@y_remove cook_distance[i] = np.dot((y_p-X_remove@beta_i).T, y_p-X_remove@beta_i)/(N*mean_squared_error) # plt.bar(list(range(y.shape[0])), cook_distance) # plt.boxplot(cook_distance) outliers_num_cook_distance = [] for i in range(cook_distance.shape[0]): if (cook_distance[i] > np.percentile(cook_distance, 75)+1.5*stats.iqr(cook_distance)): outliers_num_cook_distance.append(i) cook_distance_remove_outliers = cook_distance[cook_distance <= np.percentile(cook_distance, 75)+1.5*stats.iqr(cook_distance)] ################################### # Calculate standardized residuals ################################### s = np.zeros((y.shape[0], 1)) for i in range(y.shape[0]): s[i] = e[i]/np.sqrt(mean_squared_error*(1-leverage[i])) # plt.bar(list(range(y.shape[0])), np.abs(s)) # plt.boxplot(s) outliers_num_s = [] for i in range(s.shape[0]): if (s[i] > np.percentile(s, 75)+1.5*stats.iqr(s)): outliers_num_s.append(i) # Remove outliers by_eye = True if by_eye: outliers_num = [364, 365, 368, 370, 371, 372, 380, 405, 410, 418] else: outliers_num = np.union1d(outliers_num_leverage, outliers_num_cook_distance) outliers_num = np.union1d(outliers_num, outliers_num_s) lm_remove = sm.OLS(y_remove, sm.add_constant(X_remove)).fit() X_remove = np.delete(X, outliers_num, 0) y_remove = np.delete(y, outliers_num, 0) s_remove = np.delete(s, outliers_num, 0) # Page1 n_interval = 50 lmbda_list = np.linspace(-2, 2, n_interval) llf_list = np.zeros(n_interval) for i in range(lmbda_list.shape[0]): llf_list[i] = stats.boxcox_llf(lmbda_list[i], y_remove) fig, ax = plt.subplots(figsize=(8,4)) plt.plot(lmbda_list, llf_list) plt.xlabel('Lambda value') plt.ylabel('Log likelihood') plt.title('Box-Cox Transformation Curve') plt.show() # Page 2 # Generate diagnostic plots before removing outliers before = True # Change this variable to False to generate diagnostic plot after removing outliers if before: model_residuals = lm.resid model_norm_residuals = lm.get_influence().resid_studentized_internal model_leverage = lm.get_influence().hat_matrix_diag model_cooks = lm.get_influence().cooks_distance[0] diagnostic_plot = plt.figure() plt.scatter(model_leverage, model_norm_residuals, alpha=0.5) sns.regplot(model_leverage, model_norm_residuals, scatter=False, ci=False, lowess=True, line_kws={'color':'red', 'lw':1, 'alpha':0.8}, label='Cook\'s distance') diagnostic_plot.axes[0].set_xlim(0, max(model_leverage)+0.01) diagnostic_plot.axes[0].set_ylim(-3,5) plt.title('Residuals vs Leverage\nBefore removing outliers') plt.xlabel('Leverage') plt.ylabel('Standardized Residuals') plt.legend() leverage_top_3 = np.flip(np.argsort(model_cooks), 0)[:3] for i in leverage_top_3: diagnostic_plot.axes[0].annotate(i, xy=(model_leverage[i], model_norm_residuals[i])) plt.show() # Boxcox transformation y_boxcox, maxlog = stats.boxcox(y_remove) # Influence plots after removing outliers and boxcox transformation lm_remove = sm.OLS(y_boxcox, sm.add_constant(X_remove)).fit() fig, ax = plt.subplots(figsize=(9,6)) fig = sm.graphics.influence_plot(lm_remove, alpha=0.001, ax=ax, criterion='cooks') fig.show() # Page 3 # Standardized residuals vs Fitted values without any transformation sns.residplot(y_predicted, s) plt.xlabel('Fitted values') plt.ylabel('Standardized residuals') plt.title('Without any transformation\nResiduals vs Fitted') plt.show() # Standardized residuals vs Fitted values removing all outliers and boxcox transformation beta_hat_prime = np.dot(la.inv(np.dot(X_remove.T, X_remove)), np.dot(X_remove.T, y_remove)) y_predicted_prime = X_remove@beta_hat_prime # Fitted house price sns.residplot(y_boxcox, np.delete(s, outliers_num)) plt.xlabel('Fitted values') plt.ylabel('Standardized residuals') plt.title('Removing all outliers and apply boxcox transformation\nResiduals vs Fitted') plt.show() # Page 4 # Fitted house price vs True house price plt.scatter(y_predicted_prime, y_remove) model = LinearRegression().fit(y_predicted_prime, y_remove) plt.plot(y_predicted_prime, model.predict(y_predicted_prime), 'r') print(model.score(y_predicted_prime, y_remove)) plt.xlabel('Fitted house price') plt.ylabel('True hous price') plt.title('After removing outliers and boxcox transformation') plt.show() <file_sep>import numpy as np import pandas as pd from sklearn.naive_bayes import BernoulliNB from sklearn.naive_bayes import GaussianNB from sklearn.ensemble import RandomForestClassifier import matplotlib.pyplot as plt import random import math import argparse from helper import * parser = argparse.ArgumentParser() parser.add_argument('--model_name', default='Gaussian', type=str) parser.add_argument('--preprocess', default=False, type=bool) parser.add_argument('--num_epochs', default=10, type=int) parser.add_argument('--test', default=True, type=bool) parser.add_argument('--path', default='yuchecw2_1.csv', type=str) parser.add_argument('--n_estimators', default=30, type=int) parser.add_argument('--max_depth', default=16, type=int) args = parser.parse_args() train_data = pd.read_csv("MNIST/train.csv") test_data = pd.read_csv("MNIST/test.csv") train_data = pd.DataFrame.as_matrix(train_data) test_data = pd.DataFrame.as_matrix(test_data) if args.preprocess: train_data = preprocess(train_data, False) if not args.test: ratio = 0.2 num_data = train_data.shape[0] num_val = (int)(num_data*ratio) accuracy_list = [] for epoch in range(args.num_epochs): random.seed(epoch) val_samples = random.sample(range(num_data), num_val) mask_array = np.ones((num_data, 1), dtype=bool) for i in val_samples: mask_array[i] = False label = np.empty((num_data-num_val, 1)) feature = np.empty((num_data-num_val, train_data.shape[1]-1)) idx = 0 for i in range(num_data): if (mask_array[i]): label[idx] = train_data[i,0] feature[idx, :] = train_data[i,1:] idx = idx + 1 val_label = train_data[val_samples, 0] val_feature = train_data[val_samples, 1:] # Create a model and train it if args.model_name == 'Gaussian': model = GaussianNB() elif args.model_name == 'Bernoulli': # Thresholding feature[feature>127] = 255 feature[feature<=127] = 0 val_feature[val_feature>127] = 255 val_feature[val_feature<=127] = 0 model = BernoulliNB() elif args.model_name == 'Random_Forest': model = RandomForestClassifier(n_estimators=args.n_estimators, max_depth=args.max_depth) label = np.ravel(label) fit_model = model.fit(feature, label) label_prediction = fit_model.predict(val_feature) num_correct = (val_label == label_prediction).sum() accuracy = num_correct/num_val accuracy_list.append(accuracy) print('Training and cross validation: uses %s model, preprocessed: %d, accuracy: %f'%(args.model_name, args.preprocess, sum(accuracy_list)/len(accuracy_list))) else: label = train_data[:,0] feature = train_data[:,1:] # Create a model and train it if args.model_name == 'Gaussian': model = GaussianNB() elif args.model_name == 'Bernoulli': feature[feature>127] = 255 feature[feature<=127] = 0 model = BernoulliNB() elif args.model_name == 'Random_Forest': model = RandomForestClassifier(n_estimators=args.n_estimators, max_depth=args.max_depth) label = np.ravel(label) fit_model = model.fit(feature, label) if args.preprocess: test_data = preprocess(test_data, True) test_prediction = fit_model.predict(test_data) df = pd.DataFrame(test_prediction) df_test_data = pd.DataFrame(test_data) df.to_csv(args.path) # Calculate class means if args.preprocess: original_size = 20 # box_size else: original_size = 28 num_classes = 10 mean = [None]*num_classes for label in range(num_classes): mean[label] = df_test_data[df[0]==label].mean() mean_matrix = [] for label in range(num_classes): a = np.empty((original_size, original_size)) for j in range(original_size): for i in range(original_size): if (mean[label][original_size*j+i] < 127): a[j, i] = 255 else: a[j, i] = 0 mean_matrix.append(a) plt.figure() for label in range(10): plt.subplot(1, 10, label+1) plt.imshow(mean_matrix[label], cmap='Greys') plt.axis('off') plt.show()
7c931ad5555bba1275f6ec02bc372371ca6a4a35
[ "Text", "Python", "R" ]
18
Python
jeffreyjeffreywang/Applied-Machine-Learning
1dcb4a304908e065c3b737ce4e025be1b5777b92
7f869c76a23c4349d13e459789d1801139d612c4
refs/heads/master
<file_sep>FROM python:3.6.2 # https://hub.docker.com/r/frolvlad/alpine-python3/ RUN apt-get update && \ apt-get -y install can-utils && \ pip install python-can #ADD scripts/vcanup.bash /vcanup.bash #RUN /vcanup.bash <file_sep>#!/bin/bash # install can-utils git clone https://github.com/linux-can/can-utils.git cd can-utils ./autogen.sh ./configure make sudo make install <file_sep>#!/bin/bash # Bring up a virtual can bus device /sbin/modprobe can /sbin/modprobe can_raw /sbin/modprobe vcan ip link add dev vcan0 type vcan ip link set up vcan0
9a58ffb3e746fb73e8371caef082fe995616fb01
[ "Dockerfile", "Shell" ]
3
Dockerfile
folkengine/docker-can
c875e6007ecdc7ae56be9b4da30d8aa14e7ef97c
e8a2d0e959f481d5213d1d6d90fd02d8c45b6951
refs/heads/master
<file_sep>$(document).ready(function(){ $(window).scroll(function(){ var wScroll = $(this).scrollTop(); $(".logo").css({ 'transform' : 'translate(0px, ' + wScroll/4 +'%)' }); if(wScroll> $(".product-section").offset().top -($(window).height()/1.3)){ $(".product-section figure").each(function(i){ setTimeout(function(){ $(".product-section figure").eq(i).addClass("is-showing"); }, 150* (i+1)); }); } if(wScroll>$(".large-window").offset().top-$(window).height()){ $(".large-window").css({'background-position':'center '+ (wScroll -$(".large-window").offset().top) +'px'}); var opacity = (wScroll-$(".large-window").offset().top+400) / (wScroll/5); $(".window-tint").css({'opacity':opacity}); } if(wScroll>$(".blog-posts").offset().top-$(window).height()){ var offset = Math.min(0, wScroll - $(".blog-posts").offset().top +$(window).height()-350); $(".post-1").css({'transform':'translate('+offset+'px, '+Math.abs(offset*0.2)+'px)'}); $(".post-3").css({'transform':'translate('+Math.abs(offset)+'px, '+Math.abs(offset*0.2)+'px)'}); } }); $("figure").hover(function(){ $(this).find("figcaption").css("left", "0%"); $(this).find("img").css("transform", "scale(1.3)"); }, function(){ $(this).find("figcaption").css("left", "-100%"); $(this).find("img").css("transform", "scale(1)"); }); });
7287933defe5f0d9b759bd20d87a1fd73b28d52d
[ "JavaScript" ]
1
JavaScript
bizhe/Parallax-Design
c7f0feb8a5ba9ae45f04edf9cad325a65c421090
1fd66a4598e6c4fbacbddaa36b2c928076800fd5
refs/heads/master
<repo_name>falkemedia/pdf-extractor<file_sep>/src/Exceptions/FileDoesNotExist.php <?php namespace falkemedia\PdfExtractor\Exceptions; class FileDoesNotExist extends \Exception { } <file_sep>/src/Extractor.php <?php namespace falkemedia\PdfExtractor; use falkemedia\PdfExtractor\Exceptions\BinaryNotFound; use Intervention\Image\ImageManager; use falkemedia\PdfExtractor\Exceptions\PageOutOfBounds; use falkemedia\PdfExtractor\Exceptions\FileDoesNotExist; use Imagick; use Spatie\PdfToText\Pdf; use SQLite3; class Extractor { protected $pdfPath; protected $pdf; protected $imagick; protected $pageCount; protected $resolution = 144; protected $maxThumbnailWidth, $maxThumbnailHeight; protected $quality = 90; private function generatePdfToTextBinPath() { $path = exec('which pdftotext'); if (empty($path)) { throw new BinaryNotFound("Could not find the `pdftotext` binary on your system."); } return $path; } /** * Loads a PDF file from a given file path. * * @param String $file * @return Extractor * @throws FileDoesNotExist */ public function load(string $file) { if (!file_exists($file)) { throw new FileDoesNotExist("File `{$file}` does not exist"); } // Store the filepath. (Will later be used to determine f.ex. a storage path for images) $this->pdfPath = $file; // Create the imagick instance and ping the file (to gather basic infos about the pdf like the page count) $this->imagick = new Imagick(); $this->imagick->pingImage($file); // Store the page count of the current PDF file. $this->pageCount = $this->imagick->getNumberImages(); // Create the Pdf object $this->pdf = new Pdf($this->generatePdfToTextBinPath()); $this->pdf->setPdf($file); // Make this call chainable. return $this; } /** * Sets the max width of the thumbnail. * If reached the height will be calculated in respect to the aspect ratio of the image. * * @param int $width * @return $this */ public function setMaxThumbnailWidth(int $width) { $this->maxThumbnailWidth = $width; return $this; } /** * Sets the max height of the thumbnail. * If reached the width will be calculated in respect to the aspect ratio of the image. * * @param int $height * @return $this */ public function setMaxThumbnailHeight(int $height) { $this->maxThumbnailHeight = $height; return $this; } /** * Sets the image quality. * Being 0 the lowest and 100 the highest quality. * * @param int $quality * @return $this */ public function setQuality(int $quality) { $this->quality = $quality; return $this; } /** * Sets the resolution used by ImageMagic. * This is not a px resolution like you might think! * Details: https://www.php.net/manual/de/imagick.setresolution.php * * You probably won't need to touch this. * If you like to change the resolution of the resulting thumbnail * look at setMaxThumbnailHeight() or setMaxThumbnailWidth(). * * @param int $resolution * @return $this */ public function setResolution(int $resolution) { $this->resolution = $resolution; return $this; } /** * This generates a thumbnail from a given page. * * @param int $page * @return \Intervention\Image\Image * @throws PageOutOfBounds * @throws \ImagickException */ public function generateThumbnailFromPage($page = 1) { if ($page > $this->pageCount) { throw new PageOutOfBounds("Page `{$page}` is beyond the last page the end of this PDF. Total page count is `{$this->pageCount}`"); } if ($page < 1) { throw new PageOutOfBounds("Page `{$page}` is not a valid page number."); } // Reinitialize imagick because the target resolution must be set // before reading the actual image. $this->imagick = new Imagick(); $this->imagick->setResolution($this->resolution, $this->resolution); // Load the page as image. $this->imagick->readImage(sprintf('%s[%s]', $this->pdfPath, $page - 1)); // Flatten the image. $this->imagick = $this->imagick->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN); // Create an intervention image from the ImageMagic instance. // create an image manager instance with favored driver $manager = new ImageManager(['driver' => 'imagick']); // to finally create image instances $img = $manager->make($this->imagick); // If we did set at least one constraint (width or height) // we resize the image with respect to the aspect ratio. if ($this->maxThumbnailWidth != null || $this->maxThumbnailHeight != null) { $img->resize($this->maxThumbnailWidth, $this->maxThumbnailHeight, function ($constraint) { $constraint->aspectRatio(); }); } return $img; } /** * Saves an image to the disk at a given path. * * @param \Intervention\Image\Image $image * @param int $pageNumber * @param String $storagePath * @param String $prefix * @param String $suffix */ public function storeThumbnail(\Intervention\Image\Image $image, $pageNumber, $storagePath = null, $prefix = null, $suffix = null) { if ($image == null) { return; } $storagePath = $this->checkOrCreateStoragePath($storagePath); $filename = $pageNumber; // If present append the suffix. if ($suffix != null) { $filename = $filename . $suffix; } // If present prepend the prefix. if ($prefix != null) { $filename = $prefix . $filename; } // finally we save the image as a new file $image->save($storagePath . $filename . '.jpg', $this->quality); } /** * Generates thumbnail images from individual pages of the loaded pdf document. * * @param String $storagePath * @param String $prefix * @param String $suffix * @throws PageOutOfBounds * @throws \ImagickException */ public function generateThumbnails($storagePath = null, $prefix = null, $suffix = null) { for ($page = 1; $page <= $this->pageCount; $page++) { // Generate the thumbnail for this page. $thumbnail = $this->generateThumbnailFromPage($page); // Store that thumbnail. $this->storeThumbnail($thumbnail, $page, $storagePath, $prefix, $suffix); } } /** * Returns the text of a single page. * * @param int $page * @return String * @throws PageOutOfBounds */ public function getTextOfPage($page = 1) { if ($page > $this->pageCount) { throw new PageOutOfBounds("Page `{$page}` is beyond the last page the end of this PDF. Total page count is `{$this->pageCount}`"); } if ($page < 1) { throw new PageOutOfBounds("Page `{$page}` is not a valid page number."); } return $this->pdf->setOptions(["f {$page}", "l {$page}"])->text(); } /** * Returns an array containing the text of one page per item. * * @return Page[] * @throws PageOutOfBounds */ public function getTextOfAllPages() { $pages = []; for ($page = 1; $page <= $this->pageCount; $page++) { // Get the text for this page. $text = $this->getTextOfPage($page); $pages[] = new Page($page, $text); } return $pages; } /** * This generates an optimized SQLite database storage containing the pages and their text contents. * It can be used to do an efficient full-text search. * It uses an FTS4 table for optimal performance. * More info: https://sqlite.org/fts3.html * * @param String $storagePath * @param String $filename * @param string $tableName * @throws PageOutOfBounds */ public function generateTextDatabase($storagePath = null, $filename = null, $tableName = "pages") { // Generate a full path with the given storage path and filename. $storagePath = $this->checkOrCreateStoragePath($storagePath, $filename ?? "database.sqlite"); $db = new SQLite3($storagePath); $db->enableExceptions(true); try { $db->exec("DROP TABLE {$tableName}"); } catch (\Exception $e) {} try { $db->exec("CREATE VIRTUAL TABLE {$tableName} USING fts4(page, body);"); } catch (\Exception $e) {} // This will return an array full of Page objects. $pages = $this->getTextOfAllPages(); foreach ($pages as $page) { try { $db->query("INSERT INTO {$tableName}(page, body) VALUES($page->number, '{$page->text}');"); } catch (\Exception $e) { echo "There was a problem storing the contents of page {$page->number}\n"; echo $e->getMessage(); echo "\n\n\n"; } } } /** * Checks if a given storage path is valid. * If not it generates a path based on the PDF path. * * @param String $storagePath * @param String $filename * @return string */ private function checkOrCreateStoragePath($storagePath = null, $filename = null) { // If no databaseFilepath is provided we need to create our own. // By default the folder of the source PDF is used as a base path // with /export/ appended to it. $storagePath = ($storagePath == null) ? dirname($this->pdfPath) . '/export' : $storagePath; // remove any trailing slash if present so we have known string. $storagePath = rtrim($storagePath, '/'); // Now we know we have exactly one trailing slash :) $storagePath = $storagePath . "/"; // Does the storage path already exist? // If not lets create it.. $this->checkPath($storagePath); // Did we provide a filename? if ($filename != null) { $storagePath = $storagePath . $filename; } return $storagePath; } /** * Creates a directory at the given path if not present. * * @param $path */ private function checkPath($path) { if (!is_dir($path)) { mkdir($path); } } } <file_sep>/src/Exceptions/PageOutOfBounds.php <?php namespace falkemedia\PdfExtractor\Exceptions; class PageOutOfBounds extends \Exception { } <file_sep>/CHANGELOG.md # Changelog All notable changes to `pdf-extractor` will be documented in this file ## 1.0.0 - 2020-08-04 - initial release <file_sep>/README.md # PDF Extractor [![Latest Version on Packagist](https://img.shields.io/packagist/v/falkemedia/pdf-extractor.svg?style=flat-square)](https://packagist.org/packages/falkemedia/pdf-extractor) [![Total Downloads](https://img.shields.io/packagist/dt/falkemedia/pdf-extractor.svg?style=flat-square)](https://packagist.org/packages/falkemedia/pdf-extractor) This package automates the generation of an SQLite database that you can use to do a full-text search on a PDF. Meaning you take your PDF, use this tool to generate a database and then query the database and not the PDF for any text search. This tool also generates thumbnails that you can use to display your search results however you like. This is heavily inspired [spatie/pdf-to-image](https://github.com/spatie/pdf-to-image) and has a dependency of [spatie/pdf-to-text](https://github.com/spatie/pdf-to-text) ## Installation You can install the package via composer: ```bash composer require falkemedia/pdf-extractor ``` This package requires the installation of ImageMagic and the **imagick** php extension. Instructions for macOS Catalina + PHP 7.3: ```bash brew install imagemagick pecl install imagick ``` > If there are any errors with imagemagic I suggest [reading through this guide](https://medium.com/@girishkr/install-imagick-on-macos-catalina-php-7-3-64b4e8542ba2) Also, behind the scenes this package leverages [pdftotext](https://en.wikipedia.org/wiki/Pdftotext). On a mac you can install the binary using brew ```bash brew install poppler ``` ## Usage examples/extract_pdf_data.php ``` php <?php namespace falkemedia\PdfExtractor\Examples; use falkemedia\PdfExtractor\Extractor; require 'vendor/autoload.php'; // Load PDF $extractor = new Extractor(); $extractor->load('/path/to/a/pdf/file.pdf'); // Generate thumbnails $extractor ->setMaxThumbnailHeight(600) ->setMaxThumbnailWidth(480) ->setQuality(75) ->generateThumbnails(); // Store Fulltext infos $extractor->generateTextDatabase(); ``` If you have a saved sqlite database you can do full-text queries like for example: ```sqlite SELECT*FROM pages WHERE body MATCH "*YOUR_SEARCH_QUERY*" ``` ### Testing ``` bash composer test ``` ### Changelog Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently. ## Contributing Please see [CONTRIBUTING](CONTRIBUTING.md) for details. ### Security If you discover any security related issues, please email <EMAIL> instead of using the issue tracker. ## Credits - [falkemedia](https://github.com/falkemedia) - [<NAME>](https://github.com/robin7331) - [All Contributors](../../contributors) ## License The MIT License (MIT). Please see [License File](LICENSE.md) for more information. ## PHP Package Boilerplate This package was generated using the [PHP Package Boilerplate](https://laravelpackageboilerplate.com). <file_sep>/src/Exceptions/BinaryNotFound.php <?php namespace falkemedia\PdfExtractor\Exceptions; use Exception; class BinaryNotFound extends Exception { } <file_sep>/src/Page.php <?php namespace falkemedia\PdfExtractor; class Page { public $number; public $text; /** * Page constructor. * @param $number * @param $text */ public function __construct($number, $text) { $this->number = $number; $this->text = $text; } } <file_sep>/src/examples/extract_pdf_data.php <?php namespace falkemedia\PdfExtractor\Examples; use falkemedia\PdfExtractor\Extractor; require 'vendor/autoload.php'; // Load PDF $extractor = new Extractor(); $extractor->load('/path/to/a/pdf/file.pdf'); // Generate Thumbnails $extractor ->setMaxThumbnailHeight(600) ->setMaxThumbnailWidth(480) ->setQuality(75) ->generateThumbnails(); // Store Fulltext infos $extractor->generateTextDatabase();
321e2d720aa942003a0528d6c2b7ddbc20de6c53
[ "Markdown", "PHP" ]
8
PHP
falkemedia/pdf-extractor
b6f9cd16444ee932df7aecdcc9b48499958ed280
f8fba7d7cf2b8d27b0b98bd6879a5610daac2c35
refs/heads/master
<file_sep># CsharpStuff C sharp apps I developed WinFormsApplication1 - click on form changes the size and color of the form randomly <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load_1(object sender, EventArgs e) { Text = "Prvi Program"; Width = 500; Height = 500; } private void Form1_MouseClick(object sender, MouseEventArgs e) { Random R = new Random(); BackColor = Color.FromArgb(R.Next(256), R.Next(256), R.Next(256)); Width = R.Next(300, 500); Height = R.Next(200, 500); Text = "Kliknuli ste na polje (" + e.X + "," + e.Y + ")"; } // private void Form1_Load_1_MouseClick(object sender, MouseEventArgs e) // { // } } }
d1c7e6152657691bde8e44d55fbcdc7d6e840c9f
[ "Markdown", "C#" ]
2
Markdown
megas333/CsharpStuff
a35bbe7c629e6c8f26bec6326b4782b9316d4559
045f128e6625a61bf60620ea3b3be3b49c6fe27c
refs/heads/master
<file_sep> /// /// @file constructor.cc /// @author Islotus(<EMAIL>) /// @date 2016-06-08 18:18:52 /// #include <iostream> using std :: cout; using std :: cin; using std :: endl; class point { public: point ( int x, int y ) //有参构造函数 { cout << "对象创建时构造函数被自动调用" << endl; _xPos = x; _yPos = y; } void print () { cout << "xPos: " << _xPos << ", yPos: " << _yPos << endl; } private: //私有成员 int _xPos; int _yPos; }; int main() { // point pt0 (); // pt0.print (); point pt1 (3,4); //调用有参构造函数声明point类变量(类对象)pt1 pt1.print (); return 0; } <file_sep> /// /// @file constructor_default_parameter.cc /// @author Islotus(<EMAIL>) /// @date 2016-06-08 22:21:31 /// #include <iostream> using std :: cout; using std :: cin; using std :: endl; class point { public: point (int x = 0, int y = 0) //有参构造函数 { cout << "对象创建时构造函数自动调用" << endl; _xPos = x; _yPos = y; } void print () { cout << "xPos: " << _xPos << ",yPos: " << _yPos << endl; } private: int _xPos; int _yPos; }; int main() { point pt0; pt0.print (); point pt1 (3, 4); pt1.print (); return 0; } <file_sep> /// /// @file initialize_expression.cc /// @author Islotus(<EMAIL>) /// @date 2016-06-08 22:39:20 /// #include <iostream> using std :: cin; using std :: cout; using std :: endl; class point { public: point(int x) //初始化表取决于成员声明的顺序 :_xPos (x) ,_yPos (_xPos) { } void print () { cout << "_xPos: " << _xPos << ",_yPos: " << _yPos << endl; } private: int _yPos; //先定义 int _xPos; //后定义 // int _xPos; // int _yPos; }; int main() { point pt1 (3); pt1.print (); return 0; } <file_sep> /// /// @file learn_class1.cc /// @author Islotus(<EMAIL>) /// @date 2016-06-08 09:09:03 /// //在类定义的外部定义成员函数 class computer //类定义,起到接口作用 { public: //3个public成员函数的原型声明 void print(); void SetBrand(const char *sz); void SetPrice(float pr); private: char brand [20]; float price; }; #include <iostream> #include <cstring> using namespace std; void computer :: print() //成员函数的实现,注意作用域限定符的使用 { cout << "品牌:" << brand << endl; cout << "价格:" << price << endl; } void computer :: SetBrand(const char *sz) { strcpy (brand,sz); //字符串复制 } void computer :: SetPrice (float pr) { price = pr; } int main() { computer com1; com1.SetPrice (5000); com1.SetBrand ("Lenovo"); com1.print(); return 0; } <file_sep> /// /// @file exercise1.cc /// @author Islotus(<EMAIL>) /// @date 2016-06-08 17:33:18 /// //创建文件student.cpp,并在文件中定义SetInfo和Display成员函数的实现 #include <iostream> #include <cstring> using std :: cout; using std :: cin; using std :: endl; //using namespace std; class CStudent { public: void SetInfo (int id,const char * pszName); //将学生ID和姓名赋值给成员变量 void Display (); //打印出成员变量 private: int _m_ild; char _m_szName [32]; }; void CStudent :: SetInfo (int ild, const char * pszName) { _m_ild = ild; strcpy (_m_szName, pszName); } void CStudent :: Display () { cout << "the student named" << _m_szName << "s id is" << _m_ild << endl; } //最后在main.cc中使用该类 int main() { //栈中实现 CStudent stud; stud.SetInfo (3, "Tom" ); stud.Display (); //堆中实现 CStudent * pStud = new CStudent; pStud -> SetInfo (0, "Bill" ); pStud -> Display(); (* pStud).Display (); delete pStud; //释放申请的空间 pStud = NULL; //指针赋空值 // return 0; } <file_sep> /// /// @file computer_class.h /// @author Islotus(<EMAIL>) /// @date 2016-06-08 08:53:04 /// class computer { char brand [20]; //默认为private类型 public: //这里的private不能省略,因为不是在类定义的开始位置 void print(); private: float price; public: void SetBrand (char * sz); void SetBrand (float pr); }; <file_sep> /// /// @file object_declaration.cc /// @author Islotus(<EMAIL>) /// @date 2016-06-08 17:14:36 /// class computer { public: void print (); void SetBrand (const char * sz ); void SetPrice (float pr ); private: char _brand [20]; float _price; }; //不能忘记; #include <iostream> #include <cstring> using namespace std; void computer :: print() { cout << "品牌:" << _brand << endl; cout << "价格:" << _price << endl; } void computer :: SetBrand (const char * sz) { strcpy(_brand, sz); } void computer :: SetPrice (float pr) { _price = pr; } int main() { computer com1; com1.SetBrand ("lenovo"); com1.SetPrice (8000); com1.print (); return 0; } <file_sep> /// /// @file overloaded_constructor.cc /// @author Islotus(<EMAIL>) /// @date 2016-06-08 18:33:01 /// #include <iostream> using std :: cin; using std :: cout; using std :: endl; class point { public: point ( int x, int y ) //有参构造函数 { cout << "有参构造函数的调用" << endl; _xPos = x; _yPos = y; } point () { cout << "无参构造函数的调用" << endl; _xPos = 0; _yPos = 0; } void print () { cout << "xPos: " << _xPos << ",yPos: " << _yPos << endl; } private: int _xPos; int _yPos; }; int main() { point pt1 (3,4); pt1.print (); point pt2; pt2.print (); return 0; } <file_sep> /// /// @file learn_class.cc /// @author Islotus(<EMAIL>) /// @date 2016-06-08 08:47:48 /// //在类定义时定义成员函数 #include <iostream> #include <cstring> using namespace std; class computer { public: //在类定义的同时实现了3个成员函数 void print() { cout << "品牌:" << brand << endl; cout << "价格:" << price << endl; } void SetBrand(const char * sz) { strcpy(brand,sz); //字符串复制 } void SetPrice(float pr) { price = pr; } private: char brand [20]; float price; }; //#include "computer_class.h" //包含了computer类的定义 int main() { computer com1; //声明创建一个类对象 com1.SetPrice (5000); com1.SetBrand ("Lenovo"); com1.print(); return 0; } <file_sep> /// /// @file area_of_rectangle.cc /// @author Islotus(<EMAIL>) /// @date 2016-06-08 08:16:24 /// //用面向对象的方法求矩形的面积 //首先定义一个矩形类,然后矩形有长、宽属性,有求面积的方法等 #include <iostream> using namespace std; class CRectangle { public: CRectangle(float l = 0.0f, float w = 0.0f) { this -> length = l; this -> width = w; } float area() { return this -> length * this -> width; } //... private: float length; float width; }; int main() { CRectangle rect(3.0f, 4.0f); cout << rect.area() << endl; return 0; }
a8a2aee9020806e41f0828f0f6e7b2741314c151
[ "C++" ]
10
C++
Islotus/08062016
4d72f8d70c8c1091b443d771578a4f31efb27ccd
9b8506a7b1e6b90573f928cb4d078fd2fe885b80
refs/heads/master
<file_sep>rootProject.name = 'serveranalytics' <file_sep>gradle --daemon clean test distZip -x processResources <file_sep>package de.tlongo.serveranalytics.test; import org.hibernate.annotations.Type; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import java.time.LocalDateTime; /** * Created by <NAME> on 10/9/14. */ @Entity(name = "foo") public class Foo { @Type(type="de.tlongo.serveranalytics.services.logfileservice.LocalDateTimeUserType") public LocalDateTime date; @Id @GeneratedValue(strategy = GenerationType.AUTO) long id; public Foo() { } public Foo(LocalDateTime date) { this.date = date; } } <file_sep>package de.tlongo.serveranalytics.services.logfileservice; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.sql.Timestamp; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; /** * Created by tomas on 18.09.14. */ public class LogFileParser { static Logger logger = LoggerFactory.getLogger(LogFileParser.class); static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z"); private static final List<LogEntry> EMPTY_LIST = new ArrayList<>(); public static boolean isEntryValid(LogEntry entry) { return entry.getStatus() != -9999; } /** * Parses a nginx log file line by line, extracts information and returns a list * of LogEntry objects * * @param logFile The log file to parse * * @return A list of LogEntry objects. An empty list if an error occurs. */ public static List<LogEntry> parseLogFile(File logFile, String producingApp) { try { List<LogEntry> entryList = new ArrayList<>(); BufferedReader reader = new BufferedReader(new FileReader(logFile)); String line = null; while ((line = reader.readLine()) != null) { if (line.isEmpty()) continue; LogEntry entry = new LogEntry(); String[] tokens = line.split("@"); if (tokens.length != 5) { // Trying to split this log line into its components by the delimeter '@' // caused an error because '@' was part of the line itself. // Mark entry as invalid in order to get some metrics on how often this // occurs. We might have to change the separator. entry.setStatus(-9999); } else { entry.setAddress(tokens[0]); entry.setDate(Timestamp.valueOf(LocalDateTime.parse(tokens[1], formatter))); entry.setStatus(Integer.parseInt(tokens[3])); entry.setAgent(tokens[4]); entry.setProducedBy(producingApp); String[] requestTokens = splitRequestString(tokens[2]); if (requestTokens.length != 3) { entry.setStatus(-9999); } else { entry.setRequestMethod(requestTokens[0]); entry.setRequestUri(requestTokens[1]); entry.setRequestProtocol(requestTokens[2]); } } entryList.add(entry); } return entryList; } catch (FileNotFoundException e) { logger.error("Could not find file under path {}", logFile.getAbsolutePath()); return EMPTY_LIST; } catch (IOException e) { logger.error("Error parsing logfile {}\n{}", logFile.getAbsolutePath(), e); return EMPTY_LIST; } } private static String[] splitRequestString(String requestString) { // tokens = [method, uri, protocol] String[] tokens = requestString.split(" "); return tokens; } /** * Parses log files located in the specified directory. * * @return A List of log entries extracted from the files in the directory. */ public static List<LogEntry> parseLogDirectory(String logDir) { File dir = new File(logDir); if (!dir.isDirectory()) { logger.error("{} is not a directory", logDir); return EMPTY_LIST; } logger.info("Parsing log files in directory {}", dir.getAbsolutePath()); try { List<LogEntry> logEntryList = new ArrayList<>(); DirectoryStream<Path> directoryStream = Files.newDirectoryStream(dir.toPath()); directoryStream.forEach(path -> { File logFile = new File(path.toAbsolutePath().toString()); if (!logFile.isDirectory() && logFile.getName().contains("log")) { logger.info("Parsing logfile {}", logFile.getAbsolutePath()); List<LogEntry> list = parseLogFile(logFile, dir.toPath().getFileName().toString()); logEntryList.addAll(list); } }); return logEntryList; } catch (IOException e) { logger.error("Could not find directory under {}", logDir); return EMPTY_LIST; } } } <file_sep>apply plugin: 'java' apply plugin: 'application' sourceCompatibility = 1.8 version = '2.0.3' mainClassName = "de.tlongo.serveranalytics.services.logfileservice.LogService" repositories { mavenCentral() } dependencies { compile 'com.sparkjava:spark-core:2.0.0' compile 'org.codehaus.groovy:groovy-all:2.3.6' compile 'commons-cli:commons-cli:1.2' compile 'com.google.code.gson:gson:2.2.4' compile 'org.springframework.data:spring-data-jpa:1.7.0.RELEASE' compile 'ch.qos.logback:logback-classic:1.1.1' compile 'org.hibernate.javax.persistence:hibernate-jpa-2.0-api:1.0.1.Final' compile('org.hibernate:hibernate-entitymanager:4.3.6.Final') { //The pacage that comes with hibernate is not Java8 compatible exclude group: 'org.javassist' } compile 'org.javassist:javassist:3.18.2-GA' compile 'mysql:mysql-connector-java:5.1.6' compile 'com.rabbitmq:amqp-client:3.4.4' testCompile 'org.springframework:spring-test:4.0.7.RELEASE' testCompile 'org.hamcrest:hamcrest-all:1.3' testCompile group: 'junit', name: 'junit', version: '4.11' } installApp { // copy the configs to external folder into("lib/config") { from 'src/main/resources' include '*' } } distZip { archiveName = "${project.name}.zip" ext.versionFileName ="${version}.version" ext.versionFile = file(versionFileName) // copy the configs to external folder into("$baseName/lib/config") { from 'src/main/resources' include '*' } into("$baseName") { from "${project.projectDir.toPath().toAbsolutePath().toString()}" include versionFileName } doFirst { versionFile.createNewFile() } doLast { versionFile.delete() } } // Adde the config folder to the classpath of the config script startScripts.classpath += files("config") <file_sep>package de.tlongo.serveranalytics.test; import de.tlongo.serveranalytics.services.logfileservice.LogEntry; import de.tlongo.serveranalytics.services.logfileservice.LogEntryRepository; import de.tlongo.serveranalytics.services.logfileservice.LogFileParser; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.io.File; import java.net.URL; import java.sql.Timestamp; import java.time.LocalDateTime; import java.time.Month; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collector; import java.util.stream.Collectors; import static org.hamcrest.Matchers.*; import static org.hamcrest.MatcherAssert.*; /** * Created by tomas on 19.09.14. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/springdataconfig.xml") public class TestPersistence { @Autowired LogEntryRepository repo; @Before public void clearDatabase() { repo.deleteAll(); } @Test @Ignore public void testPersistLogEntry() throws Exception { LocalDateTime currentDateTime = LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS); LogEntry entry = new LogEntry(); entry.setAgent("Mausi"); entry.setDate(Timestamp.valueOf(currentDateTime)); repo.save(entry); LogEntry loaded = repo.findOne(entry.getId()); assertThat(loaded, notNullValue()); assertThat(loaded.getAgent(), equalTo("Mausi")); assertThat(loaded.getDate(), equalTo(Timestamp.valueOf(currentDateTime))); System.out.println(loaded.getDate().toString()); } @Test @Ignore public void testPersistParsedFile() throws Exception { List<LogEntry> logEntries = LogFileParser.parseLogFile(new File("src/test/logdir/fixed/access.log.2"), "Test"); logEntries.forEach(entry -> { repo.save(entry); }); long count = repo.count(); assertThat(count, equalTo((long)logEntries.size())); } @Test @Ignore public void testPersistParsedDirectory() throws Exception { List<LogEntry> logEntries = LogFileParser.parseLogDirectory("src/test/logdir/fixed"); logEntries.forEach(entry -> { repo.save(entry); }); long count = repo.count(); assertThat(count, equalTo((long) logEntries.size())); } @Test public void testFindByDateRange() throws Exception { String dir = new ClassPathResource("/logdir/fixed/access.log.2").getFile().toPath().normalize().toAbsolutePath().toString(); List<LogEntry> logEntries = LogFileParser.parseLogFile(new File(dir), "test"); logEntries.forEach(entry -> { repo.save(entry); }); long count = repo.count(); assertThat(count, equalTo((long) logEntries.size())); Timestamp start = Timestamp.valueOf(LocalDateTime.of(2014, Month.OCTOBER, 18, 19, 57, 2).truncatedTo(ChronoUnit.DAYS)); Timestamp end = Timestamp.valueOf(LocalDateTime.of(2014, Month.OCTOBER, 19, 19, 57, 2).truncatedTo(ChronoUnit.DAYS)); List<LogEntry> entries = repo.findByDateRange(start, end); assertThat(entries, notNullValue()); assertThat(entries, hasSize(6)); start = Timestamp.valueOf(LocalDateTime.of(2014, Month.SEPTEMBER, 22, 19, 57, 2).truncatedTo(ChronoUnit.DAYS)); end = Timestamp.valueOf(LocalDateTime.of(2014, Month.SEPTEMBER, 23, 19, 57, 2).truncatedTo(ChronoUnit.DAYS)); entries = repo.findByDateRange(start, end); assertThat(entries, notNullValue()); assertThat(entries, hasSize(73)); } @Test public void testFindByIdList() throws Exception { String logfile = new ClassPathResource("/logdir/fixed/access.log.3").getFile().toPath().toAbsolutePath().normalize().toString(); List<LogEntry> logEntries = LogFileParser.parseLogFile(new File(logfile), "test"); repo.save(logEntries); String idList = logEntries.stream(). map(entry -> String.valueOf(entry.getId())). collect(Collectors.joining(",")); System.out.println("<<<" + idList + ">>>"); List<Long> longIds = Arrays.stream(idList.split(",")).map(stringid -> Long.parseLong(stringid)).collect(Collectors.toCollection(ArrayList::new)); idList = longIds.stream(). map(longId -> longId.toString()). collect(Collectors.joining(",")); System.out.println("<<<" + idList + ">>>"); long now = System.currentTimeMillis(); List<LogEntry> finalFetch = repo.findAll(longIds); double time = (double)(System.currentTimeMillis() - now) / 1000.0; System.out.println("TIME: " + time); assertThat(finalFetch, hasSize(logEntries.size())); assertThat(finalFetch, equalTo(logEntries)); } } <file_sep>#Taks ##Elastic Search Integration ElasticSearch soll Logeinträge indzieren. Hauptgrund hierfür ist die spätere Verwendung von Kibana zur Visualisierung. Der Logfileservice soll nach jedem Parselauf die aktuell gefundenen Einträge in eine Queue schreiben (zusätzlich zum Eintragen in eine DB). Dort horcht jeder mit, der an den Logeinträgen interessiert ist. * GET Route, die eine Liste von IDs entgegennimmt und die entsprechenden Logs aus der DB liefert * Nach jedem täglichen Import, die frischen LogIDs in die Queue schreiben<file_sep>logfileservice.logdir=src/test/logdir/fixed logfileservice.persisting.perLogFile=true<file_sep>package de.tlongo.serveranalytics.test; import org.springframework.data.jpa.repository.JpaRepository; /** * Created by tomas on 10/9/14. */ public interface FooRepo extends JpaRepository<Foo, Long> { }
ff8096466a3b5fcfbd96e25c7fc2e39a6c938c4c
[ "Markdown", "INI", "Gradle", "Java", "Shell" ]
9
Gradle
TomasLongo/logfileservice
d201a9acb1028794587d62e31baaf8a3c8ab10c7
b33eba523dbb0a6e567c5ab33094c6890b83acfd
refs/heads/master
<repo_name>heathzj/70M<file_sep>/Drivers/External-Peripherals/oled_c1.h #ifndef OLED_C1_H #define OLED_C1_H #include "define.h" #include "TCPIP Stack/TCPIP.h" #define I2C_nLOLOCK 0x01u #define I2C_nALC 0x02u #define I2C_nMUTE 0x04u #define nLCDLEN 40 #define nBYTE_COMPARE 0 typedef struct { const char* pcTitle; char cTitleIndex; char* pcContent; }tstLCDMenu; extern char FirmwareVersion[4]; extern char LOStatusString1[9]; extern char LOStatusString2[9]; extern char RFFreqString1[12]; extern char RFFreqString2[12]; extern char AttenString1[8]; extern char AttenString2[8]; extern char IPString[16]; extern char MNString[18]; extern char SNString[9]; extern char s18VDC[4]; extern char s24VDC[4]; extern char sLNBREF[4]; extern char sBUCREF[4]; extern char sUCPower[10]; extern char sDCPower[10]; extern char sUPC_StPwr[10]; extern char sDNC_StPwr[10]; extern char sALCa[4]; extern char sALCb[4]; extern char sMutea[9]; extern char sMuteb[9]; extern unsigned char EditMode; extern unsigned char EditPosition; extern unsigned char FirstPressKey; extern char LCDPrintBuffer[2][40]; extern char LCDBlinkBuffer[2][40]; extern const rom char acLCDTitle[30][nLCDLEN]; extern const rom char acLCDBlinkTitle[23][nLCDLEN]; typedef struct{ void (*pvfPrintMenu)(void); void (*pvfSetValue)(void); void (*pvfMoveCursorLeft)(void); void (*pvfMoveCursorRight)(void); BYTE u8RightMenu; BYTE u8LeftMenu; BYTE u8UpMenu; BYTE u8DownMenu; BYTE u8BlinkPos; /* Start position for blinking text */ BYTE u8BlinkLen; /* Length for blinking text */ }tstMenuDisplay; typedef union { unsigned long u32Freq; unsigned char u8Freq[4]; }tunFreq; typedef union { unsigned short int u16Atten; unsigned char u8Atten[2]; }tunAtten; typedef struct { unsigned char u8Updateflag; //BYTE 0 unsigned char u8CtrlStatus; //BYTE 1 0x1(bit0) = Lock status, 0x2(bit1) = ALC, 0x4(bit2) = Mute tunFreq unRfFreq; //BYTE 2-5 consider union here tunAtten unAtten; //BYTE 6-7 consider union here unsigned char u8WtPower; //BYTE 8 Write outputpower to modules unsigned char u8RdPower; //BYTE 9 Read outputpower from modules }tstI2CMessage; /******************************************************************************************************************** byte 0: bit0: write flag 1 by master, cleared by software bit1: AGC_OFFON off=1, on=0, write by master bit2: lock status bit3: Rx_enbl, enable=1, disable=0; byte 1,2,3,4: 4 bytes for RF frequency in kHz byte 5,6: when AGC_OFFON=1(off),2bytes for user setable attenuation dB X 10, 0-250 when AGC_OFFON=0(on), output power setting in dBm X10 +500, when it was written as 0xFFFF, nothing will be changed. byte 7,8: output power detect, output_power dBm X10+500 byte 9: value=0-12 Gain compensation table address, 0=950MHz, 1=1050MHz, 2=1150MHz, 3=1250MHz, 4=1350MHz, 5=1450MHz, 6=1550MHz, 7=1650MHz, 8=1750MHz, 9=1850MHz, 10=1950MHz, 11=2050MHz, 12=2150MHz value=13-25 Power compensation table address, 13=950MHz, 14=1050MHz, 15=1150MHz, 16=1250MHz, 17=1350MHz, 18=1450MHz, 19=1550MHz, 20=1650MHz, 21=1750MHz, 22=1850MHz, 23=1950MHz, 24=2050MHz, 25=2150MHz value=26-56 output power detection table address, from -15dBm to +15dBm 26=-15dBm, 27=-14dBm, 28=-13dBm, 29=-12dBm, 30=-11dBm, 31=-10dBm, 32=-9dBm, 33=-8dBm, 34=-7dBm, 35=-6dBm, 36=-5dBm, 37=-4dBm, 38=-3dBm, 39=-2dBm, 40=-1dBm, 41=0dBm, 42=1dBm, 43=2dBm, 44=3dBm, 45=4dBm,46=5dBm, 47=6dBm, 48=7dBm, 49=8dBm, 50=9dBm, 51=10dBm, 52=11dBm, 53=12dBm, 54=13dBm, 55=14dBm, 56=15dBm, byte 10,11: Gain compensation dB X 10, range 0-65, Power compensation dB X10, range 0-65 Output power detection table if this is written as 0xfff by master, slave will read the compensation table and put into I2C_Array. **********************************************************************************************************************/ #define nI2C_WRITE 0x01 #define nI2C_READ 0xfe #define nAGC_OFF 0xFD//0x02 //u8CtrlStatus|nAGC_OFF set off //swapped back #define nAGC_ON 0x02//0xFD //u8CtrlStatus&nAGC_ON set on //swapped back #define nLOCK 0x04 #define nUNLOCK 0xFB #define nRX_ENABLE 0x08 //= mute on/off #define nRX_DISABLE 0xF7 typedef struct { //bit0: write flag 1 by master, cleared by software 0x01 ~0xFE //bit1: AGC_OFFON off=1, on=0, write by master 0x02 ~0xFD //bit2: lock status 0x04 ~0xFB //bit3: Rx_enbl, enable=1, disable=0; 0x08 ~0xF7 BYTE u8CtrlStatus; //BYTE 0 tunFreq unRfFreq; //BYTE 1-4 4 bytes for RF frequency in kHzs tunAtten unAtten; //BYTE 5-6 consider union here WORD u16RdPower; //BYTE 7-8 output power detect, output_power dBm X10+500 BYTE u8GainCompenAddr; //byte 9 Gain compensation table address WORD u16GainCompenVale; //byte 10-11 Gain compensation dB X 10, range 0-65, }tstI2CMsg; #define nBUC_REF_ON 0x02 #define nBUC_REF_OFF 0xFD #define nLNB_REF_ON 0x04 #define nLNB_REF_OFF 0xFB #define nBUC_DC_ON 0x08 #define nBUC_DC_OFF 0xF7 #define nLNB_DC_ON 0x10 #define nLNB_DC_OFF 0xEF #define nBUC_OVER_CURRENT 0x20 #define nLNB_OVER_CURRENT 0x40 #define nEXT_REF 0x80 /******************************************************************************************************************** byte 0: bit0: write flag 1 by master, cleared by software bit1: BUC_REF_ONOFF 1=on, 0=off bit2: LNB_REF_ONOFF 1=on, 0=off bit3: BUC_DC_ONOFF 1=on, 0=off bit4: LNB_DC_ONOFF 1=on, 0=off bit5: BUC DC over current 1=over current, 0=normal. When BUC over current, BUC_DC_ONOFF will be set to 0. This bit must be cleared before turn on the BUC DC again. bit6: LNB DC over current 1=over current, 0=normal. When LNB over current, LNB_DC_ONOFF will be set to 0. This bit must be cleared before turn on the LNB DC again. bit7: external reference detect 1=external reference 0=internal reference byte 1: bit0: LED1 bit1: LED2 bit2: LED3 bit3: LED4 byte 2,3: BUC current in mA, unsigned int byte 4,5: LNB current in mA, unsigned int byte 6,7: BUC current limit in mA, unsigned int byte 8,9: LNB current limit in mA, unsinged int **********************************************************************************************************************/ typedef struct { BYTE u8Status; //byte 0 BYTE u8LEDSetting; //byte 1 bit0-3,= LED1-4 WORD u16BUCCurrent; //byte 2-3BUC current in mA, unsigned int WORD u16LNBCurrent; //byte 4-5 LNB current in mA, unsigned int WORD u16BUCCurrentLimit; //BYTE 6-7 BUC current limit in mA, unsigned int WORD u16LNBCurrentLimit; //BYTE 8-9 LNB current limit in mA, unsigned int }tstI2CMsgVOL; typedef struct { unsigned char u8Updateflag; unsigned char u818VDC; //BYTE 0 unsigned char u824VDC; //BYTE 1 }tstI2CMessageVOL; extern tstI2CMessage stI2CUpCvtMsg; extern tstI2CMessage stI2CDownCvtMsg; extern tstI2CMessageVOL stI2CVOLMsg; extern tstI2CMsg stI2CUCMsg; extern tstI2CMsg stI2CDCMsg; extern tstI2CMsgVOL stI2CREFMsg; extern char IPString[]; extern unsigned char LastMenu; extern unsigned char CurrentMenu; extern APP_CONFIG AppConfig; extern unsigned char KeyPressedFlag, PressedKey, RefreshFlag; extern BYTE EditUpdateFlag;//Edit position char update only extern BYTE ValueUpdateFlag; //Content Value Update only extern const rom tstMenuDisplay stMenuDisplay[30]; void OLED_vSetKepad(void); void OLED_vSetIO(void); void OLED_vEnableInterrupt(void); void CheckBusy(); void WriteIns(char instruction); void WriteData(char data1); unsigned char ReadData(void); void WriteString(unsigned char count,unsigned char * MSG); void LCDWriteString(unsigned char * MSG); void PrintCGRAM(unsigned char number1); void LCDClear(void); void LCDReturnhome(void); void LCDEntryMode(void); void LCDDisplay(unsigned char displayflag, unsigned char cusorflag, unsigned char blinkflag); void Initial_LCD(void); void PrintLCD(void); void PrintBlinkLCD(void); void DisplayCompanyMenu(void); void InitalizeMenu(void); BYTE LCD__u8GetOnOff(void); BYTE LCD__u8UpdateToModule(BYTE* pu8Parameter,BYTE* pu8Data ,BYTE u8CompareFlag,BYTE* pu8SendData); BYTE LCD_u8UpdateDisplayContent(void); void KeyProcessing(void); void UpdateStatus(void); void Main_vLEDLO(BYTE Setting); void Main_vLEDTX(BYTE Setting); void Main_vLEDLO(BYTE Setting); //Set LED IO direction to output void Main_vLEDInit(void); #endif /* OLED_C1_H */ <file_sep>/Drivers/External-Peripherals/oled_c1.c #include "define.h" #include "i2c_c1.h" #include "oled_c1.h" rom unsigned char CGRAM[2][8] = {{0x04,0x0E,0x15,0x04,0x04,0x04,0x04,0x04}, {0x04,0x15,0x0E,0x04,0x04,0x04,0x04,0x04}}; void OLED_vSetKepad(void) { UPKEY_TRIS = 1; DOWNKEY_TRIS = 1; LEFTKEY_TRIS = 1; RIGHTKEY_TRIS = 1; ENTERKEY_TRIS = 1; CANCELKEY_TRIS = 1; CONVERTERA_STATUS_TRIS = 1; CONVERTERB_STATUS_TRIS = 1; } void OLED_vSetIO(void) { OLED_RS_TRIS = 0; OLED_RW_TRIS = 0; OLED_EN_TRIS = 0; OLED_DB7_TRIS = 0; OLED_DB6_TRIS = 0; OLED_DB5_TRIS = 0; OLED_DB4_TRIS = 0; OLED_DB3_TRIS = 0; OLED_DB2_TRIS = 0; OLED_DB1_TRIS = 0; OLED_DB0_TRIS = 0; } void OLED_vEnableInterrupt(void) { PIE1bits.TMR2IE = 0; // disable Timer2 interrupt PIR1bits.TMR2IF = 0; IPR1bits.TMR2IP = 0; // set Timer2 interrupt to low interrupt INTCON3bits.INT1IE = 1; // enable key interrupt INTCON3bits.INT1IP = 0; // set key interrupt to low interrupt INTCON2bits.INTEDG1 = 1; // 1 = Interrupt on rising edge // INTCON2bits.INTEDG1 = 0; // 0 = Interrupt on falling edge TRISBbits.TRISB1 = 1; // RB1 input, INT1 ADCON0bits.ADON = 0; ADCON1 |= 0x0F; // set all IO pin to digital } void CheckBusy() { unsigned char temp; OLED_BUS_W = 0xff; OLED_RS = 0; OLED_RW = 1; OLED_BUS_TRIS = 0xFF; do { OLED_EN = 1; Nop(); /* zj */ temp = OLED_DB7_R; OLED_EN = 0; }while(temp); OLED_BUS_TRIS = 0; } void WriteIns(char instruction) { CheckBusy(); OLED_RS = 0; OLED_RW = 0; OLED_EN = 1; Nop(); /* zj */ OLED_BUS_W = instruction; OLED_EN = 0; } void WriteData(char data1) { CheckBusy(); OLED_RS = 1; OLED_RW = 0; Nop(); /* zj */ OLED_EN = 1; Nop(); /* zj */ OLED_BUS_W = data1; OLED_EN = 0; Nop(); /* zj */ } unsigned char ReadData(void) { unsigned char temp; OLED_BUS_TRIS = 0xFF; OLED_RS = 1; OLED_RW = 1; OLED_EN = 1; Nop(); /* zj */ temp = OLED_BUS_R; OLED_EN = 0; OLED_BUS_TRIS = 0; CheckBusy(); return temp; } void WriteString(unsigned char count,unsigned char * MSG) { unsigned char i; for(i = 0; i < count; i++) { if ((MSG[i] >= ' ') && (MSG[i] <= 'z')) { WriteData(MSG[i]); } } } void LCDWriteString(unsigned char * MSG) { unsigned char temp; temp = *MSG; while (temp) { if ((temp >= ' ') && (temp <= 'z')) { WriteData(temp); } MSG++; temp = *MSG; } } void DRI_vPrintCGRAM(unsigned char number1) { unsigned char i; WriteIns(0x40); //SET CG_RAM ADDRESS 000000 for(i = 0;i<=24;i++) { WriteData(CGRAM[number1][i]); } } void DRI_vLCDClear(void) { WriteIns(0x01); //Clear Display } void DRI_vLCDReturnhome(void) { WriteIns(0x02); //Return Home } void DRI_vLCDEntryMode(void) { WriteIns(0x06); //Entry Mode Set, address increment & Shift off } void DRI_vLCDDisplay(unsigned char displayflag, unsigned char cusorflag, unsigned char blinkflag) { unsigned char temp = 0x08; if (displayflag == TRUE) { temp |= 0x04; // display ON } if (cusorflag == TRUE) { temp |= 0x02; // cusor ON } if (blinkflag == TRUE) { temp |= 0x01; // Blink ON } WriteIns(temp); //Display ON/OFF control,Display ON,Cursor&Blink OFF } void Initial_LCD(void) { CurrentMenu = MENU0; LastMenu = CurrentMenu; WriteIns(0x38); //function set,8-bit transfer,2-lines display & 5*8 dot characteristic, font 00 WriteIns(0x38); //function set,8-bit transfer,2-lines display & 5*8 dot characteristic, font 00 WriteIns(0x38); //function set,8-bit transfer,2-lines display & 5*8 dot characteristic, font 00 WriteIns(0x38); //function set,8-bit transfer,2-lines display & 5*8 dot characteristic, font 00 WriteIns(0x0C); //Display ON/OFF control,Display ON,Cursor&Blink OFF WriteIns(0x06); //Entry Mode Set, address increment & Shift off WriteIns(0x02); //Return Home WriteIns(0x01); //Clear Display } void PrintCompanyLCD(void) { unsigned char i, temp, temp1; for (i = 0; i < 40; i++) { temp = 0x80 + i; WriteIns(temp); temp = LCDPrintBuffer[0][i]; if ((temp >= ' ') && (temp <= 'z')) { WriteData(temp); } } for (i = 0; i < 40; i++) { temp = 0xC0 + i; WriteIns(temp); temp = LCDPrintBuffer[1][i]; if ((temp >= ' ') && (temp <= 'z')) { WriteData(temp); } } if (EditMode == TRUE) { // void DRI_vLCDDisplay(unsigned char displayflag, unsigned char cusorflag, unsigned char blinkflag) WriteIns(0xC0 + EditPosition); DRI_vLCDDisplay(TRUE, TRUE, FALSE); } } void PrintLCDWholePage(void) { unsigned char i, temp, temp1; /* First 3 pages have same menu, no need to re-print, but menu 0 is initial , need to print */ //if((LastMenu > 3) || (CurrentMenu > 3) || ((CurrentMenu==0) && (LastMenu==0))) { WriteIns(0x80); Nop(); for (i = 0; i < 40; i++) { temp = acLCDTitle[CurrentMenu][i]; if ((temp >= ' ') && (temp <= 'z')) { WriteData(temp); } } } WriteIns(0xC0); Nop(); for (i = 0; i < 40; i++) { //temp = 0xC0 + i; //WriteIns(temp); temp = LCDPrintBuffer[1][i]; if ((temp >= ' ') && (temp <= 'z')) { WriteData(temp); } } if (EditMode == TRUE) { // void DRI_vLCDDisplay(unsigned char displayflag, unsigned char cusorflag, unsigned char blinkflag) WriteIns(0xC0 + EditPosition); DRI_vLCDDisplay(TRUE, TRUE, FALSE); } } /* JuZh, Consider only print the blink text part if there is no Menu Index change, provieded the blink location and length */ void PrintBlinkMenuText(void) { unsigned char i, temp; static BYTE boBlink; BYTE u8BlinkPos; BYTE u8BlinkLen; u8BlinkPos = stMenuDisplay[CurrentMenu].u8BlinkPos; u8BlinkLen = stMenuDisplay[CurrentMenu].u8BlinkLen; boBlink = boBlink?0:1; WriteIns(0x80 + u8BlinkPos); for (i = 0; i < u8BlinkLen; i++) { temp = boBlink?' ':acLCDTitle[CurrentMenu][i + u8BlinkPos]; /* toggole between space and text */ if ((temp >= ' ') && (temp <= 'z')) { WriteData(temp); } } //DelayMS(1); if (EditMode == TRUE) { // void DRI_vLCDDisplay(unsigned char displayflag, unsigned char cusorflag, unsigned char blinkflag) WriteIns(0xC0 + EditPosition); DRI_vLCDDisplay(TRUE, TRUE, FALSE); } DelayMS(1); } /* consider only update the value text instead of whole line */ void PrintNewValue(void) { unsigned char i, temp, temp1; WriteIns(0xC0); for (i = 0; i < 40; i++) { temp = LCDPrintBuffer[1][i]; if ((temp >= ' ') && (temp <= 'z')) { WriteData(temp); } } if (EditMode == TRUE) { // void DRI_vLCDDisplay(unsigned char displayflag, unsigned char cusorflag, unsigned char blinkflag) WriteIns(0xC0 + EditPosition); DRI_vLCDDisplay(TRUE, TRUE, FALSE); } } void PrintEditPosition(void) { unsigned char i, temp; WriteIns(0xC0+EditPosition); if((LCDPrintBuffer[1][EditPosition] == 'E') || (LCDPrintBuffer[1][EditPosition] == 'D')) //Enabled Disabled { for (i = 0; i < 9; i++) /* Only re-print the cursor value or print "ON", "OFF", 2 bytes are enough */ { temp = LCDPrintBuffer[1][EditPosition + i]; if ((temp >= ' ') && (temp <= 'z')) { WriteData(temp); } } } else if(LCDPrintBuffer[1][EditPosition] != 'O') /* Not editing On/Off , set only 1 number*/ { temp = LCDPrintBuffer[1][EditPosition]; if ((temp >= ' ') && (temp <= 'z')) { WriteData(temp); } } else /* On/Off, set 2 bytes */ { for (i = 0; i < 3; i++) /* Only re-print the cursor value or print "ON", "OFF", 2 bytes are enough */ { temp = LCDPrintBuffer[1][EditPosition + i]; if ((temp >= ' ') && (temp <= 'z')) { WriteData(temp); } } } if (EditMode == TRUE) { // void DRI_vLCDDisplay(unsigned char displayflag, unsigned char cusorflag, unsigned char blinkflag) WriteIns(0xC0 + EditPosition); DRI_vLCDDisplay(TRUE, TRUE, FALSE); } } /* Not used any more */ void PrintBlinkLCD(void) { unsigned char i, temp; WriteIns(0x80); for (i = 0; i < 40; i++) { temp = acLCDBlinkTitle[CurrentMenu][i];; if ((temp >= ' ') && (temp <= 'z')) { WriteData(temp); } } WriteIns(0xC0); for (i = 0; i < 40; i++) { temp = LCDPrintBuffer[1][i]; if ((temp >= ' ') && (temp <= 'z')) { WriteData(temp); } } if (EditMode == TRUE) { // void DRI_vLCDDisplay(unsigned char displayflag, unsigned char cusorflag, unsigned char blinkflag) WriteIns(0xC0 + EditPosition); DRI_vLCDDisplay(TRUE, TRUE, FALSE); } } <file_sep>/Devices/UpConverter_c1.c #include "define.h" #include "Global.h" #include "oled_c1.h" #include "string.h" #include "Util.h" void UpCvt_vPrintFreq(void) { strncpy(LCDPrintBuffer[1], RFFreqString1,sizeof(RFFreqString1)); } void UpCvt_vPrintPower(void) { strncpy(LCDPrintBuffer[1], sUCPower,sizeof(sUCPower)); } void UpCvt_vPrintStPwr(void) { strncpy(LCDPrintBuffer[1], sUPC_StPwr,sizeof(sUPC_StPwr)); } void UpCvt_vPrintLo(void) { if (stConverter.stUp.u8AlarmStatus == 1) { strncpy(LCDPrintBuffer[1], LOStatusString1,sizeof(LOStatusString1)); } else { strncpy(LCDPrintBuffer[1], LOStatusString2,sizeof(LOStatusString2)); } } void UpCvt_vPrintAttn(void) { strncpy(LCDPrintBuffer[1], AttenString1,sizeof(AttenString1)); } void UpCvt_vPrintALC(void) { strncpy(LCDPrintBuffer[1], sALCa,sizeof(sALCa)); } void UpCvt_vPrintMute(void) { if(stConverter.stUp.u8Mute==1) strncpypgm2ram(sMutea,"ENABLED ",8); else strncpypgm2ram(sMutea,"DISABLED",8); strncpy(LCDPrintBuffer[1], sMutea,sizeof(sMutea)); } void UpCvt_vSendI2C() { stI2CUCMsg.u16GainCompenVale = 0xFFFF; /* Don't write tables */ SetI2C(MODULE0); } void UpCvt_vSetFreq(void) { DWORD tempDWORD = 0; float fFreq = 0; // update LCD value to Freq/Atten/IP, TBD, update wrt power, ALC, Mute if (CurrentMenu == nFREQ_MENU_A) // UC1 Freq { fFreq = Util_u8String2NFloat((char*)&LCDPrintBuffer[1][0]); tempDWORD = (DWORD)(fFreq * 1000.0f);// should deduct 950 000? 950M ~ 2150M tempDWORD = nLO_FREQ - tempDWORD; if ((tempDWORD != stConverter.stUp.u32OutputFreq) && (tempDWORD <= MAXRFFREQ) && (tempDWORD >= MINRFFREQ)) { //stConverter.stUp.u32OutputFreq = tempDWORD; stI2CUCMsg.unRfFreq.u32Freq = Util_u16DWORDSwap(tempDWORD); strncpy(RFFreqString1 ,LCDPrintBuffer[1], sizeof(RFFreqString1) ); UpCvt_vSendI2C(); } } } void UpCvt_vSetAttn(void) { WORD tempWORD = 0; if ((stConverter.stUp.u8ALC != STATUS_OFF)) return; tempWORD = LCDPrintBuffer[1][0] - '0'; tempWORD = ((WORD)(tempWORD * 10)) + ((WORD)LCDPrintBuffer[1][1] - '0'); tempWORD = ((WORD)(tempWORD * 10)) + ((DWORD)LCDPrintBuffer[1][3] - '0'); /* tempWORD is atten * 10 */ if ((tempWORD != stConverter.stUp.u16Atten) && (tempWORD <= MAXATTEN)&&(tempWORD >= MINATTEN)) { //stConverter.stUp.u16Atten = tempWORD; stI2CUCMsg.unAtten.u16Atten= Util_u16ByteSwap(tempWORD); memcpy(AttenString1 ,LCDPrintBuffer[1], sizeof(AttenString1) ); UpCvt_vSendI2C(); } } void UpCvt_vSetPower(void) { /*Disabled and moved to UpCvt_vSetStPwr */ } void UpCvt_vSetStPwr(void) { BYTE u8TempByte =0; float fTemp; SHORT i16Temp; WORD u16Temp; if ((stConverter.stUp.u8ALC != STATUS_ON)) return; fTemp = Util_u8String2Float(LCDPrintBuffer[1]); u16Temp = (WORD)(fTemp *10 + 500); if ((u16Temp!= stConverter.stUp.u16SetPwr) && (u16Temp <= MAXPOWER) && (u16Temp >= MINPOWER)) { stConverter.stUp.u16SetPwr = u16Temp; stConverter.stUp.fSetPwr= fTemp; //shared 16bits of att and wtpwr stI2CUCMsg.unAtten.u16Atten = Util_u16ByteSwap(u16Temp); memcpy(sUPC_StPwr,LCDPrintBuffer[1], sizeof(sUPC_StPwr) ); UpCvt_vSendI2C(); } } void UpCvt_vSetALC(void) { BYTE u8TempByte =0; u8TempByte = LCD__u8GetOnOff(); strncpy(sALCa,LCDPrintBuffer[1], sizeof(sALCa) ); if(u8TempByte==0) { stConverter.stUp.u8ALC = OFF; stI2CUCMsg.u8CtrlStatus &= nAGC_OFF;//0xFD,swapped back } else if(u8TempByte==1) { stConverter.stUp.u8ALC = ON; stI2CUCMsg.u8CtrlStatus |= nAGC_ON;//0x02, swapped back } UpCvt_vSendI2C(); } void UpCvt_vSetMute() { BYTE u8TempByte =0; if(!memcmppgm2ram(LCDPrintBuffer[1],"ENABLED",7)) u8TempByte = 1; else if (!memcmppgm2ram(LCDPrintBuffer[1],"DISABLED",8)) u8TempByte = 0; if(u8TempByte==0) { stConverter.stUp.u8Mute = 0; strncpy(sMutea,LCDPrintBuffer[1], sizeof(sMutea) ); stI2CUCMsg.u8CtrlStatus &= nRX_DISABLE ; UpCvt_vSendI2C(); Main_vLEDTX(u8TempByte); } else if(u8TempByte==1) { stConverter.stUp.u8Mute = 1; strncpy(sMutea,LCDPrintBuffer[1], sizeof(sMutea) ); stI2CUCMsg.u8CtrlStatus |= nRX_ENABLE; UpCvt_vSendI2C(); Main_vLEDTX(u8TempByte); } } <file_sep>/Drivers/External-Peripherals/oled_c2.h #ifndef OLED_C2_H #define OLED_C2_H void LCDSub_vLeftMoveCursorFreq(void); void LCDSub_vLeftMoveCursorPower(void); void LCDSub_vLeftMoveCursorAttn(void); void LCDSub_vLeftMoveCursorIP(void); void LCDSub_vRightMoveCursorFreq(void); void LCDSub_vRightMoveCursorPower(void); void LCDSub_vRightMoveCursorAttn(void); void LCDSub_vRightMoveCursorIP(void); #endif /* OLED_C2_H */ <file_sep>/Drivers/External-Peripherals/oled_c2.c #include "define.h" #include "Global.h" #include <string.h> #include "DeviceApi.h" #include "i2c_c1.h" #include "Util.h" #include "oled_c1.h" #include "oled_c2.h" unsigned char LCDBufferPosition[2]; char LOStatusString1[9] = {"LOCKED "}; char LOStatusString2[9] = {"UNLOCKED"}; /*JuZh 950.000MHz to 2150.000MHz */ char RFFreqString1[12] = {"3625.000MHz"}; /* must update to 3 digits decimal */ char RFFreqString2[12] = {"3625.000MHz"}; /* must update to 3 digits decimal */ char AttenString1[8] = {"00.0 dB"}; char AttenString2[8] = {"00.0 dB"}; char IPString[16] = {"192.168.001.001"}; char MNString[18] = {"SCMDC62001SN10-RM"}; char SNString[9] = {"12345678"}; char s18VDC[4] = {"OFF"}; char s24VDC[4] = {"OFF"}; char sLNBREF[4] = {"OFF"}; char sBUCREF[4] = {"OFF"}; char sUCPower[10] = {"-30.0 dBm"}; char sDCPower[10] = {"-30.0 dBm"}; char sUPC_StPwr[10] = {"-00.0 dBm"}; char sDNC_StPwr[10] = {"-00.0 dBm"}; char sALCa[4]= {"OFF"}; char sALCb[4] = {"OFF"}; char sMutea[9] = {"DISABLED"}; char sMuteb[9] = {"DISABLED"}; unsigned char LastMenu = MENU0; unsigned char CurrentMenu = MENU0; /* LCD_u8UpdateDisplayContent is called if RefreshFlag is set to TRUE, it is set to TRUE if there is sys value update or if there is Menu page change. RefreshFlag is set to false after LCD_u8UpdateDisplayContent and PrintLCD */ unsigned char KeyPressedFlag = FALSE, PressedKey = NULL; BYTE RefreshFlag = FALSE; //Page change, update whole Menu BYTE EditUpdateFlag = FALSE;//Edit position char update only BYTE ValueUpdateFlag = FALSE; //Content Value Update only unsigned char EditMode = FALSE, EditPosition = 0, FirstPressKey = TRUE; tstI2CMessage stI2CUpCvtMsg; tstI2CMessage stI2CDownCvtMsg; tstI2CMessageVOL stI2CVOLMsg; tstI2CMsg stI2CUCMsg; tstI2CMsg stI2CDCMsg; tstI2CMsgVOL stI2CREFMsg; tstI2CMsg stI2CLOMsg; BYTE u8ExtLO = 0; char readflag = 0x00; #pragma udata gpr8 char LCDPrintBuffer[2][nLCDLEN]; #pragma udata grp10 char LCDBlinkBuffer[2][nLCDLEN]; typedef struct menustructure { unsigned char editable; } menustructure_t; #define MaxMenuNum 28 menustructure_t ConvertMenu[MaxMenuNum]; typedef struct{ void (*pvfPrintMenu)(void); void (*pvfSetValue)(void); void (*pvfMoveCursorLeft)(void); void (*pvfMoveCursorRight)(void); BYTE u8RightMenu; BYTE u8LeftMenu; BYTE u8UpMenu; BYTE u8DownMenu; BYTE u8BlinkPos; /* Start position for blinking text */ BYTE u8BlinkLen; /* Length for blinking text */ }tstMenuDisplay; const rom tstMenuDisplay stMenuDisplay[30]= { {&Main_vPrintUpConverter,NULL,NULL,NULL, MENU2,MENU3, MENU0,MENU4,0,16}, //zj changed 0 -3, blink len 7 to 14 {&Main_vPrintDownConverter,NULL,NULL,NULL, MENU2,MENU0, MENU1,MENU11,8,7},//skip {&Main_vPrintVolCtrl,NULL,NULL,NULL, MENU3,MENU0, MENU2,MENU2,16,10},//zj changed to be fixed page {&Main_vPrintDeviceInfo,NULL,NULL,NULL, MENU0,MENU2, MENU3,MENU27,26,13},//zj changed 0 -3 {&UpCvt_vPrintFreq, &UpCvt_vSetFreq,&LCDSub_vLeftMoveCursorFreq,&LCDSub_vRightMoveCursorFreq, MENU5,MENU10, MENU0,MENU4,3,9}, {&UpCvt_vPrintPower, &UpCvt_vSetPower,&LCDSub_vLeftMoveCursorPower,&LCDSub_vRightMoveCursorPower, MENU6,MENU4, MENU0,MENU5,3,7}, {&UpCvt_vPrintStPwr, &UpCvt_vSetStPwr,&LCDSub_vLeftMoveCursorPower,&LCDSub_vRightMoveCursorPower, MENU7,MENU5, MENU0,MENU6,3,9}, {&UpCvt_vPrintLo, NULL,NULL,NULL, MENU8,MENU6, MENU0,MENU7,3,11}, {&UpCvt_vPrintAttn, &UpCvt_vSetAttn,&LCDSub_vLeftMoveCursorAttn,&LCDSub_vRightMoveCursorAttn, MENU9,MENU7, MENU0,MENU8,3,6 }, {&UpCvt_vPrintALC, &UpCvt_vSetALC,NULL,NULL, MENU10,MENU8, MENU0,MENU9,3,5}, {&UpCvt_vPrintMute, &UpCvt_vSetMute,NULL,NULL, MENU4,MENU9, MENU0,MENU10,3,9}, {&DownCvt_vPrintFreq, &DownCvt_vSetFreq,&LCDSub_vLeftMoveCursorFreq,&LCDSub_vRightMoveCursorFreq, MENU12,MENU17, MENU1,MENU11,3,9}, {&DownCvt_vPrintPower, &DownCvt_vSetPower,&LCDSub_vLeftMoveCursorPower,&LCDSub_vRightMoveCursorPower,MENU13,MENU11, MENU1,MENU12,3,7}, {&DownCvt_vPrintStPwr, &DownCvt_vSetStPwr,&LCDSub_vLeftMoveCursorPower,&LCDSub_vRightMoveCursorPower,MENU14,MENU12, MENU0,MENU13,3,9}, {&DownCvt_vPrintLo, NULL,NULL,NULL, MENU15,MENU13, MENU1,MENU14,3,11}, {&DownCvt_vPrintAttn, &DownCvt_vSetAttn,&LCDSub_vLeftMoveCursorAttn,&LCDSub_vRightMoveCursorAttn, MENU16,MENU14, MENU1,MENU15,3,6}, {&DownCvt_vPrintALC, &DownCvt_vSetALC,NULL,NULL, MENU17,MENU15, MENU1,MENU16,3,5}, {&DownCvt_vPrintMute, &DownCvt_vSetMute,NULL,NULL, MENU11,MENU16, MENU1,MENU17,3,9}, {&VOLCTRL_vPrint18V, &VOLCTRL_vSet18V,NULL,NULL, MENU19,MENU26, MENU2,MENU18,5,8}, {&VOLCTRL_vPrint24V, &VOLCTRL_vSet24V,NULL,NULL, MENU20,MENU18, MENU2,MENU19,5,8}, {&VOLCTRL_vPrintLNBREF, &VOLCTRL_vSetLNBREF,NULL,NULL, MENU21,MENU19, MENU2,MENU20,5,9}, {&VOLCTRL_vPrintBUCREF, &VOLCTRL_vSetBUCREF,NULL,NULL, MENU22,MENU20, MENU2,MENU21,5,9}, {&VOLCTRL_vPrintEXTREF, NULL,NULL,NULL, MENU23,MENU21, MENU2,MENU22,5,9}, {&VOLCTRL_vPrintBUCI, NULL,NULL,NULL, MENU24,MENU22, MENU2,MENU23,5,13}, {&VOLCTRL_vPrintLNBI, NULL,NULL,NULL, MENU25,MENU23, MENU2,MENU24,5,13}, {&VOLCTRL_vPrintBUCAlm, &VOLCTRL_vClearBUCAlm,NULL,NULL, MENU26,MENU24, MENU2,MENU25,5,17}, {&VOLCTRL_vPrintLNBAlm, &VOLCTRL_vClearLNBAlm,NULL,NULL, MENU18,MENU25, MENU2,MENU26,5,17}, {&Main_vPrintIP,&Main_vSetIP,&LCDSub_vLeftMoveCursorIP,&LCDSub_vRightMoveCursorIP, MENU28,MENU29, MENU3,MENU27,5,4}, {&Main_vPrintModelNo,NULL,NULL,NULL, MENU29,MENU27, MENU3,MENU28,10,15}, {&Main_vPrintSerialNo,NULL,NULL,NULL, MENU27,MENU28, MENU3,MENU29,26,14} }; const rom char acLCDTitle[30][nLCDLEN]={ //1234567890123456789012345678901234567890// //0123456789012345678901234567890123456789// "[DOWN CONVERTER][MAINCTRL][DEVICE INFO] ", "[DOWN CONVERTER][MAINCTRL][DEVICE INFO] ", "[DOWN CONVERTER][MAINCTRL][DEVICE INFO] ", "[DOWN CONVERTER][MAINCTRL][DEVICE INFO] ", "DC [RF FREQ] [POWER] [SET PWR] [LO STATU", "DC [POWER] [SET PWR] [LO STATUS] [ATTN] ", "DC [SET PWR] [LO STATUS] [ATTN] [ALC] [R", "DC [LO STATUS] [ATTN] [ALC] [RF ENBL] [R", "DC [ATTN] [ALC] [RF ENBL] [RF FREQ] [POW", "DC [ALC] [RF ENBL] [RF FREQ] [POWER] [SE", "DC [RF ENBL] [RF FREQ] [POWER] [SET PWR]", "DC [RF FREQ] [POWER] [SET PWR] [LO STATU", "DC [POWER] [SET PWR] [LO STATUS] [ATTN] ", "DC [SET PWR] [LO STATUS] [ATTN] [ALC] [R", "DC [LO STATUS] [ATTN] [ALC] [RF ENBL] [R", "DC [ATTN] [ALC] [RF ENBL] [RF FREQ] [POW", "DC [ALC] [RF ENBL] [RF FREQ] [POWER] [SE", "DC [RF ENBL] [RF FREQ] [POWER] [SET PWR]", "CTRL [LNB DC] [BUC DC] [LNB REF] [BUC RE", "CTRL [BUC DC] [LNB REF] [BUC REF] REF ", "CTRL [LNB REF] [BUC REF] [ REF ] [BUC ", "CTRL [BUC REF] [ REF ] [BUC CURRENT] [", "CTRL [ REF ] [BUC CURRENT] [LNB CURREN", "CTRL [BUC CURRENT] [LNB CURRENT] [BUC OV", "CTRL [LNB CURRENT] [BUC OVERCURRENT] [LN", "CTRL [BUC OVERCURRENT] [LNB OVERCURRENT]", "CTRL [LNB OVERCURRENT] [LNB DC] [BUC DC]", "INFO [IP] [MODULE NUMBER] [SERIAL NUMBER", "INFO [IP] [MODULE NUMBER] [SERIAL NUMBER", "INFO [IP] [MODULE NUMBER] [SERIAL NUMBER" }; /* Page 0-3 same title */ const rom char acLCDBlinkTitle[23][nLCDLEN]={ " [DNCVT] [DC VOL] [DEVICE INFO] ", "[UPCVT] [DC VOL] [DEVICE INFO] ", "[UPCVT] [DNCVT] [DEVICE INFO] ", "[UPCVT] [DNCVT] [DC VOL] ", "UC [POWER] [LO STATUS] [ATTN]", "UC [LO STATUS] [ATTN] [ALC] [MU", "UC [ATTN] [ALC] [MUTE] [RF ", "UC [ALC] [MUTE] [RF FREQ] [POWER", "UC [MUTE] [RF FREQ] [POWER] [LO S", "UC [RF FREQ] [POWER] [LO STATUS]", "DC [POWER] [LO STATUS] [ATTN]", "DC [LO STATUS] [ATTN] [ALC] [MU", "DC [ATTN] [ALC] [MUTE] [RF ", "DC [ALC] [MUTE] [RF FREQ] [POWER", "DC [MUTE] [RF FREQ] [POWER] [LO S", "DC [RF FREQ] [POWER] [LO STATUS]", "VOL [BUC DC][LNB REF] [BUC REF]", "VOL [LNB DC] [LNB REF] [BUC REF]", "VOL [LNB DC] [BUC DC] [BUC REF]", "VOL [LNB DC] [BUC DC][LNB REF] ", "INFO [MODULE NUMBER] [SERIAL NUMBER", "INFO [IP] [SERIAL NUMBER", "INFO [IP] [MODULE NUMBER] " }; /* Page 0-3 same title */ static BYTE SYS__u8UpdateUpConverter(); static BYTE SYS__u8UpdateDownConverter(); static BYTE SYS__u8UpdateVOL(); void DisplayCompanyMenu(void) { strcpypgm2ram (LCDPrintBuffer[0], " SINGCOM "); strcpypgm2ram (LCDPrintBuffer[1], " FREQUENCY CONVERTER "); PrintCompanyLCD(); } void InitalizeMenu(void) { unsigned char i; for (i = 0; i < 40; i++) { //LCDPrintBuffer[0][i] = ' '; LCDPrintBuffer[1][i] = ' '; } CurrentMenu = MENU0; IPString[0] = ((AppConfig.MyIPAddr.v[0] / 100) % 10) + '0'; IPString[1] = ((AppConfig.MyIPAddr.v[0] / 10) % 10) + '0'; IPString[2] = ((AppConfig.MyIPAddr.v[0] / 1) % 10) + '0'; IPString[4] = ((AppConfig.MyIPAddr.v[1] / 100) % 10) + '0'; IPString[5] = ((AppConfig.MyIPAddr.v[1] / 10) % 10) + '0'; IPString[6] = ((AppConfig.MyIPAddr.v[1] / 1) % 10) + '0'; IPString[8] = ((AppConfig.MyIPAddr.v[2] / 100) % 10) + '0'; IPString[9] = ((AppConfig.MyIPAddr.v[2] / 10) % 10) + '0'; IPString[10] = ((AppConfig.MyIPAddr.v[2] / 1) % 10) + '0'; IPString[12] = ((AppConfig.MyIPAddr.v[3] / 100) % 10) + '0'; IPString[13] = ((AppConfig.MyIPAddr.v[3] / 10) % 10) + '0'; IPString[14] = ((AppConfig.MyIPAddr.v[3] / 1) % 10) + '0'; // Level 0 Menu 0/1/2/3: UC1/DC2/DCVOL/INFO // UC1 Menu 4/5/6/7/8/9: Output Freq(Editable)/Output Power(E)/LO Status/Atten(E)/ALC(E)/Mute(E) // DC2 Menu 10/11/12/13/14/15: Input Freq(Editable)/Output Power(E)/LO Status/Atten(E)/ALC(E)/Mute(E) // DCVOL Menu 16/17: 18V DC(E) / 24V DC(E) // INFO Menu 18/19/20: IP(Editable)/MN/SN // Level 0 ConvertMenu[0].editable = FALSE; ConvertMenu[1].editable = FALSE; ConvertMenu[2].editable = FALSE; ConvertMenu[3].editable = FALSE; // UC1 ConvertMenu[4].editable = TRUE; ConvertMenu[5].editable = FALSE; ConvertMenu[6].editable = TRUE; ConvertMenu[7].editable = FALSE; ConvertMenu[8].editable = TRUE; ConvertMenu[9].editable = TRUE; ConvertMenu[10].editable = TRUE; // DC2 ConvertMenu[11].editable = TRUE; ConvertMenu[12].editable = FALSE; ConvertMenu[13].editable = TRUE; ConvertMenu[14].editable = FALSE; ConvertMenu[15].editable = TRUE; ConvertMenu[16].editable = TRUE; ConvertMenu[17].editable = TRUE; // DCVOL ConvertMenu[18].editable = TRUE; ConvertMenu[19].editable = TRUE; ConvertMenu[20].editable = TRUE; ConvertMenu[21].editable = TRUE; ConvertMenu[22].editable = FALSE; ConvertMenu[23].editable = FALSE; ConvertMenu[24].editable = FALSE; ConvertMenu[25].editable = TRUE; ConvertMenu[26].editable = TRUE; // INFO ConvertMenu[27].editable = TRUE; ConvertMenu[28].editable = FALSE; ConvertMenu[29].editable = FALSE; } BYTE LCD__u8GetOnOff(void) { if('N' == LCDPrintBuffer[1][1]) return 1; else if('F' == LCDPrintBuffer[1][1]) return 0; } BYTE LCD__u8UpdateToModule(BYTE* pu8Parameter,BYTE* pu8Data ,BYTE u8CompareFlag,BYTE* pu8SendData) { if ((*pu8Data!= *pu8Parameter)) { *pu8Parameter= *pu8Data; if(nBYTE_COMPARE == u8CompareFlag) { *pu8SendData = *pu8Data; } else { if(STATUS_ON == *pu8Data) *pu8SendData |= u8CompareFlag; else *pu8SendData &= (~u8CompareFlag); } return TRUE; } else { return FALSE; } } /**************New Menu ******************/ // Level 0 Menu 0/1/2/3: UC1/DC2/DCVOL/INFO // UC1 Menu 4/5/6/7/8/9: Output Freq(Editable)/Output Power(E)/LO Status/Atten(E)/ALC(E)/Mute(E) // DC2 Menu 10/11/12/13/14/15: Input Freq(Editable)/Output Power(E)/LO Status/Atten(E)/ALC(E)/Mute(E) // DCVOL Menu 16/17: 18V DC(E) / 24V DC(E) // INFO Menu 18/19/20: IP(Editable)/MN/SN BYTE LCD_u8UpdateDisplayContent(void) { unsigned char i; memset(LCDPrintBuffer[1],' ', nLCDLEN); stMenuDisplay[CurrentMenu].pvfPrintMenu(); } static BYTE LCD__u8ToParentMenu() { CurrentMenu = stMenuDisplay[CurrentMenu].u8UpMenu; } /* In main menus, Enter 1st child menus */ static BYTE LCD__u8ToChildMenu() { CurrentMenu = stMenuDisplay[CurrentMenu].u8DownMenu; } BYTE LCD__u8UpkeyEdit() { // update LCD display zj: must consider on off settings too if ((LCDPrintBuffer[1][EditPosition] >= '0') && (LCDPrintBuffer[1][EditPosition] < '9')) { LCDPrintBuffer[1][EditPosition]++; } else if (LCDPrintBuffer[1][EditPosition] == '9') { LCDPrintBuffer[1][EditPosition] = '0'; } #if 1 else if (LCDPrintBuffer[1][EditPosition] == '-') { LCDPrintBuffer[1][EditPosition] = '+'; } else if (LCDPrintBuffer[1][EditPosition] == '+') { LCDPrintBuffer[1][EditPosition] = '-'; } #endif if(!memcmppgm2ram(LCDPrintBuffer[1],"ON ",3)) { memcpypgm2ram(LCDPrintBuffer[1],"OFF",3); } else if(!memcmppgm2ram(LCDPrintBuffer[1],"OFF",3)) { memcpypgm2ram(LCDPrintBuffer[1],"ON ",3); } if(!memcmppgm2ram(LCDPrintBuffer[1],"Alarm",5)) { memcpypgm2ram(LCDPrintBuffer[1],"OK ",5); } if(!memcmppgm2ram(LCDPrintBuffer[1],"ENABLED ",8)) { memcpypgm2ram(LCDPrintBuffer[1],"DISABLED",8); } else if(!memcmppgm2ram(LCDPrintBuffer[1],"DISABLED",8)) { memcpypgm2ram(LCDPrintBuffer[1],"ENABLED ",8); } EditUpdateFlag = TRUE; /* Blink is required here to display the updated value */ /* No additional Menu Content updated is required */ /* RefreshFlag is already set to true, when entering Edit mode */ } static BYTE LCD__u8UpkeyToParentMenu() { LCD__u8ToParentMenu(); /* Refresh flag not required to be set here, since there is menu change, SYS__vLcdKeyPadTask will refresh */ } static BYTE LCD__u8UpKeyProcess() { if (EditMode == TRUE) { LCD__u8UpkeyEdit(); } else /* Go into parent menu */ { LCD__u8UpkeyToParentMenu(); } } static BYTE LCD__u8DownKeyEdit() { // update LCD display zj: must consider on off settings too if ((LCDPrintBuffer[1][EditPosition] > '0') && (LCDPrintBuffer[1][EditPosition] <= '9')) { LCDPrintBuffer[1][EditPosition]--; } else if (LCDPrintBuffer[1][EditPosition] == '0') { LCDPrintBuffer[1][EditPosition] = '9'; } #if 1 else if (LCDPrintBuffer[1][EditPosition] == '-') { LCDPrintBuffer[1][EditPosition] = '+'; } else if (LCDPrintBuffer[1][EditPosition] == '+') { LCDPrintBuffer[1][EditPosition] = '-'; } #endif if(!memcmppgm2ram(LCDPrintBuffer[1],"ON ",3)) { memcpypgm2ram(LCDPrintBuffer[1],"OFF",3); } else if(!memcmppgm2ram(LCDPrintBuffer[1],"OFF",3)) { memcpypgm2ram(LCDPrintBuffer[1],"ON ",3); } if(!memcmppgm2ram(LCDPrintBuffer[1],"Alarm",5)) { memcpypgm2ram(LCDPrintBuffer[1],"OK ",5); } if(!memcmppgm2ram(LCDPrintBuffer[1],"ENABLED ",8)) { memcpypgm2ram(LCDPrintBuffer[1],"DISABLED",8); } else if(!memcmppgm2ram(LCDPrintBuffer[1],"DISABLED",8)) { memcpypgm2ram(LCDPrintBuffer[1],"ENABLED ",8); } EditUpdateFlag = TRUE; /* Blink is required here to display the updated value */ /* No additional Menu Content updated is required */ /* RefreshFlag is already set to true, when entering Edit mode */ } static BYTE LCD__u8DownkeyToChildMenu() { LCD__u8ToChildMenu(); /* Refresh flag not required to be set here, since there is menu change, SYS__vLcdKeyPadTask will refresh */ } static BYTE LCD__u8DownKeyProcess() { if (EditMode == TRUE) { LCD__u8DownKeyEdit(); } else /* Go into child menu */ { LCD__u8DownkeyToChildMenu(); } } void LCDSub_vLeftMoveCursorFreq() { if (EditPosition == 0) { EditPosition = 7; } else if (EditPosition == 5) //skip '.' { EditPosition = 3; } else { EditPosition--; } } void LCDSub_vLeftMoveCursorAttn() { if (EditPosition == 0) { EditPosition = 3; } else if (EditPosition == 3)//skip '.' { EditPosition = 1; } else { EditPosition--; } } void LCDSub_vLeftMoveCursorPower(void) { if (EditPosition == 0) { EditPosition = 4; } else if (EditPosition == 4) { EditPosition =2; } else { EditPosition--; } } void LCDSub_vLeftMoveCursorIP(void) { if (EditPosition == 0) { EditPosition = 14; } if('.' == LCDPrintBuffer[1][EditPosition-1]) /* Skip '.' */ { EditPosition -= 2; } else { EditPosition--; } } static BYTE LCD__u8LeftKeyMoveCursor(void) { // update LCD display stMenuDisplay[CurrentMenu].pvfMoveCursorLeft(); // void DRI_vLCDDisplay(unsigned char displayflag, unsigned char cusorflag, unsigned char blinkflag) WriteIns(0xC0 + EditPosition); DRI_vLCDDisplay(TRUE, TRUE, FALSE); } static BYTE LCD__u8LeftKeyToLeftMenu(void) { CurrentMenu = stMenuDisplay[CurrentMenu].u8LeftMenu; /* Refresh flag not required to be set here, since there is menu change, SYS__vLcdKeyPadTask will refresh */ } static BYTE LCD__u8LeftKeyProcess(void) { if (EditMode == TRUE) /* Move cursor to left */ { LCD__u8LeftKeyMoveCursor(); } else /* Go to previous menu */ { LCD__u8LeftKeyToLeftMenu(); } } void LCDSub_vRightMoveCursorFreq(void) { if (EditPosition == 7) { EditPosition = 0; } else if (EditPosition == 3) //'.' { EditPosition = 5; } else { EditPosition++; } } void LCDSub_vRightMoveCursorAttn(void) { if (EditPosition == 3) { EditPosition = 0; } else if (EditPosition == 1)//skip '.' { EditPosition = 3; } else { EditPosition = 1; } } void LCDSub_vRightMoveCursorPower(void) { if (EditPosition == 2) { EditPosition = 4; } else if (EditPosition == 4) { EditPosition = 0; } else { EditPosition++; } } void LCDSub_vRightMoveCursorIP(void) { if (EditPosition == 14) { EditPosition = 0; } if('.' == LCDPrintBuffer[1][EditPosition+1]) /* Skip '.' */ { EditPosition += 2; } else { EditPosition++; } } static BYTE LCD__u8RightKeyMoveCursor() { // update LCD display stMenuDisplay[CurrentMenu].pvfMoveCursorRight(); // void DRI_vLCDDisplay(unsigned char displayflag, unsigned char cusorflag, unsigned char blinkflag) WriteIns(0xC0 + EditPosition); DRI_vLCDDisplay(TRUE, TRUE, FALSE); } static BYTE LCD__u8RightKeyToRightMenu() { CurrentMenu = stMenuDisplay[CurrentMenu].u8RightMenu; /* Refresh flag not required to be set here, since there is menu change, SYS__vLcdKeyPadTask will refresh */ } static BYTE LCD__u8RightKeyProcess() { if (EditMode == TRUE) /* Move cursor to right */ { LCD__u8RightKeyMoveCursor(); } else /* Go to next menu */ { LCD__u8RightKeyToRightMenu(); } } static BYTE LCD__u8EnterKeySetValue() { // update LCD value to Freq/Atten/IP, TBD, update wrt power, ALC, Mute stMenuDisplay[CurrentMenu].pvfSetValue(); DRI_vLCDDisplay(TRUE, FALSE, FALSE); EditMode = FALSE; EditPosition = 0; } /* In main menus, Enter 1st child menus */ static BYTE LCD__u8EnterKeyToChildMenu() { LCD__u8ToChildMenu(); /* Refresh flag not required to be set here, since there is menu change, SYS__vLcdKeyPadTask will refresh */ } static BYTE LCD__u8EnterKeyToEditMode() { EditMode = TRUE; EditPosition = 0; WriteIns(0xC0 + EditPosition); DRI_vLCDDisplay(TRUE, TRUE, FALSE); //RefreshFlag = TRUE; } static BYTE LCD__u8EnterKeyProcess() { /* 1. In Edit mode Set new values */ if (EditMode == TRUE) { LCD__u8EnterKeySetValue(); return 0; } /* 2. Not in Edit Mode */ #if 0 /* 2.1 In main menus, Enter 1st child menus */ /*JuZh: Not required feature */ if(CurrentMenu <= MENU3) { LCD__u8EnterKeyToChildMenu(); return 0; } #endif /* 2.2 In Child menus, go to edit mode */ if (ConvertMenu[CurrentMenu].editable == TRUE) { LCD__u8EnterKeyToEditMode(); return 0; } // RefreshFlag = TRUE; } static BYTE LCD__u8CancelKeyExitEditMode() { EditMode = FALSE; EditPosition = 0; DRI_vLCDDisplay(TRUE, FALSE, FALSE); } /* Consider merget this function with UpkeyToParentMenu */ static BYTE LCD__u8CancelKeyToParentMenu() { LCD__u8ToParentMenu(); /* Refresh flag not required to be set here, since there is menu change, SYS__vLcdKeyPadTask will refresh */ } static BYTE LCD__u8CancelKeyProcess() { /* 1. In Edit mode, Cancel Edit Mode */ if(TRUE == EditMode) { LCD__u8CancelKeyExitEditMode(); } #if 0 /* 2. Not in editor mode, in child menu, Exit from child menu, Enter parent menus */ /* JuZh: Diabled not required feature to save process time */ else { LCD__u8CancelKeyToParentMenu(); } #endif RefreshFlag = TRUE; } // Level 0 Menu 0/1/2/3: UC1/DC2/DCVOL/INFO // UC1 Menu 4/5/6/7/8/9: Output Freq(Editable)/Output Power(E)/LO Status/Atten(E)/ALC(E)/Mute(E) // DC2 Menu 10/11/12/13/14/15: Input Freq(Editable)/Output Power(E)/LO Status/Atten(E)/ALC(E)/Mute(E) // DCVOL Menu 16/17: 18V DC(E) / 24V DC(E) // INFO Menu 18/19/20: IP(Editable)/MN/SN void KeyProcessing(void) { switch (PressedKey) { case UPKEY: { LCD__u8UpKeyProcess(); } break; case DOWNKEY: { LCD__u8DownKeyProcess(); } break; case LEFTKEY: { LCD__u8LeftKeyProcess(); } break; case RIGHTKEY: { LCD__u8RightKeyProcess(); } break; case ENTERKEY: //zj tbd must update freq 0000.000 attn 00.0, ALC mute, Power { LCD__u8EnterKeyProcess(); } break; case CANCELKEY: { LCD__u8CancelKeyProcess(); } break; default : break; } } //tstI2CMsg stI2CUCMsg; //tstI2CMsg stI2CDCMsg; //tstI2CMsgVOL stI2CREFMsg; static BYTE SYS__u8UpdateUpConverter() { DWORD tempDWORD = 0; WORD tempWORD = 0; BYTE u8TempByte = 0; BOOL boReturn = FALSE; float fAtten; float fSetPwr; int i16frac; stI2CUCMsg.u8CtrlStatus &= nI2C_READ; I2C_Send(I2C_UPCVT_ADDR, (char*)&readflag, 1); //Notify Want to read I2C message by sending null boReturn = I2C_Read(I2C_UPCVT_ADDR, (char*)&stI2CUCMsg, sizeof(tstI2CMsg)); //Read I2C message if(!boReturn) return FALSE; if (((stI2CUCMsg.u8CtrlStatus & nLOCK )== 0) && (stConverter.stUp.u8AlarmStatus != 0)) { stConverter.stUp.u8AlarmStatus = 0; //0 = alm stConverter.stUp.u8Lock = 0; /* If we are not at this menu now, we don't have to refresh now */ if(((CurrentMenu == nLOSTATUS_MENU_A) || (CurrentMenu == MENU0)) && (TRUE != EditMode) ) /* if edit is on going, don't refresh the new read values */ { ValueUpdateFlag = TRUE; stMenuDisplay[CurrentMenu].pvfPrintMenu(); } Main_vLEDLO(OFF); Main_vLEDRX(OFF); } else if (((stI2CUCMsg.u8CtrlStatus & nLOCK)!= 0) && (stConverter.stUp.u8AlarmStatus == 0)) { stConverter.stUp.u8AlarmStatus = 1; stConverter.stUp.u8Lock = 1; /* If we are not at this menu, we don't have to refresh now */ if(((CurrentMenu == nLOSTATUS_MENU_A)|| (CurrentMenu == MENU0)) && (TRUE != EditMode) ) { ValueUpdateFlag = TRUE; stMenuDisplay[CurrentMenu].pvfPrintMenu(); } /* ZJ don't check down cvt anymore */ // if(stConverter.stDown.u8Lock == 1) //check the other cvt if(u8ExtLO == 1) Main_vLEDLO(ON); Main_vLEDRX(ON); } u8TempByte = (stI2CUCMsg.u8CtrlStatus & nAGC_ON)?1:0; //if(u8TempByte != stConverter.stUp.u8ALC) { stConverter.stUp.u8ALC= u8TempByte; if(STATUS_OFF == stConverter.stUp.u8ALC) { strcpypgm2ram(sALCa,"OFF"); } else { strcpypgm2ram(sALCa,"ON "); } /* If we are not at this menu now, we don't have to refresh now */ if((CurrentMenu == nALC_MENU_A)&& (TRUE != EditMode)) { ValueUpdateFlag = TRUE; stMenuDisplay[nALC_MENU_A].pvfPrintMenu(); } } u8TempByte = (stI2CUCMsg.u8CtrlStatus & nRX_ENABLE)?1:0; //0 = disabled, 1 = enabled //if(u8TempByte != stConverter.stUp.u8Mute) { stConverter.stUp.u8Mute= u8TempByte; if(STATUS_OFF == stConverter.stUp.u8Mute) { strcpypgm2ram(sMutea,"DISABLED "); Main_vLEDTX(OFF); } else { strcpypgm2ram(sMutea,"ENABLED "); Main_vLEDTX(ON); } if((CurrentMenu == nMUTE_MENU_A)&& (TRUE != EditMode)) { ValueUpdateFlag = TRUE; stMenuDisplay[nMUTE_MENU_A].pvfPrintMenu(); } } tempDWORD = Util_u16DWORDSwap(stI2CUCMsg.unRfFreq.u32Freq); if((tempDWORD != stConverter.stUp.u32OutputFreq)&&(tempDWORD <=MAXRFFREQ)&&(tempDWORD>=MINRFFREQ)) { stConverter.stUp.u32OutputFreq = tempDWORD; sprintf(RFFreqString1,"%04ld.%03ldMHz",(nLO_FREQ - stConverter.stUp.u32OutputFreq)/1000,(nLO_FREQ - stConverter.stUp.u32OutputFreq)%1000 ); if(((CurrentMenu == nFREQ_MENU_A) || (CurrentMenu == MENU0)) && (TRUE != EditMode)) { ValueUpdateFlag = TRUE; stMenuDisplay[CurrentMenu].pvfPrintMenu(); } } tempWORD = Util_u16ByteSwap(stI2CUCMsg.unAtten.u16Atten); if (stConverter.stUp.u8ALC == STATUS_OFF) /* ALC OFF, read out Attn*/ { if ((tempWORD != stConverter.stUp.u16Atten)&&(tempWORD<= MAXATTEN)&&(tempWORD>= MINATTEN)) { stConverter.stUp.u16Atten = tempWORD; fAtten = (float)stConverter.stUp.u16Atten /10.0f; sprintf(AttenString1,"%02d.%1d dB",(int)fAtten,(int)(fAtten*10) %10 ); if((CurrentMenu == nATTN_MENU_A)&& (TRUE != EditMode)) { ValueUpdateFlag = TRUE; stMenuDisplay[nATTN_MENU_A].pvfPrintMenu(); } } } else /* ALC ON, read out Set Power*/ { if ((tempWORD != stConverter.stUp.u16SetPwr)&&(tempWORD<= MAXPOWER)&&(tempWORD>= MINPOWER)) { stConverter.stUp.u16SetPwr = tempWORD; fSetPwr = ((float)stConverter.stUp.u16SetPwr -500)/10.0f; stConverter.stUp.fSetPwr = fSetPwr; i16frac = (int)(fSetPwr*10) %10; if(i16frac < 0) i16frac *= -1; if ((fSetPwr<0)&& (fSetPwr>-1)) { sprintf(sUPC_StPwr,"-%02d.%1d dBm",(int)fSetPwr,i16frac); } else { sprintf(sUPC_StPwr,"%+03d.%1d dBm",(int)fSetPwr,i16frac); } if((CurrentMenu == nSTPWR_MENU_A)&& (TRUE != EditMode)) { ValueUpdateFlag = TRUE; stMenuDisplay[nSTPWR_MENU_A].pvfPrintMenu(); } } } tempWORD = Util_u16ByteSwap(stI2CUCMsg.u16RdPower); if(((tempWORD) != stConverter.stUp.u16OutputPower)&&(tempWORD<=MAXPOWER)&&(tempWORD>=MINPOWER)) { stConverter.stUp.u16OutputPower = tempWORD; ; stConverter.stUp.fOutputPower= ((float)tempWORD-500) ; stConverter.stUp.fOutputPower= stConverter.stUp.fOutputPower / 10.0f; fSetPwr = stConverter.stUp.fOutputPower; i16frac = (int)(fSetPwr*10) %10; if(i16frac < 0) i16frac *= -1; if ((fSetPwr<0) && (fSetPwr>-1)) { sprintf(sUCPower,"-%02d.%1d dBm",(int)fSetPwr,i16frac); } else { sprintf(sUCPower,"%+03d.%1d dBm",(int)fSetPwr,i16frac); } if(((CurrentMenu == nPOWER_MENU_A) || (CurrentMenu == MENU0))&& (TRUE != EditMode)) { ValueUpdateFlag = TRUE; stMenuDisplay[CurrentMenu].pvfPrintMenu(); } } return TRUE; } static BYTE SYS__u8UpdateDownConverter() { DWORD tempDWORD = 0; WORD tempWORD = 0; BYTE u8TempByte = 0; BOOL boReturn = FALSE; float fAtten; float fSetPwr; int i16frac; stI2CDCMsg.u8CtrlStatus &= nI2C_READ; I2C_Send(I2C_DownCVT_ADDR, (char*)&readflag, 1); boReturn = I2C_Read(I2C_DownCVT_ADDR, (char*)&stI2CDCMsg, sizeof(tstI2CMsg)); if(!boReturn) return FALSE; if (((stI2CDCMsg.u8CtrlStatus & nLOCK)== 0) && (stConverter.stDown.u8AlarmStatus != 0)) { stConverter.stDown.u8AlarmStatus = 0; stConverter.stDown.u8Lock = 0; if(((CurrentMenu == nLOSTATUS_MENU_B) || (CurrentMenu == MENU1)) && (TRUE != EditMode)) { ValueUpdateFlag = TRUE; stMenuDisplay[CurrentMenu].pvfPrintMenu(); } Main_vLEDLO(OFF); } else if (((stI2CDCMsg.u8CtrlStatus & nLOCK)!= 0) && (stConverter.stDown.u8AlarmStatus == 0)) { stConverter.stDown.u8AlarmStatus = 1; stConverter.stDown.u8Lock = 1; if(((CurrentMenu == nLOSTATUS_MENU_B) || (CurrentMenu == MENU1))&& (TRUE != EditMode)) { ValueUpdateFlag = TRUE; stMenuDisplay[CurrentMenu].pvfPrintMenu(); } if(stConverter.stUp.u8Lock == 1) Main_vLEDLO(ON); } u8TempByte = (stI2CDCMsg.u8CtrlStatus & nAGC_OFF)?0:1; //if(u8TempByte != stConverter.stDown.u8ALC) { stConverter.stDown.u8ALC= u8TempByte; if(STATUS_OFF == stConverter.stDown.u8ALC) { strcpypgm2ram(sALCb,"OFF"); } else { strcpypgm2ram(sALCb,"ON "); } if((CurrentMenu == nALC_MENU_B) && (TRUE != EditMode)) { ValueUpdateFlag = TRUE; stMenuDisplay[nALC_MENU_B].pvfPrintMenu(); } } u8TempByte = (stI2CDCMsg.u8CtrlStatus & nRX_ENABLE)?1:0; //if(u8TempByte != stConverter.stDown.u8Mute) { stConverter.stDown.u8Mute= u8TempByte; if(STATUS_OFF == stConverter.stDown.u8Mute) { strcpypgm2ram(sMuteb,"DISABLED"); //Main_vLEDRX(OFF); //zj disable for Lband } else { strcpypgm2ram(sMuteb,"ENABLED "); //Main_vLEDRX(ON); //zj disable for Lband } if ((CurrentMenu == nMUTE_MENU_B) && (TRUE != EditMode)) { ValueUpdateFlag = TRUE; stMenuDisplay[nMUTE_MENU_B].pvfPrintMenu(); } } tempDWORD = Util_u16DWORDSwap(stI2CDCMsg.unRfFreq.u32Freq); if ((tempDWORD != stConverter.stDown.u32InputFreq)&&(tempDWORD <=MAXRFFREQ)&&(tempDWORD>=MINRFFREQ)) { stConverter.stDown.u32InputFreq = tempDWORD; sprintf(RFFreqString2,"%04ld.%03ldMHz",stConverter.stDown.u32InputFreq/1000,stConverter.stDown.u32InputFreq%1000 ); if(((CurrentMenu == nFREQ_MENU_B) || (CurrentMenu == MENU1)) && (TRUE != EditMode)) { ValueUpdateFlag = TRUE; stMenuDisplay[CurrentMenu].pvfPrintMenu(); } } tempWORD = Util_u16ByteSwap(stI2CDCMsg.unAtten.u16Atten); if (stConverter.stDown.u8ALC == STATUS_OFF) /* ALC OFF, read out Attn*/ { if ((tempWORD != stConverter.stDown.u16Atten)&&(tempWORD<= MAXATTEN)&&(tempWORD>= MINATTEN)) { stConverter.stDown.u16Atten = tempWORD; fAtten = (float)stConverter.stDown.u16Atten /10.0f; sprintf(AttenString2,"%02d.%1d dB",(int)fAtten,(int)(fAtten*10) %10 ); if((CurrentMenu == nATTN_MENU_B) && (TRUE != EditMode)) { ValueUpdateFlag = TRUE; stMenuDisplay[nATTN_MENU_B].pvfPrintMenu(); } } } else /* ALC ON, read out Set Power*/ { if ((tempWORD != stConverter.stDown.u16SetPwr)&&(tempWORD<= MAXPOWER)&&(tempWORD>= MINPOWER)) { stConverter.stDown.u16SetPwr = tempWORD; fSetPwr = ((float)stConverter.stDown.u16SetPwr -500)/10.0f; stConverter.stDown.fSetPwr = fSetPwr; i16frac = (int)(fSetPwr*10) %10; if(i16frac < 0) i16frac *= -1; if ((fSetPwr<0) && (fSetPwr>-1)) { sprintf(sDNC_StPwr,"-%02d.%1d dBm",(int)fSetPwr,i16frac); } else { sprintf(sDNC_StPwr,"%+03d.%1d dBm",(int)fSetPwr,i16frac); } if((CurrentMenu == nSTPWR_MENU_B)&& (TRUE != EditMode)) { ValueUpdateFlag = TRUE; stMenuDisplay[nSTPWR_MENU_B].pvfPrintMenu(); } } } tempWORD = Util_u16ByteSwap(stI2CDCMsg.u16RdPower); if((tempWORD != stConverter.stDown.u16OutputPower)&&(tempWORD<=MAXPOWER)&&(tempWORD>=MINPOWER)) { stConverter.stDown.i16OutputPower = tempWORD; stConverter.stDown.fOutputPower = ((float)tempWORD-500); stConverter.stDown.fOutputPower = stConverter.stDown.fOutputPower /10.0f; fSetPwr = stConverter.stDown.fOutputPower; i16frac = (int)(fSetPwr*10) %10; if(i16frac < 0) i16frac *= -1; if ((fSetPwr<0) && (fSetPwr>-1)) { sprintf(sDCPower,"-%02d.%1d dBm",(int)fSetPwr,i16frac); } else { sprintf(sDCPower,"%+03d.%1d dBm",(int)fSetPwr,i16frac); } if(((CurrentMenu == nPOWER_MENU_B) || (CurrentMenu == MENU1))&& (TRUE != EditMode)) { ValueUpdateFlag = TRUE; stMenuDisplay[CurrentMenu].pvfPrintMenu(); } } return TRUE; } static BYTE SYS__u8UpdateVOL() { BYTE u8TempByte = 0; WORD u16TempWord = 0; BOOL boReturn = FALSE; stI2CREFMsg.u8Status &= nI2C_READ; I2C_Send(I2C_REF_ADDR, (char*)&readflag, 1); boReturn = I2C_Read(I2C_REF_ADDR, (char*)&stI2CREFMsg, sizeof(tstI2CMsgVOL)); if(!boReturn) return FALSE; u8TempByte = stI2CREFMsg.u8Status & nLNB_DC_ON ? 1:0; if(stConverter.stDC.u8LNB_DC_ONOFF!= u8TempByte ) { stConverter.stDC.u8LNB_DC_ONOFF= u8TempByte; if (STATUS_ON != stConverter.stDC.u8LNB_DC_ONOFF) { s18VDC[1] ='F'; s18VDC[2] ='F'; } else { s18VDC[1] ='N'; s18VDC[2] =' '; } if(((CurrentMenu == nDC18V_MENU) || (CurrentMenu == MENU2)) && (TRUE != EditMode)) { ValueUpdateFlag = TRUE; stMenuDisplay[CurrentMenu].pvfPrintMenu(); } } u8TempByte = stI2CREFMsg.u8Status & nBUC_DC_ON ? 1:0; if(stConverter.stDC.u8BUC_DC_ONOFF!= u8TempByte ) { stConverter.stDC.u8BUC_DC_ONOFF= u8TempByte; if (STATUS_ON != stConverter.stDC.u8BUC_DC_ONOFF) { s24VDC[1] ='F'; s24VDC[2] ='F'; } else { s24VDC[1] ='N'; s24VDC[2] =' '; } if (((CurrentMenu == nDC24V_MENU) || (CurrentMenu == MENU2)) && (TRUE != EditMode)) { ValueUpdateFlag = TRUE; stMenuDisplay[CurrentMenu].pvfPrintMenu(); } } u8TempByte = stI2CREFMsg.u8Status & nBUC_REF_ON ? 1:0; if(stConverter.stDC.u8BUC_REF_ONOFF!= u8TempByte ) { stConverter.stDC.u8BUC_REF_ONOFF= u8TempByte; if (STATUS_ON != stConverter.stDC.u8BUC_REF_ONOFF) { sBUCREF[1] ='F'; sBUCREF[2] ='F'; } else { sBUCREF[1] ='N'; sBUCREF[2] =' '; } if ((CurrentMenu == nBUCREF_MENU) && (TRUE != EditMode)) { ValueUpdateFlag = TRUE; stMenuDisplay[nBUCREF_MENU].pvfPrintMenu(); } } u8TempByte = stI2CREFMsg.u8Status & nLNB_REF_ON ? 1:0; if(stConverter.stDC.u8LNB_REF_ONOFF!= u8TempByte ) { stConverter.stDC.u8LNB_REF_ONOFF= u8TempByte; if (STATUS_ON != stConverter.stDC.u8LNB_REF_ONOFF) { sLNBREF[1] ='F'; sLNBREF[2] ='F'; } else { sLNBREF[1] ='N'; sLNBREF[2] =' '; } if ((CurrentMenu == nLNBREF_MENU) && (TRUE != EditMode)) { ValueUpdateFlag = TRUE; stMenuDisplay[nLNBREF_MENU].pvfPrintMenu(); } } u8TempByte = stI2CREFMsg.u8Status & nBUC_OVER_CURRENT ? 1:0; if(stConverter.stDC.u8BUC_DC_OVERCurrent != u8TempByte) { stConverter.stDC.u8BUC_DC_OVERCurrent = u8TempByte; if ((CurrentMenu == nBUCOVERI_MENU) && (TRUE != EditMode)) { ValueUpdateFlag = TRUE; stMenuDisplay[CurrentMenu].pvfPrintMenu(); } } u8TempByte = stI2CREFMsg.u8Status & nLNB_OVER_CURRENT ? 1:0; if(stConverter.stDC.u8LNB_DC_OVERCurrent != u8TempByte) { stConverter.stDC.u8LNB_DC_OVERCurrent = u8TempByte; if ((CurrentMenu == nLNBOVERI_MENU) && (TRUE != EditMode)) { ValueUpdateFlag = TRUE; stMenuDisplay[CurrentMenu].pvfPrintMenu(); } } u8TempByte = stI2CREFMsg.u8Status & nEXT_REF ? 1:0; if(stConverter.stDC.u8EXTREF != u8TempByte ) { stConverter.stDC.u8EXTREF = u8TempByte; if (((CurrentMenu == nEXTREF_MENU) || (CurrentMenu == MENU2)) && (TRUE != EditMode)) { ValueUpdateFlag = TRUE; stMenuDisplay[CurrentMenu].pvfPrintMenu(); } } u16TempWord = Util_u16ByteSwap(stI2CREFMsg.u16BUCCurrent); if(u16TempWord != stConverter.stDC.u16BUCCurrent ) { stConverter.stDC.u16BUCCurrent = u16TempWord; if ((CurrentMenu == nBUCI_MENU) && (TRUE != EditMode)) { ValueUpdateFlag = TRUE; stMenuDisplay[CurrentMenu].pvfPrintMenu(); } } u16TempWord = Util_u16ByteSwap(stI2CREFMsg.u16LNBCurrent); if(u16TempWord!= stConverter.stDC.u16LNBCurrent) { stConverter.stDC.u16LNBCurrent = u16TempWord; if ((CurrentMenu == nLNBI_MENU) && (TRUE != EditMode)) { ValueUpdateFlag = TRUE; stMenuDisplay[CurrentMenu].pvfPrintMenu(); } } u16TempWord = Util_u16ByteSwap(stI2CREFMsg.u16BUCCurrentLimit); if(u16TempWord!= stConverter.stDC.u16BUCCurrentLimit) { stConverter.stDC.u16BUCCurrentLimit=u16TempWord; } u16TempWord = Util_u16ByteSwap(stI2CREFMsg.u16LNBCurrentLimit); if(u16TempWord!= stConverter.stDC.u16LNBCurrentLimit) { stConverter.stDC.u16LNBCurrentLimit = u16TempWord; } return TRUE; } static BYTE SYS__u8UpdateLO() { BYTE u8TempByte = 0; WORD u16TempWord = 0; BOOL boReturn = FALSE; stI2CLOMsg.u8CtrlStatus&= nI2C_READ; I2C_Send(I2C_LO_ADDR, (char*)&readflag, 1); boReturn = I2C_Read(I2C_LO_ADDR, (char*)&stI2CLOMsg, sizeof(tstI2CMsg)); if(!boReturn) return FALSE; if(stI2CLOMsg.u8CtrlStatus & 0x04) //bit2 is lo status u8ExtLO = 1; else u8ExtLO = 0; } /* ValueUpdateFlag will force refresh LCD. it must be rechecked whether current page is relavant or else, refresh is not required */ /* Data strings should be re-organized */ /* JuZh: should consider only send to one module per cycle, or else waiting time is too long */ void UpdateStatus(void) { static BYTE u8Index = 0; if(0 == u8Index) /* Module Up Converter*/ SYS__u8UpdateUpConverter(); else if(1 == u8Index) { /* Module Down Converter*/ /* Do nothing since L-Band Up converter only */ // SYS__u8UpdateDownConverter(); SYS__u8UpdateLO(); } else if(2 == u8Index) /* Module Dc Control*/ SYS__u8UpdateVOL(); u8Index++; if(u8Index>=3) u8Index = 0; } <file_sep>/Devices/DownConverter_c1.c #include "define.h" #include "Global.h" #include "oled_c1.h" #include "string.h" #include "Util.h" void DownCvt_vPrintFreq(void) { strncpy(LCDPrintBuffer[1], RFFreqString2,sizeof(RFFreqString2)); } void DownCvt_vPrintPower(void) { strncpy(LCDPrintBuffer[1], sDCPower,sizeof(sDCPower)); } void DownCvt_vPrintStPwr(void) { strncpy(LCDPrintBuffer[1], sDNC_StPwr,sizeof(sDNC_StPwr)); } void DownCvt_vPrintLo(void) { if (stConverter.stDown.u8AlarmStatus == 1) { strncpy(LCDPrintBuffer[1], LOStatusString1,sizeof(LOStatusString1)); } else { strncpy(LCDPrintBuffer[1], LOStatusString2,sizeof(LOStatusString2)); } } void DownCvt_vPrintAttn(void) { strncpy(LCDPrintBuffer[1], AttenString2,sizeof(AttenString2)); } void DownCvt_vPrintALC(void) { strncpy(LCDPrintBuffer[1], sALCb,sizeof(sALCb)); } void DownCvt_vPrintMute(void) { if(stConverter.stDown.u8Mute==1) strncpypgm2ram(sMuteb,"ENABLED ",8); else strncpypgm2ram(sMuteb,"DISABLED",8); strncpy(LCDPrintBuffer[1], sMuteb,sizeof(sMuteb)); } void DownCvt_vSendI2C() { stI2CDCMsg.u16GainCompenVale = 0xFFFF; /* Don't write tables */ SetI2C(MODULE1); } void DownCvt_vSetFreq(void) { DWORD tempDWORD = 0; float fFreq = 0; fFreq = Util_u8String2NFloat((char*)&LCDPrintBuffer[1][0]); tempDWORD = (DWORD)(fFreq * 1000.0f);// should deduct 950 000? 950M ~ 2150M if ((tempDWORD != stConverter.stDown.u32InputFreq) && (tempDWORD <= MAXRFFREQ) && (tempDWORD >= MINRFFREQ)) { // stConverter.stDown.u32InputFreq = tempDWORD; stI2CDCMsg.unRfFreq.u32Freq = Util_u16DWORDSwap(tempDWORD); strncpy(RFFreqString2 ,LCDPrintBuffer[1], sizeof(RFFreqString2) ); DownCvt_vSendI2C(); } } void DownCvt_vSetAttn(void) { WORD tempWORD = 0; if ((stConverter.stDown.u8ALC != STATUS_OFF)) return; tempWORD = LCDPrintBuffer[1][0] - '0'; tempWORD = ((WORD)(tempWORD * 10)) + ((WORD)LCDPrintBuffer[1][1] - '0'); tempWORD = ((WORD)(tempWORD * 10)) + ((DWORD)LCDPrintBuffer[1][3] - '0'); /* tempWORD is atten * 10 */ if ((tempWORD != stConverter.stDown.u16Atten) && (tempWORD <= MAXATTEN) && (tempWORD >= MINATTEN)) { //stConverter.stDown.u16Atten = tempWORD; stI2CDCMsg.unAtten.u16Atten= Util_u16ByteSwap(tempWORD); memcpy(AttenString2 ,LCDPrintBuffer[1], sizeof(AttenString2) ); DownCvt_vSendI2C(); } } void DownCvt_vSetPower(void) { /*Disabled and moved to DownCvt_vSetStPwr */ } void DownCvt_vSetStPwr(void) { BYTE u8TempByte =0; float fTemp; SHORT i16Temp; WORD u16Temp; if ((stConverter.stDown.u8ALC != STATUS_ON)) return; fTemp = Util_u8String2Float(LCDPrintBuffer[1]); u16Temp = (WORD)(fTemp *10 + 500); if ((u16Temp!= stConverter.stDown.u16SetPwr) && (u16Temp <= MAXPOWER) && (u16Temp >= MINPOWER)) { stConverter.stDown.u16SetPwr = u16Temp; stConverter.stDown.fSetPwr= fTemp; //shared 16bits of att and wtpwr stI2CDCMsg.unAtten.u16Atten = Util_u16ByteSwap(u16Temp); memcpy(sDNC_StPwr,LCDPrintBuffer[1], sizeof(sDNC_StPwr) ); DownCvt_vSendI2C(); } } void DownCvt_vSetALC(void) { BYTE u8TempByte =0; u8TempByte = LCD__u8GetOnOff(); strncpy(sALCb,LCDPrintBuffer[1], sizeof(sALCb) ); if(u8TempByte==0) { stConverter.stDown.u8ALC = OFF; stI2CDCMsg.u8CtrlStatus |= nAGC_OFF;//0x02 } else if(u8TempByte==1) { stConverter.stDown.u8ALC = ON; stI2CDCMsg.u8CtrlStatus &= nAGC_ON;//0xFD } DownCvt_vSendI2C(); } void DownCvt_vSetMute(void) { BYTE u8TempByte =0; if(!memcmppgm2ram(LCDPrintBuffer[1],"ENABLED",7)) u8TempByte = 1; else if (!memcmppgm2ram(LCDPrintBuffer[1],"DISABLED",8)) u8TempByte = 0; if(u8TempByte==0) { stConverter.stDown.u8Mute = 0; strncpy(sMuteb,LCDPrintBuffer[1], sizeof(sMuteb) ); stI2CDCMsg.u8CtrlStatus &= nRX_DISABLE; DownCvt_vSendI2C(); //Main_vLEDRX(u8TempByte); //zj disable for Lband } else if(u8TempByte==1) { stConverter.stDown.u8Mute = 1; strncpy(sMuteb,LCDPrintBuffer[1], sizeof(sMuteb) ); stI2CDCMsg.u8CtrlStatus |= nRX_ENABLE; DownCvt_vSendI2C(); //Main_vLEDRX(u8TempByte); //zj disable for Lband } } <file_sep>/Main/Main.c /********************************************************************* ********************************************************************* * FileName: MainDemo.c * Dependencies: TCPIP.h * Processor: PIC18, PIC24F, PIC24H, dsPIC30F, dsPIC33F, PIC32 * Compiler: Microchip C32 v1.05 or higher * Microchip C30 v3.12 or higher * Microchip C18 v3.30 or higher * HI-TECH PICC-18 PRO 9.63PL2 or higher * Company: Microchip Technology, Inc. * ********************************************************************/ #define THIS_IS_STACK_APPLICATION #if defined(__18F97J60) || defined(_18F97J60) // Include all headers for any enabled TCPIP Stack functions #include "TCPIP Stack/TCPIP.h" #endif // Include functions specific to this stack application #include "singcom.h" //******************************************************************************* #include "Main.h" #include "define.h" #include "delays.h" #include "Global.h" #include "timers.h" #include "list.h" #include "DualUART.h" #include "Uart.h" #include <i2c.h> #include "i2c_c1.h" #include "oled_c1.h" #include "Util.h" #define nMINUTE 60 //******************************************************************************************************* extern char Uart0PCCmdBuf[32]; extern BYTE Uart1ReadLCDCmd; extern BYTE Uart0ReadPCCmd; extern BYTE Uart0PCCmdBufCount; //********************************************************************************************************** #if 0 const char CompanyString1[40] = {" SINGCOM "}; const char CompanyString2[40] = {" DOWN CONVERTER "}; const char menutextstring1[] = {"[CVT. 1] "}; const char menutextstring2[] = {"[CVT. 2] "}; const char menutextstring3[] = {"[DEVICE INFO] "}; const char menutextstring4[] = {"LO "}; const char menutextstring5[] = {"RF "}; const char menutextstring6[] = {"LO "}; const char menutextstring7[] = {"Atten. "}; const char menutextstring8[] = {"IF "}; #endif char FirmwareVersion[4] = {"100"}; tstUpDownConverter stConverter; extern unsigned char LastMenu; extern unsigned char CurrentMenu; unsigned char SecondCounter = 0, MinuteCounter = 0; // Declare AppConfig structure and some other supporting stack variables unsigned char HardwareWDT = 1; //#define UART_TEST // uart testing IP_ADDR MyStaticIPAddr; unsigned char ostart,oend,ctemp; #pragma udata grp5 APP_CONFIG AppConfig; #pragma udata unsigned char Read2[2][4]; #pragma udata gpr8 systeminfo_t systeminfo1; #pragma udata grp10 systeminfo_t2 systeminfo2; static TICK webPass_tmr = 0, lcd_timer = 0, keypad_tmr = 0,tiDisplay_tmr=0; static void DRI__vEnableGlobalInt(); static void DRI__vHitWatchDog(void) ; static void DRI__vEnableGlobalInt(); static void DRI__vConfigSPI(); static void SYS__vStatusTask(); static void SYS__vLcdDisplayTask(void); static void SYS__vLcdKeyPadTask(void); static BYTE SYS__u8InitData(void); static void HTTP_vClearWebPassword(); void main(void); //#pragma code // Return to default code section //#define ClearWatchDog() { _asm CLRWDT _endasm } /* Called in Main function */ static void DRI__vHitWatchDog(void) { // clear MCU watchdog //ClearWatchDog(); _asm CLRWDT _endasm // clear hardware watch dog, toggle RA3 // if (HardwareWDT == 1) { // WDI_FLAG = 0; // HardwareWDT = 0; } // else { // WDI_FLAG = 1; // HardwareWDT = 1; } } //********************* FUNCTIONS ************************ /* only used in pic18f8722 */ #if 0 static void DRI__vINT_OFF(void) { // INTCONbits.GIEL = 0; // INTCONbits.GIEH = 0; // INTCONbits.GIE = 0; } static void DRI__vINT_ON(void) { // INTCONbits.GIEL = 1; // INTCONbits.GIEH = 1; // INTCONbits.GIE = 1; } #endif /* Enable Global interrupts */ static void DRI__vEnableGlobalInt() { INTCONbits.GIEL=1; INTCONbits.GIEH = 1; INTCONbits.GIE = 1; //Enable global interrupts INTCONbits.PEIE = 1; //Enable peripheral interrupts } /* Configure SPI bits and registers */ static void DRI__vConfigSPI() { SCL_TRIS = 0; SDA_TRIS = 0; SSP2CON1bits.SSPEN = 0; SSP2STATbits.SMP = 1; SSP2CON1 &= 0xF0; SSP2CON1 |= 0x08; } /* Update System status from sub modules */ /* Consider to change this task to be receive interrupt triggered with update values to reduce process time*/ static void SYS__vStatusTask() { /* Status update from Module MCUs and blick LCD */ /* SecondCounter actually update every 1/3 second = 330ms*/ if ((TickGet() - lcd_timer) >= (TICK_SECOND / 2)) { /* Update status */ UpdateStatus(); /* A time consuming task */ lcd_timer = TickGet(); } } /* For blinking display Only*/ static void SYS__vLcdBlinkTask(void) { if ((TickGet() - tiDisplay_tmr) >= (TICK_SECOND /3 )) { tiDisplay_tmr = TickGet(); SecondCounter++; /* Blinking effect: dislay text alternatively for odd and even seconds*/ /* TBD can be improved here to only update blinking part , keep others static */ // if (((SecondCounter % 4) == 1)||((SecondCounter % 4) == 2)) /* Blink 0.33s */ // { // PrintLCD(); // } // else // { // PrintBlinkLCD(); // } /* Refresh LCD screen */ if (ValueUpdateFlag == TRUE) /* if there is data update from I2C, whole page content has to be updated */ { ValueUpdateFlag = FALSE; PrintNewValue(); } else /* if no data update, just toggle the blink of value/' ', or update the edit cursor position */ { PrintBlinkMenuText(); } if(SecondCounter >= nMINUTE) /* Reset from 0 */ SecondCounter = 0; } } #if 1 /* For key processing and Menu Update*/ static void SYS__vLcdKeyPadTask(void) { /* 1. Key press handling */ /* KeyPressedFlag = true & PressedKey is set in ISR.c -> LowISR */ if ((KeyPressedFlag == TRUE) && (PressedKey != NULL)) { #if 0 /* There is not the very first time of key pressing */ if (FirstPressKey == FALSE) { /* The previous handling and t2 happened 1/10 second = 100 ms before, must re-check */ if ((TickGet() - keypad_tmr) >= (TICK_SECOND / 10)) { KeyProcessing(); } } /* This is the first time of keypress after start up, t2 is 0 in beginning */ else #endif { KeyProcessing(); } keypad_tmr = TickGet(); // FirstPressKey = FALSE; /* This is not the 1st key press */ KeyPressedFlag = FALSE; /* Clear KeyPressedFlag from LowISR */ } /* 2. Menu page update */ /* Current Menu from KeyProcessing diffs from previous menu recorded,refresh is required */ if (CurrentMenu != LastMenu) { RefreshFlag = TRUE; LastMenu = CurrentMenu; } /* Menu changed, Refresh whole LCD screen */ if (RefreshFlag == TRUE) { RefreshFlag = FALSE; LCD_u8UpdateDisplayContent(); PrintLCDWholePage(); } /* Got New data set from keypad, Refresh only Data */ else if(ValueUpdateFlag == TRUE) { ValueUpdateFlag = FALSE; PrintNewValue(); } /* Up down ky pressed, Refresh only Edit position */ else if(EditUpdateFlag == TRUE) /*Update only the Edit cursor position */ { EditUpdateFlag = FALSE; PrintEditPosition(); } } #endif #if 0 static void SYS__vLcdKeyPadTask(void) { /* 1. Key press handling */ /* KeyPressedFlag = true & PressedKey is set in ISR.c -> LowISR */ if ((KeyPressedFlag == TRUE) && (PressedKey != NULL)) { KeyProcessing(); FirstPressKey = FALSE; /* This is not the 1st key press */ KeyPressedFlag = FALSE; /* Clear KeyPressedFlag from LowISR */ } /* 2. Menu page update */ /* Current Menu from KeyProcessing diffs from previous menu recorded,refresh is required */ if (CurrentMenu != LastMenu) { RefreshFlag = TRUE; LastMenu = CurrentMenu; } /* Refresh LCD screen */ if (RefreshFlag == TRUE) { RefreshFlag = FALSE; LCD_u8UpdateDisplayContent(); PrintLCDWholePage(); } if(ValueUpdateFlag == TRUE) { ValueUpdateFlag = FALSE; PrintNewValue(); } if(EditUpdateFlag == TRUE) /*Update only the Edit cursor position */ { EditUpdateFlag = FALSE; PrintEditPosition(); } } #endif /* Flag to be used in HTTP Password Page */ static void HTTP_vClearWebPassword() { //schedule task to clear set password result if (TickGet() - webPass_tmr >= TICK_SECOND*3) { webPass_tmr = TickGet(); webpassinfo.count++; if (webpassinfo.count == 2) { webpassinfo.setpass = others; webpassinfo.count = 0; } } } static BYTE SYS__u8InitData(void) { stConverter.stUp.u8AlarmStatus = 0; stConverter.stDown.u8AlarmStatus = 0; stConverter.stUp.u8Lock = 0; stConverter.stDown.u8Lock = 0; stConverter.stUp.u16Atten= 0; stConverter.stDown.u16Atten= 0; stConverter.stUp.u8OutputPower= 30; stConverter.stDown.u8OutputPower= 30; stConverter.stUp.i16OutputPower= -30; stConverter.stDown.i16OutputPower= -30; stConverter.stUp.u32OutputFreq= 950000; stConverter.stDown.u32InputFreq= 950000; stConverter.stUp.u8ALC = FALSE; stConverter.stDown.u8ALC = FALSE; stConverter.stUp.u8Mute= FALSE; stConverter.stDown.u8Mute= FALSE; stConverter.stDC.u8LNB_DC_ONOFF= FALSE; stConverter.stDC.u8BUC_DC_ONOFF= FALSE; stConverter.stDC.u8LNB_REF_ONOFF= FALSE; stConverter.stDC.u8BUC_REF_ONOFF= FALSE; stI2CUCMsg.u8CtrlStatus= 0; stI2CUCMsg.unRfFreq.u32Freq = 950000; stI2CUCMsg.unAtten.u16Atten = 0; stI2CUCMsg.u16RdPower = 30; stI2CUCMsg.u8CtrlStatus = 0x00 | nLOCK; /* Lo Lock, ALC and Mute off */ stI2CDCMsg.u8CtrlStatus= 0; stI2CDCMsg.unRfFreq.u32Freq = 950000; stI2CDCMsg.unAtten.u16Atten = 0; stI2CDCMsg.u16RdPower = 30; stI2CDCMsg.u8CtrlStatus = 0x00 | nLOCK; /* Lo Lock, ALC and Mute off */ stI2CREFMsg.u8Status= 0; stI2CREFMsg.u16BUCCurrent = 0; stI2CREFMsg.u16LNBCurrent = 0; stI2CREFMsg.u16BUCCurrentLimit = 0; stI2CREFMsg.u16LNBCurrentLimit = 0; stConverter.stDC.u8EXTREF = 0; stConverter.stDC.u8BUC_DC_ONOFF = 0; stConverter.stDC.u8LNB_DC_ONOFF = 0; stConverter.stDC.u8BUC_REF_ONOFF= 0; stConverter.stDC.u8LNB_REF_ONOFF= 0; stConverter.stDC.u8BUC_DC_OVERCurrent = 0; stConverter.stDC.u8LNB_DC_OVERCurrent = 0; stConverter.stDC.u16BUCCurrent = 0; stConverter.stDC.u16LNBCurrent = 0; stConverter.stDC.u16BUCCurrentLimit= 0; stConverter.stDC.u16LNBCurrentLimit= 0; } void main(void) { WORD tempWORD; float fAtt = 0; #if 0 //test code SHORT i8Temp; WORD u16Temp; SHORT i16Temp = 10; char i8Temp2; WORD u16Temp2; char i8Temp3; WORD u16Temp3; char acTem[10] = "-30"; char acTem2[10] = "+13"; char acTem3[10] = "24"; //tempWORD = stI2CUCMsg.u16RdPower; stConverter.stUp.i16OutputPower =-5; sprintf(sUCPower,"%+03d dB",stConverter.stUp.i16OutputPower); stConverter.stUp.i16OutputPower =12; sprintf(sUCPower,"%+03d dB",stConverter.stUp.i16OutputPower); stConverter.stUp.i16OutputPower =0; if ((stConverter.stUp.i16OutputPower<0)&&(stConverter.stUp.i16OutputPower>-1)) { sprintf(sUCPower,"-%02d dB",stConverter.stUp.i16OutputPower); } else { sprintf(sUCPower,"%+03d dB",stConverter.stUp.i16OutputPower); } Nop(); sprintf(AttenString2,"%02d.%1d dB",(int)fAtt, (int)(fAtt*10) %10 ); Nop(); fAtt = 2.3; sprintf(AttenString2,"%02d.%1d dB",(int)fAtt, (int)(fAtt*10) %10 ); Nop(); fAtt = 12.5; sprintf(AttenString2,"%02d.%1d dB",(int)fAtt,(int)(fAtt*10) %10 ); Nop(); stConverter.stUp.u32OutputFreq = 1234567; sprintf(RFFreqString1,"%04ld.%03ldMHz",(DWORD)(stConverter.stUp.u32OutputFreq/1000),(DWORD)(stConverter.stUp.u32OutputFreq%1000) ); Nop(); stConverter.stUp.u32OutputFreq = 1234; sprintf(RFFreqString1,"%04ld.%03ldMHz",stConverter.stUp.u32OutputFreq/1000,stConverter.stUp.u32OutputFreq%1000 ); Nop(); //sscanf(); i8Temp = Util_u8String2int8((char*)acTem); u16Temp = ( i8Temp *10 + 500); i8Temp2 = Util_u8String2int8((char*)acTem2); u16Temp2 = (i8Temp2 *10 + 500); i8Temp3 = Util_u8String2int8((char*)acTem3); u16Temp3 = (i8Temp3 *10 + 500); #endif // Initialize application specific hardware InitializeBoard(); OLED_vSetKepad(); /* Set OLED Keypad io directions */ DRI__vConfigSPI(); /* Configure SPI bits and registers */ OLED_vSetIO(); /* Set OLED control io directions */ Main_vLEDInit(); /* Set LED bits on main panel */ SYS__u8InitData(); Initial_LCD(); InitalizeMenu(); DisplayCompanyMenu(); PrintCompanyLCD(); DelayMs(1000); LCD_u8UpdateDisplayContent(); DelayMs(300); PrintLCDWholePage(); //DelayMs(200); RCONbits.IPEN=1; // yt: should enable IPEN before GIE TickInit(); DRI__vEnableGlobalInt(); Main_vLEDInit(); #if defined(STACK_USE_MPFS) || defined(STACK_USE_MPFS2) MPFSInit(); #endif // Initialize Stack and application related NV variables into AppConfig. InitAppConfig(); InitData(); StackInit(); // init I2C, // set Converter A LO Frequency, Attenuation; // set Converter B LO Frequency, Attenuation; // SetDefaultValue(); OLED_vEnableInterrupt();/* Set OLED key interrupt bits */ while(1) { /** Task priority: Time: Tick Period: Trigger: 0 SYS__vLcdKeyPadTask Long 2nd Check: TICK_SECOND/10 Interrupt(KeyPressedFlag) 1 StackTask Long NULL Receiver INT 2 SYS__vStatusTask Long TICK_SECOND/3 Timer 2 StackApplications Long NULL Receiver INT 3 SYS__vLcdBlinkTask Middle TICK_SECOND Timer 4 HTTP_vClearWebPassword Short TICK_SECOND*3 Timer **/ /* If KeyPressedFlag == TRUE */ SYS__vLcdKeyPadTask(); /* Run ethernet stack task only if PHY is connected */ if(MACIsLinked()) { /* TCP/IP stack task */ StackTask(); /* This tasks invokes each of the core stack application tasks */ StackApplications(); } /* Run lower priority task only if Keypad is not in use */ // if( TRUE != KeyPressedFlag ) { SYS__vLcdBlinkTask(); SYS__vStatusTask(); HTTP_vClearWebPassword(); } #if defined(STACK_USE_SNMP_SERVER) && !defined(SNMP_TRAP_DISABLED) /* snmp_trap_task(); */ /* SNMP is not used in this version */ #endif DRI__vHitWatchDog(); } }
f73a2d27df89b0bf604b6a37bc58b92ee119bb1a
[ "C" ]
7
C
heathzj/70M
0cb18c7809d70481fc5dbe9e8ec283b5f18f43dc
0c11d28d59af94a95403c11fb96dceed905b514b
refs/heads/main
<repo_name>rcottrell0517/thermalConstantSearch<file_sep>/fetchTconstants.js const result = document.getElementById('result') const filter = document.getElementById('filter') const listItems = [] console.log(listItems) getData() // gives us what is typed in filter.addEventListener('input', (e) => filterData(e.target.value)) async function getData() { const res = await fetch('tconstants.json') const results = await res.json() console.log(results) // Clear results result.innerHTML = '' results.forEach(tconstants => { console.log(tconstants) const li = document.createElement('li') listItems.push(li) li.innerHTML = ` <img src="${tconstants.picture}"> <div class="tconstant-info"> <h2>Style: ${tconstants.style}</h2> <h2>K1: ${tconstants.K1}</h2> <h2>K2: ${tconstants.K2}</h2> <h2>n: ${tconstants.n}</h2> <h2>Time Constant: ${tconstants.Time_Constant} min.</h2> </div> ` result.appendChild(li) }); } // gives us what is being typed in function filterData(searchTerm) { console.log(searchTerm) listItems.forEach(item => { if(item.innerText.toLowerCase().includes(searchTerm.toLowerCase())) { item.classList.remove('hide') } else { item.classList.add('hide') } }) }
d8dad9fdd8f09cc64b5f4f4bf3a3d47bbecea6c9
[ "JavaScript" ]
1
JavaScript
rcottrell0517/thermalConstantSearch
fe9741400c17ce87898d61e305b6e5c9eb17c749
9f3e15df74dc0dabe88a023750d404bf0bca4854
refs/heads/master
<repo_name>BilalRaja97/Sudoku_Solver<file_sep>/Sudoku_Solver.py # <NAME> import copy #Create Sudoku class class SudokuGrid(): def __init__(self, source_grid = None): # whenever we create a sudoku grid this will start# if source_grid is None: # create these 'nine lists' self.grid = [] for i in range (9): self.grid.append([None] *9) #check legal grid else: if (type(source_grid) !=list): raise ValueError("Grid is not a list") if (len(source_grid) != 9): raise ValueError("Only 9x9 grids for this solver") for col in source_grid: if (type(col) != list): raise ValueError("Not a list of lists") if (len(col) != 9): raise ValueError("not a 9x9 grid") for item in col: if (type(item) == int): if item not in range(1,10): raise ValueError("Source Grid does not contain range 1 to 9") elif (item is not None): raise ValueError("Source Grid contains illegal object") self.grid = copy.deepcopy(source_grid) def _find_subgrids_num(self, col_num,row_num): initial_row = row_num - (row_num % 3) initial_col = col_num - (col_num % 3) nums = [] for i in range(3): for j in range(3): item = self.grid[initial_col + i][initial_row + j] if item is not None: nums.append(item) return nums def get_nums_in_col(self,col_num): # want to retrieve all the numbers in the column return [item for item in self.grid[col_num] if item is not None] def get_nums_in_row(self, row_num): # get all the numbers in rows by taking it from the cols return [col[row_num] for col in self.grid if col[row_num] is not None] def get_legal_moves(self,col_num,row_num): return [i for i in range(1,10) if i not in self.get_nums_in_row(row_num) and i not in self.get_nums_in_col(col_num) and i not in self._find_subgrids_num(col_num, row_num)] def find_next_open_square(self): # check each col for empty spot otherwise return that col is full for i in range(9): for j in range(9): if self.grid [i][j] is None: return (i,j) return (-1, -1) def set_next_square(self, new_value): if new_value not in range(1,10): raise ValueError ("Not a value between 1 to 9") (next_col, next_row) = self.find_next_open_square() if new_value not in self.get_legal_moves(next_col,next_row): raise ValueError("Not a legal move") if next_col == -1: raise Exception("Grid is full") new_grid = SudokuGrid(self.grid) # new grid is a new Class and new_grid.grid is a grid within this class new_grid.grid [next_col][next_row] = new_value return new_grid def __str__(self): repr = "" for i in range(9): for j in range(9): if type(self.grid[j][i]) == int: repr += f' {self.grid[j][i]} ' else: repr += '.' repr += '\n' return repr def solve_sudoku(sudoku_grid): (next_col, next_row) = sudoku_grid.find_next_open_square() if next_col == -1: return sudoku_grid legal_moves = sudoku_grid.get_legal_moves(next_col,next_row) # create the next few sudoku grids for all the legal moves next_stage = [sudoku_grid.set_next_square(i) for i in legal_moves] for grid in next_stage: result = solve_sudoku(grid) if result is not None: return result return None if __name__ == '__main__': sample_grid =\ [[5, 6, None, 8, 4, 7, None, None, None], [3, None, 9, None, None, None, 6, None, None], [None, None, 8, None, None, None, None, None, None], [None, 1, None, None, 8, None, None, 4, None], [7, 9, None, 6, None, 2, None, 1, 8], [None, 5, None, None, 3, None, None, 9, None], [None, None, None, None, None, None, 2, None, None], [None, None, 6, None, None, None, 8, None, 7], [None, None, None, 3, 1, 6, None, 5, 9]] answer = solve_sudoku(SudokuGrid(sample_grid)) print(answer) <file_sep>/README.md # Sudoku_Solver Simple python Sudoku solver
9d80cf6a20ae1fb3eebd6f8b560bc175d052554f
[ "Markdown", "Python" ]
2
Python
BilalRaja97/Sudoku_Solver
1ac92a83bfb0a7f1ec65499febcda35813048f62
78991010131883bd39d5297332cfd5177dcfd7e5
refs/heads/master
<repo_name>samwu4166/LibraAssist<file_sep>/app/src/main/java/com/writerwriter/libraassist/AccountListAdapter.java package com.writerwriter.libraassist; import android.content.Context; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.ramotion.foldingcell.FoldingCell; import java.util.List; /** * Created by Larry on 2017/12/10. */ public class AccountListAdapter extends RecyclerView.Adapter<AccountListAdapter.ViewHolder> { private List<AccountUnit> accountList; private Context mContext; public static class ViewHolder extends RecyclerView.ViewHolder{ public TextView account; public TextView libraryName; public EditText enter_account; public EditText enter_password; public Button log_in; public Button log_out; public ImageView image; public ViewHolder(View itemView){ super(itemView); account = (TextView)itemView.findViewById(R.id.account); libraryName = (TextView)itemView.findViewById(R.id.library_name); enter_account = (EditText)itemView.findViewById(R.id.enter_account); enter_password = (EditText)itemView.findViewById(R.id.enter_password); log_in = (Button)itemView.findViewById(R.id.log_in_btn); log_out = (Button)itemView.findViewById(R.id.log_out_btn); image = (ImageView)itemView.findViewById(R.id.library_login_icon); } } public AccountListAdapter(List<AccountUnit> accountList, Context context){ this.accountList = accountList; this.mContext = context; } @Override public int getItemCount() { return accountList.size(); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { Context context = parent.getContext(); View account_list_view = LayoutInflater.from(context).inflate(R.layout.account_list_card,parent,false); ViewHolder viewHolder = new ViewHolder(account_list_view); /*account_list_view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final FoldingCell fc = (FoldingCell) view.findViewById(R.id.account_cardview); fc.toggle(false); } });*/ return viewHolder; } @Override public void onBindViewHolder(final ViewHolder holder, final int position) { final AccountUnit accountUnit = accountList.get(position); switch ((accountUnit.getLibraryName())){ case "國立台北大學圖書館": holder.image.setImageResource(R.drawable.ntpu_lib); holder.image.setMaxHeight(holder.image.getWidth()*960/1920); break; case "新北市立圖書館": holder.image.setImageResource(R.drawable.ntc_lib); holder.image.setMaxHeight(holder.image.getWidth()*472/1280); break; case "台北市立圖書館": holder.image.setImageResource(R.drawable.tc_lib); holder.image.setMaxHeight(holder.image.getWidth()*960/1920); break; } holder.libraryName.setText(accountUnit.getLibraryName()); holder.account.setText(accountUnit.getAccount()); holder.log_in.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(!holder.enter_account.getText().toString().isEmpty() && !holder.enter_account.getText().toString().isEmpty()) { switch (accountUnit.getLibraryName()) { case "國立台北大學圖書館": AccountManager.Instance.SendUpdateAccount(AccountManager.NTPU_LIB_KEY, holder.enter_account.getText().toString(), holder.enter_password.getText().toString()); break; case "新北市立圖書館": AccountManager.Instance.SendUpdateAccount(AccountManager.NEWTAIPEI_LIB_KEY, holder.enter_account.getText().toString(), holder.enter_password.getText().toString()); break; case "台北市立圖書館": AccountManager.Instance.SendUpdateAccount(AccountManager.TAIPEI_LIB_KEY, holder.enter_account.getText().toString(), holder.enter_password.getText().toString()); break; } } else if(holder.enter_account.getText().toString().isEmpty() || holder.enter_account.getText().toString().isEmpty()){ Toast.makeText(mContext,"請輸入完整的帳號和密碼。",Toast.LENGTH_SHORT).show(); } } }); holder.log_out.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { switch(accountUnit.getLibraryName()){ case "國立台北大學圖書館": AccountManager.Instance.SendDeleteAccount(AccountManager.NTPU_LIB_KEY); break; case "新北市立圖書館": AccountManager.Instance.SendDeleteAccount(AccountManager.NEWTAIPEI_LIB_KEY); break; case "台北市立圖書館": AccountManager.Instance.SendDeleteAccount(AccountManager.TAIPEI_LIB_KEY); break; } } }); if (accountUnit.getState() == AccountUnit.PENDING){ holder.account.setText("驗證帳號密碼中..."); } else if(accountUnit.getState() == AccountUnit.ERROR){ holder.account.setText("帳號密碼驗證失敗"); } if(FirebaseAuth.getInstance().getCurrentUser() != null){ holder.log_in.setEnabled(true); } else{ holder.log_in.setEnabled(false); } holder.itemView.setTag(position); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(accountList.get(position).getState() != AccountUnit.PENDING) { final FoldingCell fc = (FoldingCell) view.findViewById(R.id.account_cardview); fc.toggle(false); } } }); } } <file_sep>/app/src/main/java/com/writerwriter/libraassist/Sub2BorrowFragment.java package com.writerwriter.libraassist; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.writerwriter.libraassist.BorrowBookAdapter; import com.writerwriter.libraassist.BorrowBookUnit; import com.writerwriter.libraassist.R; import com.writerwriter.libraassist.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; public class Sub2BorrowFragment extends Fragment { private RecyclerView borrowListView; private LinearLayoutManager linearLayoutManager; public Sub2BorrowFragment() {} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_sub2_borrow, container, false); BorrowBookAdapter adapter = new BorrowBookAdapter(AccountManager.Instance.borrowedBookList, getContext()); borrowListView = v.findViewById(R.id.borrow_book_recyclerView2); borrowListView.setHasFixedSize(true); linearLayoutManager = new LinearLayoutManager(getActivity()); borrowListView.setLayoutManager(linearLayoutManager); borrowListView.setAdapter(adapter); return v; } } <file_sep>/app/src/main/java/com/writerwriter/libraassist/TagAdapter.java package com.writerwriter.libraassist; import android.content.Context; import android.support.annotation.NonNull; import android.text.InputType; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; import com.daimajia.swipe.SwipeLayout; import com.daimajia.swipe.adapters.BaseSwipeAdapter; import org.w3c.dom.Text; import java.util.ArrayList; import java.util.List; /** * Created by Larry on 2017/12/24. */ public class TagAdapter extends BaseSwipeAdapter{ private List<TagUnit> list; private Context mContext; public TagAdapter(Context mContext, List<TagUnit> list) { this.mContext = mContext; this.list = list; } @Override public int getSwipeLayoutResourceId(int position) { return R.id.tag_item; } //ATTENTION: Never bind listener or fill values in generateView. // You have to do that in fillValues method. @Override public View generateView(int position, ViewGroup parent) { View view = LayoutInflater.from(mContext).inflate(R.layout.tag_item, null); return view; } @Override public void fillValues(final int position, View convertView) { TextView t = (TextView)convertView.findViewById(R.id.tag_text); t.setText(list.get(position).getTag_text()); TextView t2 = (TextView)convertView.findViewById(R.id.tag_pages); t2.setText(list.get(position).getTag_pages()); final SwipeLayout swipeLayout = (SwipeLayout)convertView.findViewById(getSwipeLayoutResourceId(position)); swipeLayout.setShowMode(SwipeLayout.ShowMode.LayDown); swipeLayout.addDrag(SwipeLayout.DragEdge.Left, convertView.findViewById(R.id.bottom_wrapper)); Button remove_btn = (Button)convertView.findViewById(R.id.remove_btn); Button edit_btn = (Button)convertView.findViewById(R.id.edit_btn); remove_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //list.remove(position); //notifyDataSetChanged(); Sub3BorrowFragment.Instance.UpdateBookmark(list.get(position).getTag_text(), ""); swipeLayout.close(); } }); edit_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new MaterialDialog.Builder(mContext) .title("修改書籤") .positiveText("確認") .negativeText("取消") .inputType(InputType.TYPE_CLASS_NUMBER) .input("輸入頁數:", "", new MaterialDialog.InputCallback() { @Override public void onInput(@NonNull MaterialDialog dialog, CharSequence input) { //list.get(position).setTag_pages(input.toString()); //notifyDataSetChanged(); Sub3BorrowFragment.Instance.UpdateBookmark(list.get(position).getTag_text(), input.toString()); } }) .show(); } }); } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return position; } } <file_sep>/app/src/main/java/com/writerwriter/libraassist/CollectionSearchResultUnit.java package com.writerwriter.libraassist; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.util.Log; import android.view.View; import android.widget.ImageView; import java.io.InputStream; import java.util.HashMap; /** * Created by Larry on 2017/12/12. */ public class CollectionSearchResultUnit { private static final String NULL_TITLE = "取得資料中..."; private static final String NULL_IMG = "https://www.cmswing.com/u/avatar/131"; private static final String ERROR_IMG = "http://www.51allout.co.uk/wp-content/uploads/2012/02/Image-not-found.gif"; private String isbn; private String title = NULL_TITLE; private String author = NULL_IMG; private String img; private String publish_year; private String publisher; private String location; private String storage; private String link; private String searchState = "null"; public CollectionSearchResultUnit() { } public CollectionSearchResultUnit(HashMap<String, String> data) { SetInfo(data); } public void SetInfo(HashMap<String, String> data) { if(data.containsKey("isbn")) isbn = data.get("isbn"); if(data.containsKey("title")) title = data.get("title"); if(data.containsKey("author")) author = data.get("author"); if(data.containsKey("img")) img = data.get("img"); if(data.containsKey("publish_year")) publish_year = data.get("publish_year"); if(data.containsKey("publisher")) publisher = data.get("publisher"); if(data.containsKey("link")) link = data.get("link"); if(data.containsKey("location")) location = data.get("location"); if(data.containsKey("storage")) storage = data.get("storage"); if(data.containsKey("searchState")) searchState = data.get("searchState"); if (img.equals("")) img = ERROR_IMG; } public String getImg() { return img; } public String getTitle() { return title; } public String getAuthor() { return author; } public String getLibrary() { return location; } public String getLink() { return link; } public String getIsbn() { return isbn; } public String getPublish_year() { return publish_year; } public String getPublisher() { return publisher; } public String getLocation() { return location; } public String getStorage() { return storage; } public String getDetail() { if (searchState.equals("true")) return "書名 : "+title+"\n" +"作者 : "+author+"\n" +"ISBN : "+isbn+"\n" +"出版社 : "+publisher+"\n" +"出版年 : "+publish_year+"\n" +"館藏位置 : "+location+"\n" +"可借數量 : "+storage; else if (searchState.equals("false") || searchState.equals("Pending!")) return "搜尋詳細資訊中..."; else if (searchState.equals("null")) return NULL_TITLE; else return "Error!!! State : "+searchState; } public boolean isNull() { return searchState == "null"; } public String getSearchState() { return searchState; } } <file_sep>/app/src/main/java/com/writerwriter/libraassist/NotificationUnit.java package com.writerwriter.libraassist; /** * Created by Larry on 2017/12/31. */ public class NotificationUnit { private String title; private String left_days; private String location; public NotificationUnit(String title, String left_days, String location) { this.title = title; this.left_days = left_days; this.location = location; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getLeft_days() { return left_days; } public void setLeft_days(String left_days) { this.left_days = left_days; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } } <file_sep>/app/src/main/java/com/writerwriter/libraassist/InitAlarmReceiver.java package com.writerwriter.libraassist; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.Toast; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; public class InitAlarmReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { List<BorrowBookUnit> allbooklist; allbooklist = AccountManager.Instance.borrowBookList; for(int i=0;i<allbooklist.size();i++) { BorrowBookUnit borrowBookUnit = allbooklist.get(i); SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy/MM/dd"); SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd"); Date cur = new Date(System.currentTimeMillis()); Date return_date = cur; //initial if(borrowBookUnit.getReturn_time().matches("[0-9]+/[0-9]+/[0-9]+")){ try { return_date = dateFormat1.parse(borrowBookUnit.getReturn_time()); }catch (ParseException e){ e.printStackTrace(); } } else if(borrowBookUnit.getReturn_time().matches("[0-9]+-[0-9]+-[0-9]+")){ try{ return_date = dateFormat2.parse(borrowBookUnit.getReturn_time()); }catch (ParseException e){ e.printStackTrace(); } } long left_time_millis = return_date.getTime() - cur.getTime(); int left_time_days =(int)(left_time_millis / 1000 / 60 / 60 / 24); if(left_time_days > 0 && left_time_days <= 7){ Intent intent2 = new Intent(); intent2.setClass(context,AlarmReceiver.class); intent2.putExtra("title",borrowBookUnit.getBook_name()); intent2.putExtra("time",left_time_days); PendingIntent pending1 = PendingIntent.getBroadcast(context,i * 3,intent,PendingIntent.FLAG_CANCEL_CURRENT); PendingIntent pending2 = PendingIntent.getBroadcast(context,i * 3 + 1,intent,PendingIntent.FLAG_CANCEL_CURRENT); PendingIntent pending3 = PendingIntent.getBroadcast(context,i * 3 + 2,intent,PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager alarm = (AlarmManager) context.getSystemService(context.ALARM_SERVICE); //書本要到期的前三天會通知 alarm.set(AlarmManager.RTC_WAKEUP, return_date.getTime()-3*24*60*60*60,pending1); alarm.set(AlarmManager.RTC_WAKEUP, return_date.getTime()-2*24*60*60*60,pending2); alarm.set(AlarmManager.RTC_WAKEUP, return_date.getTime()-1*24*60*60*60,pending3); } } } } <file_sep>/app/src/main/java/com/writerwriter/libraassist/TagUnit.java package com.writerwriter.libraassist; /** * Created by Larry on 2017/12/24. */ public class TagUnit { private String tag_text; private String tag_pages; public TagUnit() { } public TagUnit(String tag_text, String tag_pages) { this.tag_text = tag_text; this.tag_pages = tag_pages; } public String getTag_text() { return tag_text; } public void setTag_text(String tag_text) { this.tag_text = tag_text; } public String getTag_pages() { return tag_pages; } public void setTag_pages(String tag_pages) { this.tag_pages = tag_pages; } } <file_sep>/app/src/main/java/com/writerwriter/libraassist/BorrowBookAdapter.java package com.writerwriter.libraassist; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; /** * Created by Larry on 2017/12/28. */ public class BorrowBookAdapter extends RecyclerView.Adapter<BorrowBookAdapter.ViewHolder> { private List<BorrowBookUnit> borrowBookUnitList; private Context mContext; public static class ViewHolder extends RecyclerView.ViewHolder{ public TextView borrow_book_title; public TextView borrow_book_author; public TextView borrow_book_location; public TextView borrow_book_search_number; public TextView borrow_book_borrow_time; public TextView borrow_book_return_time; public TextView borrow_book_waiting_people_number; public TextView borrow_book_renew_count; public ViewHolder(View itemView){ super(itemView); borrow_book_title = (TextView) itemView.findViewById(R.id.borrow_book_title); borrow_book_author = (TextView) itemView.findViewById(R.id.borrow_book_author); borrow_book_location = (TextView) itemView.findViewById(R.id.borrow_book_location); borrow_book_search_number = (TextView) itemView.findViewById(R.id.borrow_book_search_number); borrow_book_borrow_time = (TextView) itemView.findViewById(R.id.borrow_book_borrow_time); borrow_book_return_time = (TextView) itemView.findViewById(R.id.borrow_book_return_time); borrow_book_waiting_people_number = (TextView) itemView.findViewById(R.id.borrow_book_waiting_people_number); borrow_book_renew_count = (TextView) itemView.findViewById(R.id.borrow_book_renew_count); } } public BorrowBookAdapter(List<BorrowBookUnit> borrowBookUnitList, Context mContext) { this.borrowBookUnitList = borrowBookUnitList; this.mContext = mContext; } @Override public int getItemCount() { return borrowBookUnitList.size(); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View borrow_book_list_view = LayoutInflater.from(mContext).inflate(R.layout.borrow_book_item,parent,false); BorrowBookAdapter.ViewHolder viewHolder = new BorrowBookAdapter.ViewHolder(borrow_book_list_view); return viewHolder; } @Override public void onBindViewHolder(ViewHolder holder, int position) { final BorrowBookUnit borrowBookUnit = borrowBookUnitList.get(position); holder.borrow_book_title.setText(borrowBookUnit.getBook_name()); holder.borrow_book_author.setText((""+borrowBookUnit.getAuthor()).equals("null")?"作者 : -":"作者 : "+borrowBookUnit.getAuthor()); holder.borrow_book_location.setText((""+borrowBookUnit.getLocation()).equals("null")?"館藏地 : -":"館藏地 : "+borrowBookUnit.getLocation()); holder.borrow_book_search_number.setText((""+borrowBookUnit.getSearch_book_number()).equals("null")?"索書號 : -":"索書號 : " + borrowBookUnit.getSearch_book_number()); holder.borrow_book_borrow_time.setText((""+borrowBookUnit.getBorrow_time()).equals("null")?"借閱日期 : -":"借閱日期 : "+borrowBookUnit.getBorrow_time()); holder.borrow_book_return_time.setText((""+borrowBookUnit.getReturn_time()).equals("null")?"應還日期 : -":"應還日期 : "+borrowBookUnit.getReturn_time()); holder.borrow_book_waiting_people_number.setText((""+borrowBookUnit.getWaiting_people_number()).equals("null")?"預約人數 : -":"預約人數 : "+borrowBookUnit.getWaiting_people_number()); holder.borrow_book_renew_count.setText((""+borrowBookUnit.getRenew_count()).equals("null")?"續借次數 : -":"續借次數 : "+borrowBookUnit.getRenew_count()); holder.itemView.setTag(position); } } <file_sep>/app/src/main/java/com/writerwriter/libraassist/LibraryInfoDetailFragment.java package com.writerwriter.libraassist; import android.app.PendingIntent; import android.content.Context; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.method.ScrollingMovementMethod; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import org.w3c.dom.Text; public class LibraryInfoDetailFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_library_info_detail, container, false); TextView info = (TextView) v.findViewById(R.id.library_detail_info); info.setMovementMethod(new ScrollingMovementMethod()); info.setTextColor(Color.BLACK); info.setTextSize(16); Bundle bundle = getArguments(); if(bundle != null){ int id = bundle.getInt("id",0); switch (id){ case 0: info.setText("關於本館\n" + "臺北大學圖書館 National Taipei University Library,係臺北大學的圖書資源服務者,眾所期盼的圖書資訊大樓已於 102年 11月 25日正式啟用營運。\n" + "\n" + " 圖書館館藏目前約有42萬冊圖書館藏(含圖書、視聽資料、電子書)、現有紙本期刊290種(不含贈刊)、本校紙本碩博士論文、參考資料等提供館內閱覽。\n" + " 電子資源檢索與使用:\n" + " 「電子資源總覽」(查詢特定資料庫使用):透過單一介面同時檢索153種資料庫、近6萬種電子期刊等數位館藏。(請參考「圖書館首頁」>「電子資源」項下)。\n" + " 「資源探索服務」:提供類google檢索功能,一鍵搜羅所有校內外相關文獻(含紙本館藏/期刊、資料庫、電子書、校外免費文獻),快速指引全文獲取途徑。\n" + " 其他電子資源:如本校電子碩博士論文、書目管理軟體(Endnote)、語言學習專區等(請參考「圖書館首頁」>「電子資源」項下各服務)。\n" + " 成員:除館長外,共有 19名館員工,提供圖書專業服務。\n" + " 提供數位化、多元化服務:\n" + " 圖書館網站、自助借書機、門禁系統、圖書資訊系統、空間座位管理系統等。\n" + " 館際互借服務與交流。\n" + " 客製化圖書館服務:導覽、教育訓練等。\n"); break; case 1: info.setText("開館資訊\n" + "\n" + "發佈館別:新北市圖(總館)\n" + "\n" + "發佈時間: 2017/12/12 | 最後修改時間: 2017/12/12\n" + "\n" + "開放時間:\n" + "\n" + "各館詳細開放時間請點選連結 新北市立圖書館各分館暨圖書閱覽室介紹\n" + "\n" + "休館時間:\n" + "\n" + "經政府公告之國定假日為休館日、每月最後一個星期四為清館日,不對外開放;其他休館日詳見以下「休館日一覽表」。\n" + "\n" + "2017 年 休館日一覽表\n" + "\n" + "板橋車站智慧圖書館春節期間照常開放 7:00-22:00\n" + "日期 \t星期 \t休館日說明\n" + "2017年1月1日 \t日 \t開國紀念日\n" + "2017年1月26日 \t四 \t調整定期休館日(調整開放時間為8:30am-5:00pm)\n" + "2017年1月27日 \t五 \t春節(除夕)\n" + "2017年1月28日 \t六 \t春節(初一)\n" + "2017年1月29日 \t日 \t春節(初二)\n" + "2017年1月30日 \t一 \t春節(初三)\n" + "2017年1月31日 \t二 \t調整開放時間為8:30am-5:00pm\n" + "2017年2月1日 \t三 \t調整開放時間為8:30am-5:00pm\n" + "2017年2月23日 \t四 \t定期休館日\n" + "2017年2月28日 \t二 \t和平紀念日\n" + "2017年3月30日 \t四 \t定期休館日\n" + "2017年4月4日 \t二 \t清明節\n" + "2017年4月27日 \t四 \t定期休館日\n" + "2017年5月25日 \t四 \t定期休館日\n" + "2017年5月30日 \t二 \t端午節\n" + "2017年6月29日 \t四 \t調整開放時間為8:30am-5:00pm\n" + "2017年7月27日 \t四 \t定期休館日\n" + "2017年8月31日 \t四 \t定期休館日\n" + "2017年9月28日 \t四 \t定期休館日\n" + "2017年10月4日 \t三 \t中秋節\n" + "2017年10月10日 \t二 \t國慶日\n" + "2017年10月26日 \t四 \t定期休館日\n" + "2017年11月30日 \t四 \t定期休館日\n" + "2017年12月28日 \t四 \t定期休館日\n" + "\n" + " \n" + "\n" + "(歡迎下載利用)新北市立圖書館2018休館日日曆檔(ics檔)\n" + "\n" + "2018休館日、調整放假日一覽表\n" + "日期 \t星期 \t休館日說明\n" + "2018年1月1日 \t一 \t開國紀念日\n" + "2018年1月25日 \t四 \t定期休館日\n" + "2018年2月15日 \t四 \t春節(除夕)\n" + "2018年2月16日 \t五 \t春節(初一)\n" + "2018年2月17日 \t六 \t春節(初二)\n" + "2018年2月18日 \t日 \t春節(初三)\n" + "2018年2月19日 \t一 \t調整開放時間至5:00pm\n" + "2018年2月20日 \t二 \t調整開放時間至5:00pm\n" + "2018年2月22日 \t四 \t定期休館日\n" + "2018年2月28日 \t三 \t和平紀念日\n" + "2018年3月29日 \t四 \t定期休館日\n" + "2018年4月4日 \t三 \t兒童節\n" + "2018年4月5日 \t四 \t清明節\n" + "2018年4月26日 \t四 \t定期休館日\n" + "2018年5月31日 \t四 \t定期休館日\n" + "2018年6月18日 \t一 \t端午節\n" + "2018年6月28日 \t四 \t調整開放時間至5:00pm\n" + "2018年7月26日 \t四 \t定期休館日\n" + "2018年8月30日 \t四 \t定期休館日\n" + "2018年9月24日 \t一 \t中秋節\n" + "2018年9月27日 \t四 \t定期休館日\n" + "2018年10月10日 \t三 \t國慶日\n" + "2018年10月25日 \t四 \t定期休館日\n" + "2018年11月29日 \t四 \t定期休館日\n" + "2018年12月27日 \t四 \t定期休館日\n" + "\n" + "依據「新北市立圖書館閱覽服務規則」,各館臨櫃申請借閱證及借、還書在閉館前30分鐘停止受理。"); break; case 2: info.setText("開館資訊\n" + "開館時間\n" + "\n" + " 週二至週六:8:30-21:00;\n" + " 週日、週一:9:00-17:00。\n" + "\n" + " 申請借閱證、領取預約書、規費繳納及臨櫃借、還書在閉館前30分鐘停止受理。\n" + "\n" + " 總館兒童室開放時間:\n" + " 週二至週六:9:00-18:00;\n" + " 週日、週一:9:00-17:00。\n" + "\n" + "\n" + " 智慧圖書館開放時間:\n" + " 西門智慧圖書館:每日上午6時至晚間12時\n" + " 松山機場智慧圖書館:每日上午6時至晚間12時\n" + " 太陽圖書館:每日上午8時30分至晚間9時\n" + " 百齡智慧圖書館:週一至週五:下午4時30分至9時\n" + "          週六、日及寒暑假:每日上午9時至晚間9時(國定假日不開放)\n" + " 福德智慧圖書館:每日上午9時至晚間9時(國定假日不開放)\n" + " 東區地下街智慧圖書館:每日上午6時至晚間12時\n" + " 古亭智慧圖書館:每日上午9時至晚間9時(國定假日不開放)\n" + "\n" + "\n" + " 啟明分館、柳鄉民眾閱覽室及親子美育數位圖書館開放時間:\n" + " 週一至週日:9:00-17:00。\n" + "\n" + " 公訓圖書站開放時間:\n" + " 一、週一至週五:8:30-17:00(申請借閱證及借、還書服務至16:30)。\n" + " 二、週六、日及國定假日休館。\n" + "\n" + " 士林分館臨時替代館(天文館)開放時間:\n" + " 週二至週日:早上9:00至下午5:00\n" + " 每週一、每月第一個星期四及國定假日固定休館\n" + "\n" + " 在開放時間內可自由進入館內閱覽,6歲以下兒童請由家長陪同。\n" + "\n" + " 經政府公告之放假日為休館日;每月第一個星期四為圖書整理清潔日,不對外開放。\n" + "\n" + " FastBook全自動借書站及借還書工作站開放時間依設置地點而定。\n" + "\n" + "\n" + "\n" + "休館日一覽表\n" + "\n" + " 2018-01-01(星期一,開國紀念日)\n" + " 2018-01-04(星期四,休館日)\n" + " 2018-02-01(星期四,休館日)\n" + " 2018-02-15~18(星期四~日,春節)\n" + " 2018-02-28(星期三,二二八紀念日)\n" + " 2018-03-01(星期四,休館日)\n" + " 2018-04-04(星期三,兒童節)\n" + " 2018-04-05(星期四,清明節)\n" + " 2018-05-03(星期四,休館日)\n" + " 2018-06-07(星期四,休館日)\n" + " 2018-06-18(星期一,端午節)\n" + " 2018-07-05(星期四,休館日)\n" + " 2018-08-02(星期四,休館日)\n" + " 2018-09-06(星期四,休館日)\n" + " 2018-09-24(星期一,中秋節)\n" + " 2018-10-04(星期四,休館日)\n" + " 2018-10-10(星期三,國慶日)\n" + " 2018-11-01(星期四,休館日)\n" + " 2018-12-06(星期四,休館日)"); break; } } return v; } } <file_sep>/app/src/main/java/com/writerwriter/libraassist/AlarmReceiver.java package com.writerwriter.libraassist; import android.app.NotificationManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.support.v4.app.NotificationCompat; import android.widget.Toast; /** * Created by Larry on 2017/12/31. */ public class AlarmReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { NotificationManager noMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); NotificationCompat.Builder builder = new NotificationCompat.Builder(context); builder.setSmallIcon(R.drawable.ic_settings) .setWhen(System.currentTimeMillis()) .setContentTitle(context.getString(R.string.app_name)) .setContentText("你借的書 : "+intent.getStringExtra("title")+" 即將在 "+intent.getIntExtra("time",1)+" 天後到期。"); noMgr.notify(intent.getIntExtra("id",0),builder.build()); } } <file_sep>/app/src/main/java/com/writerwriter/libraassist/NewBooksAdapter.java package com.writerwriter.libraassist; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.util.List; /** * Created by Larry on 2017/10/11. */ public class NewBooksAdapter extends BaseAdapter { private List<CollectionSearchResultUnit> newBooksList; private Context mContext; public NewBooksAdapter(List<CollectionSearchResultUnit> newBooksList, Context mContext) { this.newBooksList = newBooksList; this.mContext = mContext; } @Override public int getCount() { return newBooksList.size(); } @Override public Object getItem(int i) { return newBooksList.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { View rowView = view; if(rowView == null){ rowView = LayoutInflater.from(mContext).inflate(R.layout.layout_item,null); TextView name = rowView.findViewById(R.id.label); ImageView image = rowView.findViewById(R.id.image); //set data Picasso.with(mContext).load(newBooksList.get(i).getImg()).into(image); name.setText(newBooksList.get(i).getTitle()); } return rowView; } }
c21b2214f4c84b0bb5ace037998cd7435afd1284
[ "Java" ]
11
Java
samwu4166/LibraAssist
c9a2e417e5fd2d6998584ac8c4ddc0f3152596f5
4d2a2ea5faa0e2ce08e99cf21e7399246d64df0f
refs/heads/master
<file_sep><?php /** * Basic_MySqlManager_Service class file. * */ ClassLoader::loadServiceClass('basic.abstract'); /** * MySql connect exception */ class MySqlConnectException extends Exception {} /** * MySql query exception */ class MySqlQueryException extends Exception {} /** * MySql function descriptor */ class MySqlFunc { public $funcName = null; public function __construct($_funcName) { $this->funcName = $_funcName; } } /** * MySQL manager service * */ class Basic_MySqlManager_Service extends Basic_Abstract_Service { /** * @var resource Database server link */ private $link; /** * @var resource Query result resource */ private $result = false; /** * Constructor */ public function __construct() { $this->link = null; } /** * Destructor */ public function __destruct() { // Free last result and close the connection $this->freeResult(); $this->close(); } /** * Tells if MySQL connection has been established */ public function connected() { return !is_null($this->link); } /** * Performs connection to the database server */ public function connect($_hostName, $_userName, $_password, $_dbName) { // Connect $this->link = @mysql_connect($_hostName, $_userName, $_password); if ($this->link === false) throw new MySqlConnectException(mysql_error()); // Select database if (mysql_select_db($_dbName) === false) throw new MySqlConnectException(mysql_error()); // Set encoding & timezone $this->query('SET NAMES \'UTF8\''); if (defined('MYSQL_TIMEZONE')) $this->query('SET time_zone=\''.MYSQL_TIMEZONE.'\''); } /** * Closes the database server connection */ public function close() { if($this->link) { mysql_close($this->link); $this->link = null; } } /** * Accesses the ID generated from the previous INSERT operation * @return integer|boolean ID generated from the previous INSERT operation */ public function getInsertId() { return mysql_insert_id($this->link); } /** * Performs SQL query * @param string $_query SQL statemement */ public function query($_query) { // Free previous result $this->freeResult(); // Perform query $this->result = mysql_query($_query, $this->link); if ($this->result === false) throw new MySqlQueryException(mysql_error()); return $this; } /** * Frees the result */ public function freeResult() { if (is_resource($this->result)) { mysql_free_result($this->result); $this->result = null; } } /** * Extracts record as associative map * @return array Record */ public function fetchAssoc() { return mysql_fetch_assoc($this->result); } /** * Extracts record first column */ public function fetchColumn() { $result = mysql_fetch_assoc($this->result); if($result){ return reset($result); } return false; } /** * Extracts record * @param integer $_resultType Mapping type * @return array Record */ public function fetchArray($_resultType = MYSQL_BOTH) { return mysql_fetch_array($this->result, $_resultType); } /** * Extracts all records * @param integer $_resultType Mapping type * @return array Fetched records */ public function fetchAll($_resultType = MYSQL_ASSOC) { $records = array(); while ($record = mysql_fetch_array($this->result, $_resultType)) $records[] = $record; $this->freeResult(); return $records; } /** * Extracts all records * @param integer $_resultType Mapping type * @return array Fetched records */ public function fetchAllCellValue($_fieldKey, $_resultType = MYSQL_ASSOC) { $records = array(); while ($record = mysql_fetch_array($this->result, $_resultType)) $records[] = $record[$_fieldKey]; $this->freeResult(); return $records; } /** * Extracts all records as key-record map * @param string $_key Mapping key * @param integer $_resultType Mapping type * @return array Fetched records */ public function fetchAllAsMap($_key = 'id', $_resultType = MYSQL_ASSOC) { $records = array(); while ($record = mysql_fetch_array($this->result, $_resultType)) $records[$record[$_key]] = $record; $this->freeResult(); return $records; } /** * Extracts all records as key-value map * @param string $_keyFieldKey Field key whom value is to be a map key * @param string $_valueFieldKey Field key whom value is to be a map value * @return array */ public function fetchAllAsKeyValueMap($_keyFieldKey, $_valueFieldKey) { $records = array(); while ($record = mysql_fetch_array($this->result, MYSQL_ASSOC)) $records[$record[$_keyFieldKey]] = $record[$_valueFieldKey]; $this->freeResult(); return $records; } /** * Extracts all records as name by ID * @param array Records set to be extracted * @param integer $_resultType Mapping type */ public function fetchAllRecordsAsNameById(&$_records, $_resultType = MYSQL_BOTH) { $_records = array(); while ($record = mysql_fetch_array($this->result, $_resultType)) $_records[$record['id']] = $record['name']; $this->freeResult(); } /** * Accesses the number of records in the result * @return integer|boolean The number of records in the result or false if no result */ public function getRecordsCount() { return mysql_num_rows($this->result); } /** * Accesses the cell value * @param string Cell name * @return mixed Cell value on success, null otherwise */ public function fetchCellValue($_cellName) { $record = mysql_fetch_assoc($this->result); return $record !== false ? $record[$_cellName] : null; } /** * Accesses the number of affected rows * @return int Affected rows count */ public function getAffectedRows() { return mysql_affected_rows(); } /** * Executes insert query * @param string $_tableName Table name * @param array $_data Data */ public function insert($_tableName, $_data) { $query = 'INSERT INTO `'.$_tableName.'` SET '; foreach ($_data as $key => $value) { if (is_null($value)) $query .= '`'.$key.'` = NULL, '; elseif ($value instanceof MySqlFunc) $query .= '`'.$key.'`='.$value->funcName.'(),'; else $query .= '`'.$key.'` = \''.mysql_real_escape_string($value).'\', '; } $query = substr($query, 0, strlen($query)-2); $this->query($query); return $this; } /** * Executes insert query * @param string $_tableName Table name * @param array $_data Data */ public function insertMulti($_tableName, $_data) { $query = 'INSERT INTO `'.$_tableName.'` '; foreach ($_data as $dataKey => $dataValue) { foreach($dataValue as $key=>$value){ if (is_null($value)) $query .= '`'.$key.'` = NULL, '; elseif ($value instanceof MySqlFunc) $query .= '`'.$key.'`='.$value->funcName.'(),'; else $query .= '`'.$key.'` = \''.mysql_real_escape_string($value).'\', '; } } $query = substr($query, 0, strlen($query)-2); $this->query($query); return $this; } /** * WARNING: This function is deprecated, use insert instead * Inserts record * @param string $_tableName Table name * @param array $_data Data */ public function insertRecord($_tableName, $_data) { return $this->insert($_tableName, $_data); } /** * Executes UPDATE query * @param string $_tableName Table name * @param array $_data Data * @param string $_criteria Update criteria (condition) */ public function update($_tableName, $_data, $_criteria = '1') { $query = 'UPDATE `'.$_tableName.'` SET '; foreach ($_data as $key => $value) { if (is_null($value)) $query .= '`'.$key.'`=NULL,'; elseif ($value instanceof MySqlFunc) { $query .= '`'.$key.'`='.$value->funcName.'(),'; } else $query .= '`'.$key.'`=\''.mysql_real_escape_string($value).'\','; } $query = rtrim($query, ','); // Condition if (is_array($_criteria)) { $query .= ' WHERE 1'; foreach ($_criteria as $key => $value) { if (is_array($value)) { $query .= ' AND `'.$key.'` IN ('; foreach ($value as $valueItem) $query .= '\''.mysql_real_escape_string($valueItem).'\','; $query = trim($query, ','); $query .= ')'; } else $query .= ' AND `'.$key.'`=\''.mysql_real_escape_string($value).'\''; } } else $query .= ' WHERE '.$_criteria; return $this->query($query); } /** * Deletes records with specified criteria * @param string $_tableName Table name * @param string $_criteria Criteria (condition) */ public function delete($_tableName, $_criteria = '1') { $query = 'DELETE FROM `'.$_tableName.'`'; // Condition if (is_array($_criteria)) { $query .= ' WHERE 1'; foreach ($_criteria as $key => $value) { if (is_array($value)) { $query .= ' AND `'.$key.'` IN ('; foreach ($value as $valueItem) $query .= '\''.mysql_real_escape_string($valueItem).'\','; $query = trim($query, ','); $query .= ')'; } else $query .= ' AND `'.$key.'`=\''.mysql_real_escape_string($value).'\''; } } else $query .= ' WHERE '.$_criteria; $this->query($query); } /** * Executes START TRANSACTION query */ public function startTransaction() { $this->query('START TRANSACTION'); } /** * Executes ROLLBACK query */ public function rollback() { $this->query('ROLLBACK'); } /** * Executes COMMIT query */ public function commit() { $this->query('COMMIT'); } /** * Executes COUNT(*) query * @param string $_tableName Table name * @param string $_criteria Condition * @return integer Count value */ public function count($_tableName, $_criteria = '1') { $query = 'SELECT COUNT(*) AS `c` FROM `'.$_tableName.'`'; // Condition if (is_array($_criteria)) { $query .= ' WHERE 1'; foreach ($_criteria as $key => $value) { if (is_array($value)) { $query .= ' AND `'.$key.'` IN ('; foreach ($value as $valueItem) $query .= '\''.mysql_real_escape_string($valueItem).'\','; $query = trim($query, ','); $query .= ')'; } else { if (is_null($value)) $query .= ' AND `'.$key.'` IS NULL'; else $query .= ' AND `'.$key.'`=\''.mysql_real_escape_string($value).'\''; } } } else $query .= ' WHERE '.$_criteria; return (int) $this->query($query)->fetchCellValue('c'); } /** * Executes SUM(`field_key`) query * @param string $_tableName Table name * @param string $_fieldKey Field key to sum * @param string $_criteria Condition * @return integer Count value */ public function sum($_fieldKey, $_tableName, $_criteria = '1') { $query = 'SELECT SUM(`'.$_fieldKey.'`) AS `sum` FROM `'.$_tableName.'`'; // Condition if (is_array($_criteria)) { $query .= ' WHERE 1'; foreach ($_criteria as $key => $value) { if (is_array($value)) { $query .= ' AND `'.$key.'` IN ('; foreach ($value as $valueItem) $query .= '\''.mysql_real_escape_string($valueItem).'\','; $query = trim($query, ','); $query .= ')'; } else { if (is_null($value)) $query .= ' AND `'.$key.'` IS NULL'; else $query .= ' AND `'.$key.'`=\''.mysql_real_escape_string($value).'\''; } } } else $query .= ' WHERE '.$_criteria; return $this->query($query)->fetchCellValue('sum'); } /** * Executes MAX(`field_key`) query * @param string $_tableName Table name * @param string $_fieldKey Field key to sum * @param string $_criteria Condition * @return integer Max value */ public function max($_fieldKey, $_tableName, $_criteria = '1') { $query = 'SELECT MAX(`'.$_fieldKey.'`) AS `max` FROM `'.$_tableName.'`'; // Condition if (is_array($_criteria)) { $query .= ' WHERE 1'; foreach ($_criteria as $key => $value) { if (is_array($value)) { $query .= ' AND `'.$key.'` IN ('; foreach ($value as $valueItem) $query .= '\''.mysql_real_escape_string($valueItem).'\','; $query = trim($query, ','); $query .= ')'; } else { if (is_null($value)) $query .= ' AND `'.$key.'` IS NULL'; else $query .= ' AND `'.$key.'`=\''.mysql_real_escape_string($value).'\''; } } } else $query .= ' WHERE '.$_criteria; return $this->query($query)->fetchCellValue('max'); } /** * Executes SUM(`field_key`) query * @param string $_tableName Table name * @param string $_fieldKey Field key to sum * @param string $_criteria Condition * @return integer Count value */ public function sumOfProductions($_tableName, $_fieldKey1, $_fieldKey2, $_criteria = '1') { $query = 'SELECT SUM(`'.$_fieldKey1.'`*`'.$_fieldKey2.'`) AS `sum` FROM `'.$_tableName.'`'; // Condition if (is_array($_criteria)) { $query .= ' WHERE 1'; foreach ($_criteria as $key => $value) { if (is_array($value)) { $query .= ' AND `'.$key.'` IN ('; foreach ($value as $valueItem) $query .= '\''.mysql_real_escape_string($valueItem).'\','; $query = trim($query, ','); $query .= ')'; } else { if (is_null($value)) $query .= ' AND `'.$key.'` IS NULL'; else $query .= ' AND `'.$key.'`=\''.mysql_real_escape_string($value).'\''; } } } else $query .= ' WHERE '.$_criteria; return $this->query($query)->fetchCellValue('sum'); } /** * Executes COUNT(DISTINCT) query * @param string $_tableName Table name * @param string $_columnName Column name * @param string $_criteria Condition * @return integer Count value */ public function countDistinct($_tableName, $_columnName, $_criteria = '1') { return $this->query('SELECT COUNT(DISTINCT `'.$_columnName.'`) AS `c` FROM `'.$_tableName.'` WHERE '.$_criteria)->fetchCellValue('c'); } public function selectDistinct($_columnName, $_tableName, $_criteria = '1', $_order = null) { // Condition if (is_array($_criteria)) { $criteria = '1'; foreach ($_criteria as $key => $value) { if (is_array($value)) { $criteria .= ' AND `'.$key.'` IN ('; foreach ($value as $valueItem) $criteria .= '\''.mysql_real_escape_string($valueItem).'\','; $criteria = trim($criteria, ','); $criteria .= ')'; } else $criteria .= ' AND `'.$key.'`=\''.mysql_real_escape_string($value).'\''; } } else $criteria = $_criteria; // Compose query $query = 'SELECT DISTINCT `'.$_columnName.'` FROM `'.$_tableName.'` WHERE '.$criteria.''; // Order clause if (!empty($_order)) $query .= ' ORDER BY '.$_order; return $this->query($query); } public function countGroups($_select, $_tableName, $_groupColumnKey, $_criteria = '1') { return $this->query('SELECT '.$_select.', COUNT(*) AS `count` FROM `'.$_tableName.'` WHERE '.$_criteria.' GROUP BY `'.$_groupColumnKey.'`')->fetchAll(); } /** * Executes SELECT query * @param mixed $_select Select clause * @param string $_tableName Table name * @param string $_criteria Condtion * @param mixed $_order Order * @return array Extracted records */ public function select($_select, $_tableName, $_criteria = '1', $_order = null, $_limit = null, $_offset = null) { // Select clause $query = 'SELECT '; if (is_array($_select)) { foreach ($_select as $_fieldKey) $query .= '`'.$_fieldKey.'`,'; $query = trim($query, ','); } else $query .= $_select; // From clause $query .= ' FROM `'.$_tableName.'`'; // Condition if (is_array($_criteria)) { $query .= ' WHERE 1'; foreach ($_criteria as $key => $value) { if (is_array($value)) { $query .= ' AND `'.$key.'` IN ('; foreach ($value as $valueItem) $query .= '\''.mysql_real_escape_string($valueItem).'\','; $query = trim($query, ','); $query .= ')'; } else { if (is_null($value)) $query .= ' AND `'.$key.'` IS NULL'; else $query .= ' AND `'.$key.'`=\''.mysql_real_escape_string($value).'\''; } } } else $query .= ' WHERE '.$_criteria; // Order clause if (!empty($_order)) $query .= ' ORDER BY `'.$_order.'`'; // LIMIT clause if (!empty($_limit)) $query .= ' LIMIT '.$_limit; // OFFSET clause if (!empty($_offset)) $query .= ' OFFSET '.$_offset; // Execution return $this->query($query); } /** * Sets specified time zone * @param string UTC offset */ public function setTimeZone($_utcOffset) { $this->query('SET time_zone=\''.$_utcOffset.'\''); } /** * Get record [by specified criteria] * * @param string $_tableName Table name * @param int $_criteria Criteria * * @return array|boolean Record data as array or false if record is not found */ public function getRecord($_tableName, $_criteria = '1') { $query = 'SELECT * FROM `'.$_tableName.'`'; if (is_array($_criteria)) { $query .= ' WHERE 1'; foreach ($_criteria as $key => $value) { if (is_array($value)) { $query .= ' AND `'.$key.'` IN ('; foreach ($value as $valueItem) $query .= '\''.mysql_real_escape_string($valueItem).'\','; $query = trim($query, ','); $query .= ')'; } else $query .= ' AND `'.$key.'`=\''.mysql_real_escape_string($value).'\''; } } else $query .= ' WHERE '.$_criteria; return $this->query($query)->fetchAssoc(); } /** * Get record by ID * * @param string $_tableName Table name * @param int $_id Record ID * * @return array|boolean Record data as array or false if record is not found */ public function getRecordById($_tableName, $_id, $_order = null) { $query = 'SELECT * FROM `'.$_tableName.'` WHERE `id`='.$_id; if (!is_null($_order)) $query .= ' ORDER BY '.$_order; return $this->query($query)->fetchAssoc(); } /** * Get records * * @param string $_tableName Table name * @param string $_criteria Criteria (condition) * * @return array Array of records */ public function getRecords($_tableName, $_criteria = '1', $_order = null) { if (is_array($_criteria)) { $criteria = '1'; foreach ($_criteria as $key => $value) { if (is_array($value)) { $criteria .= ' AND `'.$key.'` IN ('; foreach ($value as $valueItem) $criteria .= '\''.mysql_real_escape_string($valueItem).'\','; $criteria = trim($criteria, ','); $criteria .= ')'; } else $criteria .= ' AND `'.$key.'`=\''.mysql_real_escape_string($value).'\''; } } else $criteria = $_criteria; $query = 'SELECT * FROM `'.$_tableName.'` WHERE '.$criteria; if (!is_null($_order)) $query .= ' ORDER BY '.$_order; return $this->query($query)->fetchAll(); } /** * Executes SELECT query * @param mixed $_select Select clause * @param mixed $_tableName Table name * @param string $_criteria Condtion * @param mixed $_order Order * @return array Extracted records */ public function mixedselectDistinct($_select, $_tableName, $_criteria = '1', $_order = null, $_limit = null, $_offset = null) { // Select clause $query = 'SELECT DISTINCT '; if (is_array($_select)) { foreach ($_select as $_fieldKey) $query .= '`'.$_fieldKey.'`,'; $query = trim($query, ','); } else $query .= $_select; // From clause $query .= ' FROM '; if (is_array($_tableName)) { foreach ($_tableName as $_fieldKey1) $query .= '`'.$_fieldKey1.'`,'; $query = trim($query, ','); } else $query .= '`'.$_tableName.'`'; // Condition if (is_array($_criteria)) { $query .= ' WHERE 1'; foreach ($_criteria as $key => $value) { if (is_array($value)) { $query .= ' AND `'.$key.'` IN ('; foreach ($value as $valueItem) $query .= '\''.mysql_real_escape_string($valueItem).'\','; $query = trim($query, ','); $query .= ')'; } else { if (is_null($value)) $query .= ' AND `'.$key.'` IS NULL'; else $query .= ' AND `'.$key.'`=\''.mysql_real_escape_string($value).'\''; } } } else $query .= ' WHERE '.$_criteria; // Order clause if (!empty($_order)) $query .= ' ORDER BY `'.$_order.'`'; // LIMIT clause if (!empty($_limit)) $query .= ' LIMIT '.$_limit; // OFFSET clause if (!empty($_offset)) $query .= ' OFFSET '.$_offset; // Execution return $this->query($query); } } ?><file_sep><?php /** * Basic_Abstract_Builder class file. * */ /** * Abstract builder */ abstract class Basic_Abstract_Builder { /** * General build routine * @param array $_params Array of parameters * @return AbstractModel Built data model */ public function get(array $_params = array()) { $modelClassName = str_replace('_Builder', '_Model', get_class($this)); return new $modelClassName($_params); } public function getByRequest(Request $_request = null) { $modelClassName = str_replace('_Builder', '_Model', get_class($this)); return new $modelClassName(array()); } /** * Debug purpose */ protected function _varDumpExit($_arg) { echo '<pre>'; var_dump($_arg); exit(); } /** */ protected function _simpleXmlLoadFileRetriable($_filename) { $tries = 1; while (!($xmlObject = @simplexml_load_file($_filename)) and (XML_LOAD_MAX_TRIES_NUM==0 or $tries++ < XML_LOAD_MAX_TRIES_NUM)) sleep(XML_LOAD_DELAY); return $xmlObject; } } ?><file_sep><?php /** * Asynchronous action exception * */ class AsyncActionException extends Exception {} class AsyncActionSessionExpireException extends Exception {} class AsyncActionAuthException extends Exception {} ?><file_sep><?php /** * Dictionary * */ final class Dictionary { /** * Instance holder * @var Dictionary */ private static $instance = null; /** * Words container * @var array */ private $words; /** * Prevent direct object creation */ private function __construct() { $this->words = array(); } /** * Prevent to clone the instance */ private function __clone() {} /** * Instance creator/accessor */ public function getInstance() { if (self::$instance === null) self::$instance = new Dictionary(); return self::$instance; } /** * Loads words */ public function loadWords($_dicFilename) { // Compose dictionary file name if (!file_exists($_dicFilename)) throw new Exception('Failed to load dictionary file.'); // Parse dictionary file $this->words = parse_ini_file($_dicFilename); } /** * Acsesse the word by key * @param string Key */ public function getWord($_key) { return $this->words[$_key]; } } ?><file_sep><?php /** * Application class file. * */ /** * Request * */ class Request { /** * @var string Hostname */ private $hostname = null; /** * @var integer Domain ID */ private $domainId = null; /** * @var string URL */ private $url = null; /** * $var string Method ('GET' or 'POST') */ private $method; /** * @var string Referrer */ private $referrer; /** * @var array Parameters */ private $params = array(); /** * Constructor */ public function __construct($_server, $_request) { $this->hostname = $_server['HTTP_HOST']; // Resolve domain ID $mySqlManager = Application::getService('basic.mysqlmanager'); if (substr($this->hostname, strlen($this->hostname)-strlen(MAIN_DOMAIN)) == MAIN_DOMAIN) { $subDomainName = substr($this->hostname, 0, strpos($this->hostname, '.')); $this->domainId = (int) $mySqlManager->select('id', 'domains', array('name' => $subDomainName))->fetchCellValue('id'); } else $this->domainId = (int) $mySqlManager->select('id', 'domains', array('domain' => $this->hostname))->fetchCellValue('id'); $this->url = ($url = substr($_server['REQUEST_URI'], 1)) ? $url : ''; $this->method = $_server['REQUEST_METHOD']; $this->params = $_request; $this->referrer = array_key_exists('HTTP_REFERER', $_server) ? $_server['HTTP_REFERER'] : null; } /** * Acceses the Hostname * @return string Hostname */ public function getHostname() { return $this->hostname; } /** * Accesses the Domain ID * @return integer Domain ID */ public function getDomainId() { return $this->domainId; } /** * Accesses the URL * @param boolean Indicates if URL params should be included * @return string request URL */ public function getUrl($_truncateUrlParams = true) { if ($_truncateUrlParams) { $p = strpos($this->url, '?'); if ($p === false) return $this->url; else return substr($this->url, 0, $p); } else return $this->url; } /** * Accesses the query string */ public function getQueryString() { return $_SERVER['QUERY_STRING']; } /** * Accesses the URL token on specified position * @param integer $position URL token position * @return string URL token if $_position valid, empty string otherwise */ public function getUrlToken($_position) { $tokens = explode('/', $this->url); return array_key_exists($_position, $tokens) ? $tokens[$_position] : ''; } /** * Accesses the method * @return string Request method */ public function getMethod() { return $this->method; } /** * Accesses the referrer * @return string Referrer */ public function getReferrer() { return $this->referrer; } /** * Tells if parameter with specified key exists * @param string $_key Parameter key * @return boolean True if parameter exists, false otherwise */ public function paramExists($_key) { return array_key_exists($_key, $this->params); } /** * Accesses the parameter value * @param string $_key Parameter key * @return string Parameter value */ public function getParamValue($_key) { return $this->params[$_key]; } /** * Accesses the parameter value by key if it exists * @param string $_key Parameter key * @param mixed $_defaultValue Default parameter value * @return mixed Parameter value if it exists, $_defaultValue otherwise */ public function getParamValueIfExists($_key, $_defaultValue = '') { return $this->paramExists($_key) ? $this->getParamValue($_key) : $_defaultValue; } /** * Accesses the params */ public function getParams() { return $this->params; } } ?><file_sep><?php /** * Viewer class file. * */ /** * Viewer * */ class Viewer { /** * Renders model with specified view * @param AbstractModel $_model Data model to be rendered * @param string $_viewRef View reference in form of <module_name>.<view_name> * @param array $_params Additional optional parameters */ static public function render($_model, $_viewRef, array $_params = array()) { list ($moduleName, $viewName) = explode('.', $_viewRef); require(MODULES_DIR_PATH.$moduleName.'/views/'.$viewName.'.htm'); } /** * Renders model with specified XML view * @param string $_resolvedViewName View name in form of <module_name>.<view_name> * @param AbstractModel $_model Data model to be rendered * @param array $_params Additional parameters */ static public function renderXml($_resolvedViewName, $_model, array $_params = array()) { list ($moduleName, $viewName) = explode('.', $_resolvedViewName); echo '<?xml version="1.0" encoding="UTF-8"?>'."\n"; require(DOCUMENT_ROOT.MODULES_PATH.$moduleName.'/'.VIEWS_PATH.$viewName.'.xml'); } /** * Resolves URL * @param $_unresolvedUrl Unresolved URL * @return string Resolved URL */ static public function resolveUrl($_unresolvedUrl) { //return HTTP_HOSTNAME.(MULTILINGUAL ? $router->getLang().'/' : '').$_unresolvedUrl; return HTTP_HOSTNAME.SITE_PATH.$_unresolvedUrl; } /** * Resolves style (css-file) URL * @param $_styleRef Style reference in form of <module_name>.<style_name> * @return string Resolved style (css-file) URL */ static public function resolveStyleUrl($_styleRef) { list ($moduleName, $styleName) = explode('.', $_styleRef); return MODULES_DIR_URL.$moduleName.'/styles/'.$styleName.'.css'; } /** * Resolves script (js-file) URL * @param $_scriptRef Script reference in form of <module_name>.<script_name> * @return string Resolved script (js-file) URL */ static public function resolveScriptUrl($_scriptRef) { list ($moduleName, $scriptName) = explode('.', $_scriptRef); return MODULES_DIR_URL.$moduleName.'/scripts/'.$scriptName.'.js'; } /** * Resolves plugin script (js-file) URL * @param $_scriptRef Script reference * @return string Resolved script (js-file) URL */ static public function resolvePluginScriptUrl($_scriptRef) { list ($pluginName, $scriptName) = explode('.', $_scriptRef); return PLUGINS_DIR_URL.$pluginName.'/'.$scriptName.'.js'; } /** * Resolves plugin style (css-file) URL * @param $_styleRef Style reference * @return string Resolved style (css-file) URL */ static public function resolvePluginStyleUrl($_styleRef) { list ($pluginName, $styleName) = explode('.', $_styleRef); return PLUGINS_DIR_URL.$pluginName.'/'.$styleName.'.css'; } } ?><file_sep><?php // Load abstract action ClassLoader::loadAsyncActionClass('basic.abstract'); class Googlemaps_GetUser_AsyncAction extends Basic_Abstract_AsyncAction { /** * Performs the action */ public function perform($_domainId = null, array $_params = array()) { $mySql = Application::getService('basic.mysqlmanager'); // Extract inputs $id = $this->_getString('id', $_params, false); $user = $mySql->getRecord('google_maps_users', array('id' => $id)); $this->data['user'] = $user; } } ?><file_sep><?php abstract class Basic_Abstract_AsyncAction { /** * @var array Data */ protected $data = array(); /** * @var array Errors */ protected $errors = array(); /** * @var string Redirect URL */ protected $redirectUrl = null; /** * Performs the action * @param Request Request object */ abstract public function perform($_domainId = null, array $_params = array()); /** * Accesses the data * @return array Data */ public function getData() { return $this->data; } /** * Accesses the errors * @return array Errors */ public function getErrors() { return $this->errors; } /** * Accesses the redirect URL * @return string Redirect URL */ public function getRedirectUrl() { return $this->redirectUrl; } /** */ protected function getFromArray($_key, $_array, $_default = null) { return isset($_array[$_key]) ? $_array[$_key] : $_default; } /** * Sends mail */ public function mail($_to, $_subject, $_message, $_headers = null) { if (MAIL) mail($_to, $_subject, $_message, $_headers); if (LOG_MAIL_TO_FILE) $this->logMail($_to, $_subject, $_message, $_headers); } /** * Logs mail data to a file */ public function logMail($_to, $_subject, $_message, $_headers, $_attachment = array()) { $logFilename = 'logs/mail.log'; $logFile = fopen($logFilename, 'ab'); fwrite($logFile, "\r\n".date('Y-m-d H:i:s')."\r\n"."\r\n"); fwrite($logFile, 'Headers: '.$_headers."\r\n"); if (is_array($_to)) fwrite($logFile, 'To: '.implode(',', $_to)."\r\n"); else fwrite($logFile, 'To: '.$_to."\r\n"); fwrite($logFile, 'Subject: '.$_subject."\r\n"); if (count($_attachment)) fwrite($logFile, 'Attachment: \''.implode('\', \'', $_attachment).'\''."\r\n"); fwrite($logFile, 'Message: '."\r\n".$_message."\r\n"."\r\n"); fclose($logFile); } /** * Add tags around all hyperlinks in $string */ public function plainToHtmlHyperlinks($_string) { // $result = preg_replace( // "/(?<![\>https?:\/\/|href=\"'])(?<http>(https?:[\/][\/]|www\.)([a-z]|[A-Z]|[0-9]|[\-\/.&?=_]|[~])*)/", // "<a href=\"$1\" target=\"_blank\">$1</a>", // $_string // ); $result = preg_replace( "/(?<![\>https?:\/\/|href=\"'])(?<http>(https?:[\/][\/]|www\.)([a-z]|[A-Z]|[0-9]|[\-\/.&?=_]|[~])*)/", "$1", $_string ); if (substr($result, 0, 3) == 'www') { $result = 'http://'.$result; $result = "<a href=\"$result\" target=\"_blank\">$result</a>"; } return $result; } /** * Add tags around all email addresses in $string */ public function plainToHtmlEmails($_string) { return preg_replace( "/([^@\s]*@[^@\s]*\.[^@\s]*)/", "<a href=\"mailto:$1\">$1</a>", $_string ); } /** * Replace all line feeds with HTML '<br />' tag */ public function plainToHtmlLineFeeds($_string) { $tmp = $_string; $tmp = str_replace("\r\n", '<br />', $tmp); $tmp = str_replace("\n", '<br />', $tmp); $tmp = str_replace("\r", '<br />', $tmp); return $tmp; } /** * Removes all spaces and replaces them with the specified delimiter */ public function removeSpaces($_emails, $_delimiter = ',') { $emails = str_replace(array("\r\n", "\n", "\r", "\t"), ' ', $_emails); do { $emails = str_replace(' ', ' ', $emails, $c); } while ($c); $emails = trim($emails); $emails = str_replace(' ', $_delimiter, $emails); return $emails; } /** * Returns current datetime */ public function dateNow() { return date('Y-m-d H:i:s'); } /** * Exports data to the xls-file */ protected function exportToXls($_exportFilename, $_fields, $_records = array()) { // Create PHPExcel object require_once(LIBS_DIR_PATH.'PHPExcel-1.7.9/PHPExcel.php'); $objPHPExcel = new PHPExcel(); $objPHPExcel->getProperties()->setCreator('VOS Backend Application'); $activeSheet = $objPHPExcel->setActiveSheetIndex(0); // Put fields for ($i = 0, $col = 'A'; $i < count($_fields); ++$i, ++$col) $activeSheet->setCellValue($col.'1', $_fields[$i]); // Put records $row = 1; foreach ($_records as $record) { $row += 1; $col = 'A'; foreach ($record as $cell) $activeSheet->setCellValue($col++.$row, $cell); } // Dump data $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); $objWriter->save($_exportFilename); } /** * Exports data as xls-file to a browser */ protected function exportAsXlsToBrowser($_exportFilename, $_fields, $_records = array()) { set_time_limit(0); ini_set('memory_limit', '512M'); // Set header header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="'.$_exportFilename.'"'); header('Cache-Control: max-age=0'); // If you're serving to IE 9, then the following may be needed header('Cache-Control: max-age=1'); // If you're serving to IE over SSL, then the following may be needed header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified header('Cache-Control: cache, must-revalidate'); // HTTP/1.1 header('Pragma: public'); // HTTP/1.0 // Send data to browser $this->exportToXls('php://output', $_fields, $_records); } /** * Reads xls-file */ protected function readFromXls($_filename, $_params = array()) { // This is due to PHPExcel produces PHP Notices and Warnings if provided file is cvs or other non-valid type $errorReporting = error_reporting(E_ERROR); // Extract params $startRowIndex = $this->getFromArray('startRowIndex', $_params, 1); $columnsNumber = $this->getFromArray('columnsNumber', $_params, 3); // Read file require_once(LIBS_DIR_PATH.'PHPExcel-1.7.9/PHPExcel.php'); $phpExcelInput = PHPExcel_IOFactory::load($_filename); $phpExcelInputSheet = $phpExcelInput->getActiveSheet(); $records = array(); for ($rowIndex = $startRowIndex; $rowIndex <= $phpExcelInputSheet->getHighestRow(); ++$rowIndex) { $record = array(); $empty = true; for ($columnIndex = 0; $columnIndex < $columnsNumber; ++$columnIndex) { $cell = trim($phpExcelInputSheet->getCellByColumnAndRow($columnIndex, $rowIndex)->getValue()); $record[] = $cell; $empty = $empty && empty($cell); } if (!$empty) $records[] = $record; } error_reporting($errorReporting); return $records; } protected function getMailTextFromString($_messageTemplate, $_lookups) { // Replace placeholders with corresponsing values $placeholders = array(); $values = array(); $matches = null; preg_match_all('/<!!(.+)!!>/U', $_messageTemplate, $matches); for ($i = 0; $i < count($matches[0]); ++$i) { $placeholder = $matches[0][$i]; if (!in_array($placeholder, $placeholders)) { $placeholders[] = $placeholder; $ref = $matches[1][$i]; unset($internalLookup); if ($ref{0} == '{') // Internal lookup { $tmp = trim($ref, ' '); $tmp = substr($tmp, 1, strlen($tmp)-2); list($ref, $lookupStr) = explode(':', $tmp, 2); $lookupStr = trim($lookupStr, ' '); $internalLookup = json_decode($lookupStr, true); } $value = null; if (strpos($ref, '.')) list ($lookupKey, $propertyKey) = explode('.', $ref); else list ($lookupKey, $propertyKey) = array('', $ref); if ($lookupKey == 'appConfig') $value = constant($propertyKey); elseif (isset($_lookups[$lookupKey][$propertyKey])) $value = $_lookups[$lookupKey][$propertyKey]; else $value = ''; if (isset($internalLookup)) $value = $internalLookup[$value]; $values[] = $value; } } return str_replace($placeholders, $values, $_messageTemplate); } protected function verifyCaptcha(array $_params = array()) { $sessionCaptcha = $this->getFromArray('captcha', $_SESSION, null); if (empty($sessionCaptcha)) { $this->errors['captcha'] = 'Verification code has not been generated.'; throw new AsyncActionException('Verification code has not been generated.'); } $captcha = $this->getFromArray('captcha', $_params, null); if (empty($captcha)) { $this->errors['captcha'] = 'Please, enter verification code.'; throw new AsyncActionException('Please, enter verification code.'); } if ($sessionCaptcha != $captcha) { $this->errors['captcha'] = 'You have entered the code incorrectly - please try again.'; throw new AsyncActionException('You have entered the code incorrectly - please try again.'); } } protected function _getPositiveInteger($_key, $_params, $_required = false, $_default = null) { $value = isset($_params[$_key]) ? $_params[$_key] : $_default; if (is_null($value)) { if ($_required) throw new AsyncActionException('Missing required argument: \''.$_key.'\'.'); } else // not null { if (filter_var($value, FILTER_VALIDATE_INT, array('options' => array('min_range' => 1))) === false) throw new AsyncActionException('Invalid argument (\''.$_key.'\'). Must be positive integer.'); } return $value; } protected function _getPositiveFloat($_key, $_params, $_required = false, $_default = null) { $value = isset($_params[$_key]) ? $_params[$_key] : $_default; if (is_null($value)) { if ($_required) throw new AsyncActionException('Missing required argument: \''.$_key.'\'.'); } else // not null { if (filter_var($value, FILTER_VALIDATE_FLOAT, array('options' => array('min_range' => 1))) === false) throw new AsyncActionException('Invalid argument (\''.$_key.'\'). Must be positive float.'); } return $value; } protected function _getNonNegativeInteger($_key, $_params, $_required = false, $_default = null) { $value = isset($_params[$_key]) ? $_params[$_key] : $_default; if (is_null($value)) { if ($_required) throw new AsyncActionException('Missing required argument: \''.$_key.'\'.'); } else // not null { if (filter_var($value, FILTER_VALIDATE_INT, array('options' => array('min_range' => 0))) === false) throw new AsyncActionException('Invalid argument (\''.$_key.'\'). Must be positive integer.'); } return $value; } protected function _getBoolean($_key, $_params, $_required = false, $_default = null) { $value = isset($_params[$_key]) ? $_params[$_key] : $_default; if (is_null($value)) { if ($_required) throw new AsyncActionException('Missing required argument: \''.$_key.'\'.'); } else // not null { if (filter_var($value, FILTER_VALIDATE_INT, array('options' => array('min_range' => 0, 'max_range' => 1))) === false) throw new AsyncActionException('Invalid argument (\''.$_key.'\'). Must be boolean (0 or 1).'); } return $value; } protected function _getString($_key, $_params, $_required = false, $_default = null, $_options = null) { $label = isset($_options['label']) ? $_options['label'] : $_key; $value = isset($_params[$_key]) ? $_params[$_key] : $_default; if (!isset($_options['no_trim'])) $value = trim($value); if ($_required and (is_null($value) or $value == '')) throw new AsyncActionException($label.' is required.'); if (isset($_options['max_length']) and strlen($value) > $_options['max_length']) throw new AsyncActionException($label.' is too long.'); return $value; } protected function _getArray($_key, $_params, $_required = false, $_default = null) { $value = isset($_params[$_key]) ? $_params[$_key] : $_default; if (is_null($value)) { if ($_required) throw new AsyncActionException('Missing required argument: \''.$_key.'\'.'); } else // not null { if (!is_array($value)) throw new AsyncActionException('Invalid argument (\''.$_key.'\'). Must be array.'); } return $value; } protected function _deleteFile($_filePath) { if (file_exists($_filePath)) unlink($_filePath); } /** * Debug purpose */ protected function _varDumpExit($_arg) { echo '<pre>'; var_dump($_arg); exit(); } /** * Get image size */ protected function _getImageSize($_src = false) { $size = array('width' => 200, 'height' => null); // Default image size if ($_src) { $imageFilename = '.'.$_src; if (file_exists($imageFilename)) { $tmp = getimagesize($imageFilename); if ($tmp) $size = array('width' => $tmp[0], 'height' => $tmp[1]); } } return $size; } /** * create Thumb from video */ protected function _createThumb($src, $dest, $width, $height, $quality) { if (!file_exists($src)) { //echo('Source file isn\'t exists'); return false; } $size = getimagesize($src); if ($size === false) { //echo('Cannot get image info about source'); return false; } $format = strtolower(substr($size['mime'], strpos($size['mime'], '/')+1)); $icfunc = "imagecreatefrom" . $format; if (!function_exists($icfunc)) { echo('Does not exists the function in GD to create image - "'. $icfunc. '"'); return false; } $x_ratio = $width / $size[0]; $y_ratio = $height / $size[1]; $ratio = min($x_ratio, $y_ratio); $use_x_ratio = ($x_ratio == $ratio); $new_width = $use_x_ratio ? $width : floor($size[0] * $ratio); $new_height = !$use_x_ratio ? $height : floor($size[1] * $ratio); $isrc = $icfunc($src); $idest = imagecreatetruecolor($new_width, $new_height); // imagefill($idest, 0, 0, $rgb); imagecopyresampled($idest, $isrc, 0, 0, 0, 0, $new_width, $new_height, $size[0], $size[1]); imagejpeg($idest, $dest, $quality); imagedestroy($isrc); imagedestroy($idest); return array('width' => $new_width, 'height' => $new_height); } } ?><file_sep><?php /** * Basic_Abstract_Model class file. */ /** * Abstract model * */ abstract class Basic_Abstract_Model { /** * Constructor * @param array $_params Parameters */ public function __construct(array $_params = array()) { foreach ($_params as $key => $value) { if (!property_exists($this, $key)) throw new Exception('Model property \''.get_class($this).'::'.$key.'\' does not exists.'); $this->$key = $value; } } } ?><file_sep><?php /** * Class loader * */ final class ClassLoader { /** * Loads core class * @param string $_className Class name to be loaded */ public static function loadCoreClass($_className) { $filename = CORE_DIR_PATH.$_className.'.php'; if (file_exists($filename)) require_once($filename); else throw new Exception('Core class does not exists (\''.$filename.'\').'); } /** * Loads builder class * @param string $_builderRef Builder reference in form of <module_key>.<builder_key> */ public static function loadBuilderClass($_builderRef) { list($moduleKey, $builderKey) = explode('.', $_builderRef); $filename = MODULES_DIR_PATH.$moduleKey.'/builders/'.$builderKey.'.php'; if (!file_exists($filename)) throw new Exception('Failed to load builder class (\''.$_builderRef.'\').'); require_once($filename); } /** * Loads service class * @param string $_serviceRef Service reference in form of <module_key>.<builder_key> */ public static function loadServiceClass($_serviceRef) { list($moduleKey, $serviceKey) = explode('.', $_serviceRef); $filename = MODULES_DIR_PATH.$moduleKey.'/services/'.$serviceKey.'.php'; if (!file_exists($filename)) throw new Exception('Failed to load service class (\''.$_serviceRef.'\').'); require_once($filename); } /** * Loads model class * @param string $_modelRef Model reference in form of <module_key>.<model_key> */ public static function loadModelClass($_modelRef) { list($moduleKey, $modelKey) = explode('.', $_modelRef); $filename = MODULES_DIR_PATH.$moduleKey.'/models/'.$modelKey.'.php'; if (!file_exists($filename)) throw new Exception('Failed to load model class (\''.$_modelRef.'\').'); require_once($filename); } /** * Loads async action class * @param string $_actionRef Action reference in form of <module_key>.<action_key> */ public static function loadAsyncActionClass($_actionRef) { list($moduleKey, $actionKey) = explode('.', $_actionRef); $filename = MODULES_DIR_PATH.$moduleKey.'/async/'.$actionKey.'.php'; if (!file_exists($filename)) throw new Exception('Failed to load async action class (\''.$_actionRef.'\').'); require_once($filename); } } ?><file_sep><?php // Load abstract action ClassLoader::loadAsyncActionClass('basic.abstract'); class Googlemaps_CreateUser_AsyncAction extends Basic_Abstract_AsyncAction { /** * Performs the action */ public function perform($_domainId = null, array $_params = array()) { $mySql = Application::getService('basic.mysqlmanager'); // Extract inputs $errorFlag = false; $errormessagearray = array(); $data = $this->_getArray('data', $_params, true); $nameStr = $data['name']; $nameStr = trim($nameStr); $nameStr = preg_replace("/\s{2,}/"," ",$nameStr); $nameArr = preg_split('/ /', $nameStr); foreach ($nameArr as $key => $name) { $nameValid = preg_match('/^[A-Za-zА-Яа-я]+$/msiu', $name); if (!$nameValid) { $errorFlag = true; $errormessagearray['name'] = 'Vvedite korrektno name!'; } } $addressStr = trim($data['address']); $addressStr = str_replace(',', ' ', $addressStr); $addressStr = preg_replace("/\s{2,}/"," ",$addressStr); $addressArr = preg_split('/ /', $addressStr); $addressArrLenght = count($addressArr); $index = $addressArr[0]; $country = $addressArr[1]; // var_dump($country);exit(); $city = $addressArr[2]; foreach ($addressArr as $key2 => $value2) { if (($key2>2) and ($key2<$addressArrLenght-1)) { $street.= ' '.$value2; } } $street = trim($street); $house = $addressArr[$addressArrLenght-1]; $indexValid = preg_match("/[0-9]{5}/i", $index); if (!$indexValid) { $errorFlag = true; $errormessagearray['address'] = 'Vvedite korrektno index!'; } $countryValid = preg_match('/^[A-Za-zА-Яа-я]+$/msiu',$country); if (!$countryValid) { $errorFlag = true; $errormessagearray['address'] = 'Vvedite korrektno country!'; } $cityValid = preg_match('/^[A-Za-zА-Яа-я]+$/msiu', $city); if (!$cityValid) { $errorFlag = true; $errormessagearray['address'] = 'Vvedite korrektno city!'; } $stretValid = preg_match('/^[A-Za-zА-ЯЁа-яё0-9\s]+/msi', $street); if (!$stretValid) { $errorFlag = true; $errormessagearray['address'] = 'Vvedite korrektno street!'; } $street_geo = str_replace(' ', '+', $street); if(preg_match('/\//i', $house)) { $houseArr = explode("/", $house); foreach ($houseArr as $key => $value) { $houseValid = preg_match("/^[a-zа-яё\d]{1}[a-zа-яё\d\s]*[a-zа-яё\d]{1}$/i", $value); if (!$houseValid) { $errorFlag = true; $errormessagearray['address'] = 'Vvedite korrektno house!'; } } }else{ $houseValid = preg_match('|^[A-Z0-9]+$|i', $house); if (!$houseValid) { $errorFlag = true; $errormessagearray['address'] = 'Vvedite korrektno house!'; } } $address_geo = $country.'+'.$city.'+'.$street_geo.'+'.$house; $user_api_key = '<KEY>'; //GOOGLE API KEY $xml = simplexml_load_file('http://maps.google.com/maps/api/geocode/xml?address='.$address_geo.'&sensor=false'); $json_string = json_encode($xml); $result_array = json_decode($json_string, TRUE); $status = $xml->status; // print_r($xml); if ($status == 'OK') { $lat = $result_array['result']['geometry']['location']['lat']; $lng = $result_array['result']['geometry']['location']['lng']; $data['lat'] = $lat; $data['lng'] = $lng; }else{ $errorFlag = true; $errormessagearray['address'] = 'Can`t get coordinats! Iput correct address!'; } $json = json_encode($errormessagearray); if ($errorFlag) { $errorFlag = false; throw new AsyncActionException($json); } $mySql->insert('google_maps_users', array('name'=>$nameStr,'index'=>$index, 'country'=>$country, 'city'=>$city, 'street'=>$street,'house'=>$house, 'lat'=>$lat,'lng'=>$lng)); $userid = $mySql->getInsertId(); $user = $mySql->getRecord('google_maps_users', array('id' => $userid)); $this->data['user'] = $user; } } ?><file_sep><?php define('DEBUG', true); define('LF', "\n"); define('MAIN_DOMAIN', 'googlemaps.local'); define('HTTP_HOSTNAME', ((isset($_SERVER['HTTPS']) and $_SERVER['HTTPS']=='on')?'https':'http').'://'.$_SERVER['HTTP_HOST'].'/'); define('SITE_PATH', substr($_SERVER['SCRIPT_NAME'], 1, strrpos($_SERVER['SCRIPT_NAME'], '/'))); define('DOCUMENT_ROOT', $_SERVER['DOCUMENT_ROOT'].'/'.SITE_PATH); define('APP_DIR_PATH', DOCUMENT_ROOT.APP_DIR_NAME.'/'); define('CORE_DIR_PATH', APP_DIR_PATH.'core/'); define('MODULES_DIR_PATH', APP_DIR_PATH.'modules/'); define('PLUGINS_DIR_PATH', DOCUMENT_ROOT.'plugins/'); define('LIBS_DIR_PATH', DOCUMENT_ROOT.'libs/'); define('LOGS_DIR_PATH', DOCUMENT_ROOT.'logs/'); define('TMP_DIR_PATH', DOCUMENT_ROOT.'tmp/'); define('UPLOADS_DIR_PATH', DOCUMENT_ROOT.'uploads/'); define('FFMPEG_DIR', '/usr/local/bin/ffmpeg'); define('APP_DIR_URL', HTTP_HOSTNAME.SITE_PATH.APP_DIR_NAME.'/'); define('MODULES_DIR_URL', APP_DIR_URL.'modules/'); define('PLUGINS_DIR_URL', APP_DIR_URL.'plugins/'); define('ADMIN_PANEL_URL', APP_DIR_URL.'backend/'); define('LOGS_DIR_URL', APP_DIR_URL.'logs/'); define('UPLOADS_DIR_URL', HTTP_HOSTNAME.SITE_PATH.'uploads/'); define('MYSQL_HOSTNAME', 'localhost'); define('MYSQL_USERNAME', 'horses'); define('MYSQL_PASSWORD', '<PASSWORD>'); define('MYSQL_DBNAME', 'horses'); define('MYSQL_TIMEZONE', '+2:00'); define('MULTILINGUAL', true); define('ML', MULTILINGUAL); define('DEFAULT_LANG', 'en'); define('DICS_PATH', 'dics/'); // Regular expressions define('RE_EMAIL', '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/i'); define('RE_DATE', '/^\d{4}-\d{2}-\d{2}$/'); define('SALT', '6347fujdkjfgjdr879457848'); define('STATUS_ACTIVE', 'active'); define('STATUS_NEW', 'new'); define('STATUS_UNCONFIRMED', 'unconfirmed'); define('REGISTRATIONS_PER_DAY', 4); define('VIDEOS_V2_PATH', '/uploads/videos_v2/'); define('PHOTOS_ORIGINAL_PATH', 'uploads/photos/original/'); define('PHOTOS_THUMBS_PATH', 'uploads/photos/thumbs/'); define('PHOTOS_LARGE_PATH', 'uploads/photos/large/'); define('PHOTOS_MEDIUM_PATH', 'uploads/photos/medium/'); ?><file_sep><?php /** * Basic_HttpResponse_Builder class file. * */ // Load required classes ClassLoader::loadCoreClass('notfoundexception'); ClassLoader::loadBuilderClass('basic.abstract'); ClassLoader::loadModelClass('basic.htmlresponse'); /** * HTML response builder * */ class Basic_HttpResponse_Builder extends Basic_Abstract_Builder { public function getByRequest(Request $_request = NULL) { $response = new Basic_HtmlResponse_Model(); try { // Extract request URL $url = $_request->getUrl(); // Extract first URL token $firstUrlToken = ($p = strpos($url, '/')) ? substr($url, 0, $p) : substr($url, 0); if ($firstUrlToken == 'async') // JSON (asynchronous) request { // Load async action exception class ClassLoader::loadCoreClass('asyncactionexception'); // Create async action object $restUrl = ($t = substr($url, strlen($firstUrlToken)+1)) ? $t : ''; $asyncActionRef = ($p = strpos($restUrl, '/')) ? substr($restUrl, 0, $p) : substr($restUrl, 0); ClassLoader::loadAsyncActionClass($asyncActionRef); list($moduleKey, $asyncActionKey) = explode('.', $asyncActionRef); $asyncActionClassName = $moduleKey.'_'.$asyncActionKey.'_AsyncAction'; $action = new $asyncActionClassName(); // Set response properties $response->messageBodyFormat = $response->dataType = 'json'; if ($asyncActionRef == 'basic.fileupload') $response->dataType = 'html'; //! Old IE uses iframe for async file upload // Response success by default $response->messageBody = new stdClass(); $response->messageBody->success = true; $response->messageBody->message = 'OK'; try { //! Ensure action privileges // Perform the action $action->perform($_request->getDomainId(), $_request->getParams()); // Set the response data $data = $action->getData(); if (count($data)) $response->messageBody->data = $data; } catch (AsyncActionAuthException $e) { $response->messageBody->success = false; $response->messageBody->auth = false; $response->messageBody->message = 'You are not authorized to perform this action.'; } catch (AsyncActionSessionExpireException $e) { $response->messageBody->success = false; $response->messageBody->expired = true; $response->messageBody->message = 'Session has been expired.'; } catch (AsyncActionException $e) { $response->messageBody->success = false; $response->messageBody->message = $e->getMessage(); // Set the response errors $errors = $action->getErrors(); if (count($errors)) $response->messageBody->errors = $errors; } } else // HTML request { // Extract request URL $url = $_request->getUrl(); // Skip site path if (strlen(SITE_PATH)) { $skipUrlToken = ($p = strpos($url, '/')) ? substr($url, 0, $p) : substr($url, 0); $url = ($t = substr($url, strlen($skipUrlToken)+1)) ? $t : ''; } // Extract first URL token $firstUrlToken = ($p = strpos($url, '/')) ? substr($url, 0, $p) : substr($url, 0); if ($firstUrlToken == 'backend') { $response->messageBody = new ModelViewPair( Application::getBuilder('backend.htmldocument')->getByRequest($_request), 'backend.htmldocument' ); } else { $response->messageBody = new ModelViewPair( Application::getBuilder('main.htmldocument')->getByRequest($_request), 'main.htmldocument' ); } } } catch (NotFoundException $e) { $response->statusCode = 404; $response->dataType = 'html'; $response->messageBody = new ModelViewPair( null, 'basic.notfoundhtmldocument' ); } catch (Exception $e) { echo '<h1>Exception</h1>'; echo '<p>'.$e->getMessage().'</p>'; echo '<pre>'.$e->getTraceAsString().'</pre>'; exit(); // $response->statusCode = 500; // $response->dataType = 'html'; // $response->model = GeneratorsFactory::getGenerator('basic.exceptionhtmldocument')->get(array('exception' => $e)); // $response->view = 'basic.exceptionhtmldocument'; } return $response; } } ?><file_sep><?php /** * Application class file. */ // Load core classes ClassLoader::loadCoreClass('request'); ClassLoader::loadCoreClass('viewer'); /** * Application * */ class Application { /** * @var array Builders collection */ private static $builders = array(); /** * @var array Services collection */ private static $services = array(); /** * @var array User (null stand for guest) */ // private static $user = null; /** * @var Dictionary Dictionary */ // private static $dic = null; /** * @var array Languages set (for ML mode only) */ // private static $langs = array('ru' => 'Русский', 'en' => 'English'); /** * @var string Current language */ // private static $lang = DEFAULT_LANG; /** * @var array Application settings */ // private static $settings = array(); /** * @var array Action privileges */ // private static $actionPrivileges = array // ( // 'login' => array('allow' => 0), // 'logout' => array('allow' => 0), // 'create' => array('allow' => array(UR_ADMIN)), // 'update' => array('allow' => array(UR_ADMIN)), // 'delete' => array('allow' => array(UR_ADMIN)), // 'moveup' => array('allow' => array(UR_ADMIN)), // 'movedown' => array('allow' => array(UR_ADMIN)), // 'delete' => array('allow' => array(UR_ADMIN)), // 'password' => array('allow' => array(UR_ADMIN)), // ); /** * Prevent direct object creation */ private function __construct() {} /** * Prevent to clone the instance */ private function __clone() {} /** * Application runner */ public static function run() { try { // Start a session session_start(); // Init MySQL service $mySqlManager = Application::getService('basic.mysqlmanager'); $mySqlManager->connect(MYSQL_HOSTNAME, MYSQL_USERNAME, MYSQL_PASSWORD, MYSQL_DBNAME); // Create request object $request = new Request($_SERVER, $_REQUEST); // Build HTML response $response = Application::getBuilder('basic.httpresponse')->getByRequest($request); // Send status line header('HTTP/1.1 '.$response->statusCode); // -- Send headers -- // Send 'Content-Type' header if ($response->dataType == 'html') header('Content-Type: text/html; charset=utf-8'); elseif ($response->dataType == 'json') header('Content-Type: application/json; charset=utf-8'); // elseif ($response->dataType == 'xml') header('Content-Type: application/xml; charset=utf-8'); else header('Content-Type: text/html; charset=utf-8'); // default // Send 'Location' header if any if (!is_null($response->location)) header('Location: '.$response->location); // Send message body if ($response->messageBodyFormat == 'html') Viewer::render($response->messageBody, 'main.htmldocument'); elseif ($response->messageBodyFormat == 'json') echo json_encode($response->messageBody); // elseif ($response->messageBodyFormat == 'xml') // Viewer::renderXml($response->view, $response->model); else // default Viewer::render($response->messageBody->view, $response->messageBody->model); } catch (Exception $e) { echo '<h1>Exception</h1>'; echo '<p>'.$e->getMessage().'</p>'; echo '<pre>'.$e->getTraceAsString().'</pre>'; exit(); // $response->statusCode = 500; // $response->dataType = 'html'; // $response->model = GeneratorsFactory::getGenerator('basic.exceptionhtmldocument')->get(array('exception' => $e)); // $response->view = 'basic.exceptionhtmldocument'; } } /** * Accesses the builder * @var sting $_builderRef Builder reference in form of <module_key>.<builder_key> * @return AbstractBuilder Builder object */ public static function getBuilder($_builderRef) { if (!array_key_exists($_builderRef, self::$builders)) { ClassLoader::loadBuilderClass($_builderRef); list($moduleKey, $builderKey) = explode('.', $_builderRef); $builderClassName = $moduleKey.'_'.$builderKey.'_builder'; self::$builders[$_builderRef] = new $builderClassName(); } return self::$builders[$_builderRef]; } /** * Accesses the service * @var sting $_serviceRef Service reference in form of <module_key>.<builder_key> * @return AbstractService Service object */ public static function getService($_serviceRef) { if (!array_key_exists($_serviceRef, self::$services)) { ClassLoader::loadServiceClass($_serviceRef); list($moduleKey, $serviceKey) = explode('.', $_serviceRef); $serviceClassName = $moduleKey.'_'.$serviceKey.'_service'; self::$services[$_serviceRef] = new $serviceClassName(); } return self::$services[$_serviceRef]; } /** * Accesses the application user */ // public static function getUser() // { // $user = null; // if (isset($_SESSION['user'])) // { // $mySqlManager = self::getService('basic.mysqlmanager'); // $user = $mySqlManager->select('*', 'users', array('id' => $_SESSION['user']['id']))->fetchAssoc(); // } // return $user; // } /** * Tells if action is allowed for the specific user * @param string $actionKey Action key * @param integer $userRoleId User role ID or NULL (for non-authorized) */ // public static function isActionAllowed($_actionKey, $_userRoleId) // { // if (array_key_exists($_actionKey, self::$actionPrivileges)) // { // foreach (array_reverse(self::$actionPrivileges[$_actionKey]) as $accessType => $userRoleIds) // { // if (is_array($userRoleIds) ? in_array($_userRoleId, $userRoleIds) : ($userRoleIds == 0 or $_userRoleId == $userRoleIds)) // return $accessType == 'allow'; // } // } // return false; // } } ?><file_sep><?php /** * NotFoundException class file. */ /** * Not found exception * */ class NotFoundException extends Exception {} ?><file_sep><?php // Load abstract action ClassLoader::loadAsyncActionClass('basic.abstract'); class Googlemaps_DelUser_AsyncAction extends Basic_Abstract_AsyncAction { /** * Performs the action */ public function perform($_domainId = null, array $_params = array()) { $mySql = Application::getService('basic.mysqlmanager'); // Extract inputs $id = $this->_getString('id', $_params, true); $mySql->delete('google_maps_users', array('id'=>$id)); $this->data['success'] = true; } } ?><file_sep><?php /** * Basic_Abstract_Service class file. * */ /** * Service exception */ class ServiceException extends Exception {} /** * Abstract service * */ abstract class Basic_Abstract_Service { /** * Returns current date and time as string */ public function dateNow() { return date('Y-m-d H:i:s'); } } ?><file_sep><?php /** * Basic_MySqlManager_Service class file. * */ ClassLoader::loadServiceClass('basic.abstract'); class Basic_QueryBuilder_Service extends Basic_Abstract_Service { public static function escape($value) { return '"' . mysql_real_escape_string($value) . '"'; } public static function escapeKey($key, $table_name = false) { return '`' . $key . '`'; } public static function buildQueryList($params = array()) { foreach ($params as &$param) { if ($param === null) { $param = 'NULL'; } } return ' (' . implode(',', $params) . ') '; } public static function buildQuery($query, $params = false, $row = false) { return $query . (self::buildQueryKeyEqualValue($params, true)) . ($row ? " LIMIT 1 " : ""); } public static function buildQueryTable($table_name, $params = false) { return self::buildQueryTableColumn($table_name, false, $params); } public static function buildQueryTableColumn($table_name, $column_name = false, $params = false) { return "Select " . ($column_name ? self::escapeKey($column_name) : "*") . " from " . self::escapeKey($table_name, 1) . (self::buildQueryKeyEqualValue($params, 1)); } public static function buildQueryTableColumns($table_name, $columns = [], $params = false, $connectors = []) { foreach ($columns as &$column) { $column = static::escapeKey($column); } return "Select " . (!empty($columns) ? implode(',', $columns) : "*") . " from " . self::escapeKey($table_name, 1) . self::buildQueryJoin($connectors) . (self::buildQueryKeyEqualValue($params, 1)) . self::buildQueryGroup($connectors); } public static function buildQueryTableFunction($table_name, $function = false, $params = false) { return "Select " . $function . " from " . self::escapeKey($table_name, 1) . (self::buildQueryKeyEqualValue($params, 1)); } public static function buildQueryKeyEqualValue($fields = array(), $where = false, $exclude_key = false) { $query = ''; if (is_array($fields)) { $queryPieces = []; foreach ($fields as $key => $value) { $queryPieces [] = self::buildQueryKeyEqualValueCondition($where, $exclude_key, $key, $value); } $query = implode(' AND ', $queryPieces); } if ($where && !empty($query)) { $query = ' WHERE ' . $query; } return $query; } public static function buildQueryKeyEqualValueCondition($where, $exclude_key, $key, $value) { $query = ''; if ($exclude_key === $key) { return $query; } if ($key === 'OR') { $queryPieces = []; foreach ($value as $orKey => $orValue) { $queryAndPieces = []; foreach ($orValue as $andKey => $andValue) { $queryAndPieces [] = self::buildQueryKeyEqualValueCondition($where, $exclude_key, $andKey, $andValue); } $queryPieces[] = ' ( ' . implode(' AND ', $queryAndPieces) . ' ) '; } $query .= implode(' ' . $key . ' ', $queryPieces); return $query; } else { $query .= (empty($query) ? '' : ($where ? ' AND ' : ' , ')); } $qKey = self::escapeKey($key); if (is_array($value) && $where) { $queryArray = []; foreach ($value as $kkey => $vvalue) { $kkey = strtolower($kkey); if ($kkey == 'in') { $queryArray[] = $qKey . ' IN ' . self::buildQueryList($vvalue); } elseif (in_array($kkey, ['=', '!=', '<>', '<', '>', 'like'])) { if ($vvalue === null) { if ($kkey == '=') { $newKey = ' is '; } else { $newKey = ' NOT is '; } $queryArray[] = $qKey . $newKey . ' NULL '; } else { if ($kkey == 'like') { $queryArray[] = $qKey . $kkey . ' ' . self::escape('%' . $vvalue . '%'); } else { $queryArray[] = $qKey . $kkey . ' ' . self::escape($vvalue); } } } } if (!empty($queryArray)) { $query .= '( ' . implode(' AND ', $queryArray) . ' ) '; } } elseif (!is_array($value)) { $query .= ($qKey . (($value === null && $where) ? ' is ' : ' = ') . ($value === null ? ' NULL ' : self::escape($value))); } return $query; } public static function buildQueryUpdate($table, $fields = array(), $where = array()) { return "UPDATE " . self::escapeKey($table, 1) . " SET " . self::buildQueryKeyEqualValue($fields) . ' ' . self::buildQueryKeyEqualValue($where, true); } public static function buildQueryDelete($table, $where = array()) { return "DELETE FROM " . self::escapeKey($table, 1) . ' ' . self::buildQueryKeyEqualValue($where, true); } public static function buildQueryDuplicateUpdate($fields, $exclude_key) { $query = self::buildQueryKeyEqualValue($fields, false, $exclude_key); return (empty($query) ? '' : (" ON DUPLICATE KEY UPDATE " . $query)); } public static function buildQueryInsert($table, $fields) { $arguments = array(); $keys = array(); foreach ($fields as $field_key => $field) { if (is_array($field)) { foreach ($field as $key => $value) { $field[$key] = static::escape($value); } if (empty($keys)) { $keys = array_keys($field); foreach ($keys as &$_key) { $_key = self::escapeKey($_key); } } $arguments[] = self::buildQueryList($field); } else { $keys[] = self::escapeKey($field_key); $fields[$field_key] = static::escape($field); } } if (empty($arguments)) { $arguments[] = self::buildQueryList($fields); } return "INSERT INTO " . self::escapeKey($table, 1) . self::buildQueryList($keys) . ' VALUES ' . (implode(',', $arguments)); } public static function buildQuerySort($fields) { $order = ""; if (is_array($fields) && !empty($fields)) { $new_arr = array(); $order = " ORDER BY "; foreach ($fields as $key => $value) { $new_arr[] = self::escapeKey($key) . (strtoupper($value) == 'DESC' ? ' DESC ' : ' ASC '); } $order .= implode(',', $new_arr); } return $order; } public static function buildQueryGroup($connectors = []) { $group = ""; if (is_array($connectors) && !empty($connectors)) { $new_arr = array(); $group = " GROUP BY "; foreach ($connectors as $key => $value) { $new_arr[] = $value['externalField']; } $group .= implode(',', $new_arr); } return $group; } public static function buildQueryJoin($connectors = []) { $join = ""; if (is_array($connectors) && !empty($connectors)) { $new_arr = array(); foreach ($connectors as $key => $value) { $new_arr[] = ' left join ' . self::escapeKey($value['table']) . ' on ' . self::escapeKey($value['externalField']) . ' = ' . self::escapeKey($value['internalField']) . ' '; } $join .= implode(' ', $new_arr); } return $join; } public static function buildQueryPagination($params = []) { if (!empty($params['row'])) { return ' LIMIT 1 '; } if (!empty($params['all'])) { return ' '; } $page = isset($params['page']) ? $params['page'] : 1; $page_count = isset($params['page_count']) ? $params['page_count'] : 20; $count_all = isset($params['count_all']) ? $params['count_all'] : 20; if (($count_all % $page_count) > 0) { $pages_count = floor($count_all / $page_count) + 1; } else { $pages_count = floor($count_all / $page_count); } $page_current = $page; if ($page_current < 0) { $page_current = 1; } if ($page_current > $pages_count) { $page_current = $pages_count; } if (is_numeric($page) && is_numeric($page_count)) { return " LIMIT " . ((($page_current - 1) * $page_count)) . "," . $page_count . " "; } return " LIMIT 0," . $page_count . " "; } public function buildQueryFull($table, $columns = [], $params = false, $order = [], $paging = [], $connectors = []) { return self::buildQueryTableColumns($table, $columns, $params, $connectors) . self::buildQuerySort($order) . self::buildQueryPagination($paging); } public function buildQueryCount($table, $params = false) { return self::buildQueryTableFunction($table, 'count(*)', $params); } public static function buildQueryInsertFull($table, $fields, $duplicate = array()) { $query = self::buildQueryInsert($table, $fields); if (!empty($duplicate) && $duplicate['type'] == 'update') { $query .= self::buildQueryDuplicateUpdate($fields, $duplicate['key']); } return $query; } public static function buildQueryInsertMulti($table, $fields) { $query = self::buildQueryInsert($table, $fields); return $query; } } <file_sep>/** * Google Maps User Manager * @author <NAME> <<EMAIL>> * @copyright Copyright &copy; 2017 <NAME> * @created 2017.11.28 */ $.widget('nm.googlemapsusermanager', { options: { dummy: 'dummy', markers:[], markerPr:null, infowindow:null, contentInfowindow:'', users:{}, map:null, }, _create: function () { var widget = this; this.element.on('click','.switch-lang button',function(e){ e.preventDefault(); widget.changeLang($(this)); }); this.element.on('click','#manage-users',function(e){ e.preventDefault(); widget.clearMarkers(); widget.showManager(); }); this.element.on('click','#back-to-map',function(e){ e.preventDefault(); widget.showMap(); widget.clearMarkers(); widget.getUsers(false); }); this.element.on('click','a.edit-user',function(e){ e.preventDefault(); var id = $(this).closest('tr').data('id'); widget.getUser(id); }); this.element.on('click','#back-to-usermanager',function(e){ e.preventDefault(); $('#add-user-block').hide(); $('#usermanager').show(); }); this.element.on('click','.delete-user',function(e){ e.preventDefault(); var id = $(this).closest('tr').data('id'); widget.deleteUser(id); widget.options.markers.splice(id, 1); }); this.element.on('click','#add-user',function(e){ e.preventDefault(); widget.clearFormForAddUser(); widget.showAddUserFrom(); }); this.element.on('click','button.send-add',function(e){ e.preventDefault(); widget.clearFormError(); widget.addNewUser(); }); this.element.on('click','button.send-edit',function(e){ e.preventDefault(); var id = $(this).closest('form.form-horizontal').attr('data-id'); widget.clearFormError(); widget.updateUser(id); }); this.element.on('click','#update-users',function(e){ widget.clearMarkers(); widget.getUsers(false); }); this.element.on('change','#users-select',function(e){ var id = $(this).val(); widget.showUserMap(widget.options.users[id]); }); this._initApp(); }, _initApp:function(){ var widget = this; widget.drawBlockAddUser(); widget.drawBlockUserManager(); widget.drawBlockApp(); widget.getUsers(true, function(){widget.initMap()}); widget.addUserForm(); }, drawBlockAddUser:function(){ var widget = this; widget.element.append( $('<div/>',{id:'add-user-block'}).css('display','none').append( $('<form/>',{class:'form-horizontal', role:'form'}) ) ) }, drawBlockUserManager:function(){ var widget = this; widget.element.append( $('<div/>',{id:'usermanager'}).css('display','none').append( $('<div/>',{class:'header-usermanager'}).append( $('<a/>',{href:'#', id:'back-to-map'}).text('Back'), $('<a/>',{href:'#', id:'add-user'}).text('Add new user') ), $('<div/>',{class:'user-table-block'}).append( $('<table/>',{id:'user-table', class:'table table-bordered'}).append( $('<thead/>').append( $('<tr/>').append( $('<td/>').text('Image'), $('<td/>').text('Name'), $('<td/>').text('Address'), $('<td/>').text('Action') ) ), $('<tbody/>') ) ) ) ) }, drawBlockApp:function(){ var widget = this; widget.element.append( $('<div/>',{id:'application'}).append( $('<div/>',{id:'application'}).append( $('<div/>',{id:'header'}).append( $('<a/>',{href:'#', id:'manage-users'}).text('Manage users'), ), $('<p/>',{class:'title'}).text('Выберите пользователя:'), $('<div/>',{id:'users'}).append( $('<select/>',{name:'users-select',id:'users-select'}).append( $('<option/>',{id:'default-option'}).text('----') ) ), $('<button/>',{id:'update-users',class:'btn btn-primary', type:'submit'}).text('Update users'), $('<div/>',{id:'map'}) ) ) ); }, getUsers:function(createmarkers, _callBackFn){ var widget = this; widget.options.users = []; sendRequest({ action: 'googlemaps.getusers', successHandler: function (_callbackParams) { var response = _callbackParams.response; if (!response.success) { alert(response.message); } else{ var resp = response.data.users; for (var i = 0; i < resp.length; i++) { widget.options.users[resp[i].id] = resp[i]; } widget.refreshSelectUser(widget.options.users); if (createmarkers) widget.createMarkers(); if (_callBackFn) _callBackFn(); } } }); }, initMap:function (){ var widget =this; for (var i in widget.options.users) { var lat = Number(widget.options.users[i].lat); var lng = Number(widget.options.users[i].lng); break; }; var latLng = {lat: lat, lng: lng}; widget.options.map = new google.maps.Map(document.getElementById('map'), { zoom: 15, center: latLng, mapTypeId: 'terrain' }); widget.options.infowindow = new google.maps.InfoWindow({ content: widget.options.contentInfowindow }); }, showUserMap:function (_user){ var widget = this; var marker = widget.options.markers[_user.id]; if (widget.options.markerPr) widget.setMarkerMap(null,widget.options.markerPr); widget.setMarkerMap(widget.options.map, marker); widget.options.markerPr = widget.options.markers[_user.id]; widget.showMessage(marker,_user); }, // Adds a marker to the map and push to the array. addMarker:function(user) { var widget =this; var location = {lat:Number(user.lat),lng:Number(user.lng)}; var marker = new google.maps.Marker({ position: location, animation: google.maps.Animation.DROP, map: widget.options.map }); widget.options.markers[user.id] = marker; }, createMarkers:function (){ var widget = this; widget.deleteMarkers(); widget.options.markers.length = 0; for (var i in widget.options.users) { var user = widget.options.users[i]; var marker = new google.maps.Marker({ position: {lat:Number(user.lat),lng:Number(user.lng)}, map: widget.options.map }); widget.options.markers[user.id] = marker; } }, setMapOnAll:function (_map) { var widget = this; // var map = _map || widget.options.map; for (var i in widget.options.markers) { widget.options.markers[i].setMap(_map); } }, setMarkerMap:function (map, marker) { var widget = this; marker.setMap(map); }, // Removes the markers from the map, but keeps them in the array. clearMarkers:function () { var widget = this; widget.setMapOnAll(null); }, // Deletes all markers in the array by removing references to them. deleteMarkers:function () { var widget = this; widget.clearMarkers(); widget.options.markers = []; // markers.length = 0; }, showMessage:function (_marker, user){ var widget = this; var contentInfowindow = '<div id="content">'+ '<h5 id="firstHeading" class="firstHeading">'+user.name+'</h5>'+ '<div id="bodyContent">'+ '<p>'+user.index+' '+user.country+' '+user.city+'<br>'+user.street+','+user.house+'</p>'+ '</div>'+ '</div>'; widget.options.infowindow.setContent(contentInfowindow); widget.options.infowindow.open(map, _marker); _marker.addListener('click', function() { widget.options.infowindow.open(map, _marker); }); }, addNewUser:function (){ var widget = this; var form = $('#add-user-block form'); var data = form.serializeObject(); sendRequest({ action: 'googlemaps.createuser', data: {data:data}, successHandler: function (_callbackParams) { var response = _callbackParams.response; if (!response.success) { var errors = JSON.parse(response.message); $.each(errors, function(i, val) { widget.element.find('form #input'+i).closest('div.form-group').addClass('has-error'); widget.element.find('form #input'+i).next().text(val).css('color','red'); }); } else{ var user = response.data.user; widget.drawRowTable(user); widget.addMarker(user); $('#add-user-block').hide(); $('#usermanager').show(); } } }); }, updateUser:function (_id){ var widget =this; var form = $('#add-user-block form'); var data = form.serializeObject(); data['id'] = _id; sendRequest({ action: 'googlemaps.updateuser', data: {data:data}, successHandler: function (_callbackParams) { var response = _callbackParams.response; if (!response.success) { var errors = JSON.parse(response.message); $.each(errors, function(i, val) { widget.element.find('form #input'+i).closest('div.form-group').addClass('has-error'); widget.element.find('form #input'+i).next().text(val).css('color','red'); }); } else{ widget.getUsers(true, function(){widget.showManager()}); $('#add-user-block').hide(); $('#usermanager').show(); } } }); }, clearFormError:function(){ var widget = this; var form = widget.element.find('#add-user-block form'); form.find('span.error-form').text(''); form.find('div.form-group').removeClass('has-error'); }, showAddUserFrom:function (){ var widget = this; $('#usermanager').hide(); $('#add-user-block').show(); }, addUserForm:function (){ $('#add-user-block').prepend( $('<div/>',{id:'header-add-user-block'}).append( $('<a/>',{id:'back-to-usermanager', href:'#'}).text('Back') ) ); var form = $('#add-user-block form').empty(); form.append( $('<h1/>',{class:'col-sm-offset-3 col-sm-6'}).text('Add user'), $('<div/>',{class:'form-group responsive-label'}).append( $('<label/>',{class:'col-sm-offset-3 col-sm-6 control-label'}).attr('for','inputname').text('Name').css('text-align','left'), $('<div/>',{class:'col-sm-offset-3 col-sm-6'}).append( $('<input/>',{class:'form-control', type:'text', id:'inputname', name:'name'}), $('<span/>',{class:'error-form'}) ) ), $('<div/>',{class:'form-group responsive-label'}).append( $('<label/>',{class:'col-sm-offset-3 col-sm-6 control-label'}).attr('for','inputaddress').text('Address Example:12345 Ukraine Kharkiv Plekhanivska,135/139').css('text-align','left'), $('<div/>',{class:'col-sm-offset-3 col-sm-6'}).append( $('<input/>',{class:'form-control', type:'text', id:'inputaddress', name:'address'}), $('<span/>',{class:'error-form'}) ) ), $('<div/>',{class:'footer-form col-sm-offset-3 col-sm-6'}).append( $('<button>',{class:'btn btn-primary send-edit'}).text('Submit') ) ); }, deleteUser:function (_id){ var widget = this; sendRequest({ action: 'googlemaps.deluser', data: {id: _id}, successHandler: function (_callbackParams) { var response = _callbackParams.response; if (!response.success) { alert(response.message); } else{ $('tr[data-id='+_id+']').remove(); } } }); }, getUser:function (_id){ var widget = this; sendRequest({ action: 'googlemaps.getuser', data: {id: _id}, successHandler: function (_callbackParams) { var response = _callbackParams.response; if (!response.success) { alert(response.message); } else{ var user = response.data.user; widget.editUserForm(user); } } }); }, clearFormForAddUser:function (){ var widget = this; var form = $('#add-user-block form'); form.find('#inputname').val(''); form.find('#inputaddress').val(''); form.find('button').removeClass('send-edit').addClass('send-add'); form.find('h1').text('Add user'); }, editUserForm:function (_user){ var widget = this; $('#usermanager').hide(); var form = $('#add-user-block form'); var address = _user.index+' '+_user.country+' '+_user.city+' '+_user.street+', '+_user.house; form.attr('data-id',_user.id); form.find('button').removeClass('send-add').addClass('send-edit'); $('#inputname').val(_user.name); $('#inputaddress').val(address); form.find('h1').text('Edit user'); $('#add-user-block').show(); }, showManager:function (){ var widget = this; $('#application').hide(); $('#usermanager').show(); var tbody = $('#user-table tbody').empty(); for (var i in widget.options.users) { var user = widget.options.users[i]; widget.drawRowTable(user); } }, showMap:function (){ var widget = this; $('#usermanager').hide(); $('#application').show(); }, drawRowTable:function (_user){ var widget = this; var tbody = $('#user-table tbody'); var address = _user.index+' '+_user.country+' '+_user.city+' '+_user.street+', '+_user.house; tbody.append( $('<tr/>').attr('data-id',_user.id).append( $('<td/>').text(_user.image), $('<td/>').text(_user.name), $('<td/>').text(address), $('<td/>').append( $('<a/>',{href:'#', class:'edit-user'}).text('Edit'), $('<a/>',{href:'#', class:'delete-user'}).text('Delete') ) ) ) }, refreshSelectUser:function (_items){ var widget = this; var selectEl = $('#users-select'); selectEl.find('option:not(#default-option)').remove(); for (var i in _items) { var user = _items[i]; selectEl.append( $('<option/>').attr({'data-lat':user.lat,'data-lng':user.lng}).text(user.name).val(user.id) ) }; selectEl.find('#default-option').attr({'selected':'selected','disabled':'disabled'}); }, testFn:function(){ var widget = this; console.log(this); } }); (function($) { // поиск и удаление класса по шаблону // $('p').removeClassWild("status_*"); $.fn.removeClassWild = function(mask) { return this.removeClass(function(index, cls) { var re = mask.replace(/\*/g, '\\S+'); return (cls.match(new RegExp('\\b' + re + '', 'g')) || []).join(' '); }); }; })(jQuery); <file_sep><?php error_reporting(E_ALL^E_NOTICE); ini_set('display_errors', 1); // Load config define('APP_DIR_NAME', 'application_v2'); require_once(APP_DIR_NAME.'/configs/config.php'); // Load class loader require_once(CORE_DIR_PATH.'classloader.php'); // Load application ClassLoader::loadCoreClass('application'); // Run the application Application::run(); ?><file_sep><?php /** * Basic_HtmlResponse_Model class file. * */ // Load abstract HTML document model class ClassLoader::loadModelClass('basic.abstract'); /** * Response model * */ class Basic_HtmlResponse_Model extends Basic_Abstract_Model { /** * @var integer HTTP status code */ public $statusCode = 200; /** * @var string Reason message */ public $reasonMessage = 'OK'; /** * @var string Data type */ public $dataType = 'html'; /** * @var string Location header value */ public $location = null; /** * @var string Message body data format (e.g. json could be passed withing html body) */ public $messageBodyFormat = 'html'; /** * @var mixed Message body */ public $messageBody = null; } ?><file_sep><?php // Load abstract action ClassLoader::loadAsyncActionClass('basic.abstract'); class Googlemaps_GetUsers_AsyncAction extends Basic_Abstract_AsyncAction { /** * Performs the action */ public function perform($_domainId = null, array $_params = array()) { $mySql = Application::getService('basic.mysqlmanager'); // Extract inputs $usersSort = array(); $users = $mySql->getRecords('google_maps_users', '`id`'); // var_dump($users); foreach ($users as $key => $value) { $usersSort[$value['id']] = $value; } $this->data['users'] = $users; } } ?><file_sep>var guid = (function() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return function() { return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); }; })(); $(document).ajaxStart(function() { $.blockUI({message: '<div style="padding: 12px; background-color: #d9dde2"><span style="font-size: 20px">Loading...</span></div>'}); }); $(document).ajaxStop(function() { $.unblockUI(); }); $(document).ready(function(){ $('form').on('click', 'input:checkbox.radio', function() { $this = $(this); $('input:checkbox[name=\''+$this.attr('name')+'\']').prop('checked', false); $this.prop('checked', true); }); $('form').on('click', 'input:checkbox.boolean', function() { var $this = $(this); if ($this.prop('checked')) $this.val(1); else $this.val(0); }); }); $.fn.serializeObject = function() { var o = {}; var a = this.serializeArray(); a = a.concat( $(this).find('input[type=checkbox]:not(:checked, .radio)').map(function() { return {'name': this.name, 'value': this.value}; }).get() ); $.each(a, function() { if (o[this.name] !== undefined) { if (!o[this.name].push) { o[this.name] = [o[this.name]]; } o[this.name].push(this.value || ''); } else { o[this.name] = this.value || ''; } }); return o; }; function sendRequest(_params) { if (_params.action) { var url = _params.action.charAt(0)=='/' ? _params.action : '/async/'+_params.action; var ajaxGlobal = _params.ajaxGlobal == undefined ? true : _params.ajaxGlobal; var ajaxAsync = _params.ajaxAsync == undefined ? true : _params.ajaxAsync; /* --- Modify by <NAME> 09-05-2017 for upload file (start) --- */ var processData = _params.processData == undefined ? true : _params.processData; var contentType = _params.contentType == undefined ? 'application/x-www-form-urlencoded; charset=UTF-8' : _params.contentType; /* --- Modify by <NAME> 09-05-2017 for upload file (end) --- */ $.ajax({ async: ajaxAsync, global: ajaxGlobal, type: 'POST', url: url, dataType: 'json', processData: processData, contentType: contentType, data: _params.data, cache: false, success: function(_response, _textStatus, _jqXHR) { //alert('Success: ' + _jqXHR.responseText); _params.successHandler({response: _response, requestData: _params.data}); }, error: function(_jqXHR, _textStatus, _errorThrown) { if (isBeforeunloadSupported()) { if (! beforeunloadCalled) { alert('Error: ' + _jqXHR.responseText); } } else { setTimeout(function () { alert('Error: ' + _jqXHR.responseText); }, 1000); } }, complete: function(_jqXHR, _textStatus) { if (_params.completeHandler) _params.completeHandler({requestData: _params.data}); } }); } } function clearForm($_form) { $_form.find('input:text, input:password, input:file, select, textarea').val(''); $_form.find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected'); } function populateForm($form, data) { clearForm($form); $.each(data, function(key, value) { if (value instanceof Array) { var len = value.length; for (var i = 0; i < len; i++) { var $ctrl = $form.find('[name=\''+key+'['+i+']'+'\']'); setFormControlValue($ctrl, value[i]); } } else if (value instanceof Object) { for (var i in value) { var $ctrl = $form.find('[name=\''+key+'['+i+']'+'\']'); setFormControlValue($ctrl, value[i]); } } else { var $ctrl = $form.find('[name='+key+']'); setFormControlValue($ctrl, value); } }); } function setFormControlValue($_ctrl, _value) { if ($_ctrl.is('select')){ $('option', $_ctrl).each(function() { if ($(this).val() == _value) this.selected = true; }); } else if ($_ctrl.is('textarea')) { $_ctrl.val(_value); } else { switch($_ctrl.attr("type")) { case "text": case "hidden": $_ctrl.val(_value); break; case "checkbox": if (_value == '1') { $_ctrl.prop('checked', true); $_ctrl.val(1); } else { $_ctrl.prop('checked', false); $_ctrl.val(0); } break; } } } function getCaptcha($_form) { $captchaBox = $( '<div style="display: none" id="captcha-box">'+ ' <div style="width: 160px; float: left;">'+ ' <p style="color: #000000; float: none; font: normal 18px \'Times New Roman\'; margin: 0 0 10px; padding: 0; text-align: left; width: auto;">To get your quote please enter the numbers below:</p>'+ ' <form id="captcha-form" action="/async/basic.verifycaptcha" method ="post">'+ ' <div class="captcha"></div>'+ ' <input type="text" name="captcha" value="">'+ ' <input type="submit" value="SEND">'+ ' </form>'+ ' </div>'+ ' <div style="width: 120px; float: left; padding-left: 16px; text-align: center">'+ ' <p style="color: #000000; float: none; font: normal 12px/14px \'Times New Roman\'; margin: 0 0 10px; padding: 0; text-align: justify; width: auto;">This is a verification system to ensure you are a person and not an automated system.</p>'+ ' <p style="color: #000000; float: none; font: normal 18px \'Times New Roman\'; margin: 0; padding: 0; text-align: left; width: auto;"><img src="/application/modules/basic/images/logo-captcha.png"></p>'+ ' </div>'+ '</div>' ); var $captchaForm = $captchaBox.find('form#captcha-form'); $captchaForm.off('submit'); var $submit = $captchaForm.find('input[type=submit]'); $submit.prop('disabled', false); $captchaForm.submit(function(e) { e.preventDefault(); $submit.prop('disabled', true); var data = $captchaForm.serializeObject(); sendRequest({ action: $captchaForm.attr('action'), data: data, successHandler: function(_callbackParams) { var response = _callbackParams.response; if (!response.success) alert(response.message); else { $.modal.close(); var $captchaInput = $_form.find('input[name=captcha]'); if ($captchaInput.length == 0) $_form.prepend('<input type="hidden" name="captcha" value="'+data.captcha+'" />'); else $captchaInput.val(data.captcha); $_form.submit(); } }, completeHandler: function(_callbackParams) { $submit.prop('disabled', false); } }); }); clearForm($captchaForm); $captchaBox.find('div.captcha').html('<img src="/captcha.php?r='+Math.random()+'" />'); $captchaBox.modal({overflow: 'hidden'}); } /*(function($) { $.fn.ajaxForm = function(_options) { // Default settings var settings = jQuery.extend({ dummy: 0, clearFormOnSuccess: true, onSuccess: function() { alert('Your request has been sent.'); }, beforeSubmit: function() {} }, _options); // Overwrite form's submit method this.submit(function(e) { e.preventDefault(); var $form = $(this); var $submit = $form.find('input[type=submit]'); $submit.prop('disabled', true); settings.beforeSubmit(); sendRequest({ action: $form.attr('action'), data: $form.serializeObject(), successHandler: function(_callbackParams) { var response = _callbackParams.response; if (!response.success) { if (response.errors && response.errors.captcha) getCaptcha($form); else alert(response.message); } else { if (settings.clearFormOnSuccess) clearForm($form); settings.onSuccess(); } }, completeHandler: function(_callbackParams) { $submit.prop('disabled', false); } }); }); return this; }; })(jQuery);*/ (function($) { $.fn.placeholder = function(_options) { var settings = jQuery.extend({ dummy: 0, text: 'Enter...', className: 'placeholder' }, _options); this.val(settings.text); this.addClass(settings.className); this.focusin(function() { if ($(this).hasClass(settings.className)) { $(this).removeClass(settings.className); $(this).val(''); } }); this.focusout(function() { if ($(this).val() == '') { $(this).val(settings.text); $(this).addClass(settings.className); } }); return this; }; })(jQuery); (function($, global) { var field = 'beforeunloadSupported'; if (global.localStorage && global.localStorage.getItem && global.localStorage.setItem && ! global.localStorage.getItem(field)) { $(window).on('beforeunload', function () { global.localStorage.setItem(field, 'yes'); }); $(window).on('unload', function () { // If unload fires, and beforeunload hasn't set the field, // then beforeunload didn't fire and is therefore not // supported (cough * iPad * cough) if (! global.localStorage.getItem(field)) { global.localStorage.setItem(field, 'no'); } }); } global.isBeforeunloadSupported = function () { if (global.localStorage && global.localStorage.getItem && global.localStorage.getItem(field) && global.localStorage.getItem(field) == "yes" ) { return true; } else { return false; } } })(jQuery, window); var beforeunloadCalled = false; // Beware that 'beforeunload' is not supported in all browsers. // iPad / iPhone - I'm looking at you. $(window).on('beforeunload', function () { beforeunloadCalled = true; }); function formatDateMmDdYyyy(date) { return date.substring(5,7)+'-'+date.substring(8,10)+'-'+date.substring(0,4); } function formatDateYyyyMmDd(date) { return date.substring(6,10)+'-'+date.substring(0,2)+'-'+date.substring(3,5); } function formatDateMmDdYyyyHhIiSs(date) { return date.substring(5,7)+'-'+date.substring(8,10)+'-'+date.substring(0,4)+' '+date.substring(11,19); } function getUtcOffset() { var date = new Date(); var hours = -date.getTimezoneOffset()/60; return (hours>=0?'+':'')+hours+':00'; } function formatFloatTwoDecimalDigits(_value) { return parseFloat(Math.round(_value*100)/100).toFixed(2); //return _value; } jQuery.fn.selectText = function() { var doc = document; var element = this[0]; if (doc.body.createTextRange) { var range = document.body.createTextRange(); range.moveToElementText(element); range.select(); } else if (window.getSelection) { var selection = window.getSelection(); var range = document.createRange(); range.selectNodeContents(element); selection.removeAllRanges(); selection.addRange(range); } }; function escapeHtml(text) { var map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' }; if(text === null || text ===false){ return ''; } if(text.length){ return text.replace(/[&<>"']/g, function(m) { return map[m]; }); }else{ return text; } } function bind_blueimp(params) { $(function () { var links = document.getElementById(params.containerId).getElementsByClassName(params.linkClass); blueimp.Gallery( links, { container: '#'+params.containerId+' .'+params.blueimpClass, carousel: true, slideshowInterval: parseInt(params.slideTime) * 1000, stretchImages: params.imgType, onslide: function () { var $caption = $('#'+params.containerId+' .'+params.blueimpClass + ' .caption'); $caption.animate({'bottom': '-' + $caption.outerHeight() + 'px'}, function () { }); $caption.find('.icons .icon').hide('slow'); }, onslideend: function (index, slide) { var $frame = $('#'+params.containerId + ' .frames .frame:eq(' + index + ')'); var $href = $frame.attr('data-href'); var $caption = $('#'+params.containerId+' .'+params.blueimpClass + ' .caption'); var $title = $frame.find('.title').html(); if ($title) { if ($href == undefined || $href == '') { $caption.find('.title-normal').html($title); $caption.find('.title-short').html($frame.find('.title-short').html()); } else { $caption.find('.title-normal').html('<a href="' + $href + '" target="_blank">' + $title + '</a>'); $caption.find('.title-short').html('<a href="' + $href + '" target="_blank">' + $frame.find('.title-short').html() + '</a>'); } $caption.find('.description').html($frame.find('.description').html()); if ($frame.attr('data-photo') == '1') $caption.find('.icons .icon-photo').attr('href', $href + '#photos').show('slow'); if ($frame.attr('data-video') == '1') $caption.find('.icons .icon-video').attr('href', $href + '#videos').show('slow'); $caption.animate({'bottom': 0}); } } } ); }); }
d863db604b82437eded66fed26f9d02ca9977ee9
[ "JavaScript", "PHP" ]
23
PHP
deniskucher/googlemaps
29cefe62acfe54d2f2f414c9992bb4ec222ab33c
bac93455ac2f83b9b24d6d90596424fa39637432
refs/heads/master
<repo_name>leaffm/ParseAppsScript<file_sep>/README.md Helps your Spreadsheets interact with Parse.com. ## Quickstart The Google Apps Script gallery is being finnicky, so for now, this is the easiest way to get started: 1. Copy `parse.gs`. 2. Create a new Google Spreadsheet. 3. Create a new sheet and make sure it is first sheet (closes to left side of the screen). 4. Enter your Parse Application ID in Cell B:1 and your Parse REST API Key in Cell B:2. 5. Tools -> Script Editor 6. Paste 7. See `examples.gs` or below: ```javascript parseInsert("GameScore",{ "score" : 1000, "playerName" : "<NAME>" }); results = parseQuery("GameScore", { 'playerName' : '<NAME>' }); var objectId = results[0].objectId; parseUpdate("GameScore", objectId, { "playerName" : "<NAME>" }); parseFindOrCreateByAttribute("GameScore",{ "playerName" : "<NAME>" }); ``` ## Cron Here's a neat trick to run cron tasks for free: 1. Open the Google Apps Script editor. 2. Define function that you want to run in the cron task. 3. Resources -> Current Script Triggers 4. Select the function from step two, and customize to your needs. ### Cron example Let's say you're running a script that will tally the score for a multiplayer game. You have a class called `Game` with the boolean field `scored`, the integer fields `homeScore` and `awayScore`, and a string field `winner`. Let's load some sample data: ```javascript function setupData() { parseInsert("Game", { "scored" : true, "homeScore" : 55, "awayScore" : 44, "winner" : "home" }); parseInsert("Game", { "scored" : false, "homeScore" : 99, "awayScore" : 59 }); parseInsert("Game", { "scored" : false, "homeScore" : 46, "awayScore" : 12, }); parseInsert("Game", { "scored" : false, "homeScore" : 66, "awayScore" : 100, }); } ``` And here's the scoring script: ```javascript function scoreGames() { var games = parseQuery("Game", { "scored" : false }); for (var i = 0; i < games.length; i++) { var objectId = games[i].objectId; var winner; if (games[i].homeScore > games[i].awayScore) { // home team wins winner = "home"; } else if (games[i].homeScore < games[i].awayScore) { //away team wins winner = "away"; } else { // tie winner = "tie"; } parseUpdate("Game", objectId, { "scored" : true, "winner" : winner }); } } ``` So to get this script to run every minute, just click "Resources" -> "Current Script Triggers", then select "scoreGames()" from the function list and set it to run every minute.<file_sep>/exmples/hello.gs function postToParse() { parseInsert("GameScore",{ "score" : 1000, "playerName" : "<NAME>" }); }; function queryParse() { var results = parseQuery("GameScore", { 'playerName' : '<NAME>' }); Logger.log(results[0].playerName); } function updateParse() { var results = parseQuery("GameScore", { 'playerName' : '<NAME>' }); var objectId = results[0].objectId; parseUpdate("GameScore", objectId, { "playerName" : "<NAME>" }); } /** * Adds a custom menu to the active spreadsheet, containing a single menu item * for invoking the readRows() function specified above. * The onOpen() function, when defined, is automatically invoked whenever the * spreadsheet is opened. * For more information on using the Spreadsheet API, see * https://developers.google.com/apps-script/service_spreadsheet */ function onOpen() { var sheet = SpreadsheetApp.getActiveSpreadsheet(); var entries = [{ name : "Read Data", functionName : "readRows" }]; sheet.addMenu("Script Center Menu", entries); };
347dade80c0069d0c75a194d58253b2ed5483768
[ "Markdown", "JavaScript" ]
2
Markdown
leaffm/ParseAppsScript
77634611e2097e9b8b3d49139c72c674f0895512
5c70cb5b961b013a08753c616117c7e523563350
refs/heads/master
<repo_name>linsudeer/note-source<file_sep>/source-zh/src/com/servlet/demo/listener/MyContextLinstener.java package com.servlet.demo.listener; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import java.util.HashMap; import java.util.Map; @WebListener public class MyContextLinstener implements ServletContextListener { private Map<String, String> conf = new HashMap<String, String>(); @Override public void contextInitialized(ServletContextEvent evnt) { ServletContext sc = evnt.getServletContext(); conf.put("contextPath", sc.getContextPath()); // 保存一些全局的变量 } @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { conf.clear(); } } <file_sep>/source-zh/src/com/servlet/demo/listener/MySessionAttributeListener.java package com.servlet.demo.listener; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionBindingEvent; public class MySessionAttributeListener implements HttpSessionAttributeListener { @Override public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) { } @Override public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) { } @Override public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) { } }
e4c3c02cd2b3709c4b8a3d77b49ba588a702cc31
[ "Java" ]
2
Java
linsudeer/note-source
38e646e2e86a78a6ac76cf40cf8bfd4cbfbff471
e9ca210cdc8c9771e7c249d322167860ca14caab
refs/heads/master
<file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import subprocess from flask import flash, redirect, url_for, request def error_cmd(): flash("Only show / traceroute / ping / whois / help commands are allowed !") return redirect(url_for('bird')) def launch_cmd(final_cmd): try: results = subprocess.check_output(final_cmd, shell='True') except subprocess.CalledProcessError, e: results = e.output finally: return results def help_cmd(): help = """ show protocols => show bgp session status show route => show received routes show route filtered => show received routes before filtering show route export AS-NAME => show advertised-routes show route for network all => show all AS-Path for a given network ping(6) ip/domain-name => ping command traceroute(6) ip/domain-name => traceroute command""" return(help) def writelogs(final_cmd): now = datetime.datetime.now() date = now.strftime("%Y-%m-%d at %H:%M") ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr) f = open('/var/log/birdy.log', 'a') log = str(date) + " : IP " + str(ip) + " was connected and enter : " \ + "'" + str(final_cmd) + "'" + "\n" f.write(log) f.close() <file_sep>#! /usr/bin/env python # -*- coding:utf-8 -*- from birdy import app from flask import render_template, request from functions import error_cmd, launch_cmd, help_cmd, writelogs from forms import CommandForm import subprocess import re @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 final_cmd = "birdc show protocols" results = subprocess.check_output(final_cmd, shell='True') return render_template('home.html', results=results) @app.errorhandler(500) def internal_error(e): return render_template('404.html'), 500 final_cmd = "birdc show protocols" results = subprocess.check_output(final_cmd, shell='True') return render_template('home.html', results=results) @app.route('/', methods=['GET', 'POST']) def bird(): final_cmd, results = "birdc show protocols", "" form = CommandForm(request.form) if request.method == "POST" and form.validate(): # Logs writelogs(form.cmd.data) # Forbidden chars if ";" not in form.cmd.data and \ "&" not in form.cmd.data and \ "$" not in form.cmd.data and \ "!" not in form.cmd.data and \ "-" not in form.cmd.data and \ "`" not in form.cmd.data and \ "<" not in form.cmd.data and \ ">" not in form.cmd.data: # Help allowed if form.cmd.data.startswith('help'): final_cmd = "help" results = help_cmd() # Ping allowed elif form.cmd.data.startswith('ping'): final_cmd = re.sub('ping', 'ping -n -i 0.1 -c 2', form.cmd.data) results = launch_cmd(final_cmd) # Traceroute allowed elif form.cmd.data.startswith('traceroute'): final_cmd = re.sub('traceroute', 'traceroute -w 2 -q 1 -m 10', form.cmd.data) results = launch_cmd(final_cmd) # Whois allowed elif form.cmd.data.startswith('whois'): final_cmd = re.sub('whois', 'whois -h whois.dn42', form.cmd.data) results = launch_cmd(final_cmd) # bird show allowed elif form.cmd.data.startswith('show'): final_cmd = "birdc " + form.cmd.data results = launch_cmd(final_cmd) # final_cmd = birdc show protocols and print error message else: results = launch_cmd(final_cmd) error_cmd() form.cmd.data = "" else: results = launch_cmd(final_cmd) error_cmd() else: results = launch_cmd(final_cmd) return render_template('home.html', form=form, final_cmd=final_cmd, results=results) @app.route('/ipv6', methods=['GET', 'POST']) def bird6(): final_cmd, results = "birdc6 show protocols", "" form = CommandForm(request.form) if request.method == "POST" and form.validate(): # Logs writelogs(form.cmd.data) # Forbidden chars if ";" not in form.cmd.data and \ "&" not in form.cmd.data and \ "$" not in form.cmd.data and \ "!" not in form.cmd.data and \ "-" not in form.cmd.data and \ "`" not in form.cmd.data and \ "<" not in form.cmd.data and \ ">" not in form.cmd.data: # Help allowed if form.cmd.data.startswith('help'): final_cmd = "help" results = help_cmd() # Ping allowed elif form.cmd.data.startswith('ping6'): final_cmd = re.sub('ping6', 'ping6 -n -i 0.1 -c 2', form.cmd.data) results = launch_cmd(final_cmd) # Traceroute allowed elif form.cmd.data.startswith('traceroute6'): final_cmd = re.sub('traceroute6', 'traceroute6 -w 2 -q 1 -m 10', form.cmd.data) results = launch_cmd(final_cmd) # Whois allowed elif form.cmd.data.startswith('whois'): final_cmd = re.sub('whois', 'whois -h whois.dn42', form.cmd.data) results = launch_cmd(final_cmd) # bird show allowed elif form.cmd.data.startswith('show'): final_cmd = "birdc6 " + form.cmd.data results = launch_cmd(final_cmd) # final_cmd = birdc show protocols and print error message else: results = launch_cmd(final_cmd) error_cmd() form.cmd.data = "" else: results = launch_cmd(final_cmd) error_cmd() else: results = launch_cmd(final_cmd) return render_template('home.html', form=form, final_cmd=final_cmd, results=results) @app.route('/status') def status(): ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr) return render_template('status.html', ip=str(ip)) <file_sep>{% block doc -%} <!DOCTYPE html> <html{% block html_attribs %}{% endblock html_attribs %}> {%- block html %} <head> {%- block head %} <title>{% block title %}{% endblock title %}</title> {%- block metas %} <meta name="viewport" content="width=device-width, initial-scale=1.0"> {%- endblock metas %} {%- block styles %} <!-- Bootstrap --> <link rel='ICON' type='image/x-icon' href='/static/img/bsd-logo.jpg'> <link href="/static/css/bootstrap.css" rel="stylesheet"> {%- endblock styles %} {%- endblock head %} </head> <body{% block body_attribs %}{% endblock body_attribs %}> {% block body -%} {% block navbar %} {%- endblock navbar %} {% block content -%} {%- endblock content %} {% block scripts %} <script src="/static/js/jquery.js"></script> <script src="/static/js/bootstrap.js"></script> {%- endblock scripts %} {%- endblock body %} <div id="copyright"> <hr><p align="right" style="margin-right:20px;"><font size=0.8em><a href="https://github.com/nicolasvion/birdy-src" target="_blank">Birdy</a> on the <a href="https://dn42.us" target="_blank">DN42 Network</a> - Created by <a href="http://nicolas.vion.science/cv/cv.pdf" target="_blank">n1colas</a></font></p> </div> </body> {%- endblock html %} </html> {% endblock doc -%} <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Flask from flask.ext.bootstrap import Bootstrap app = Flask(__name__) bootstrap = Bootstrap(app) app.config['SECRET_KEY'] = '<KEY>{9qsm:{*]6&-TP9F|s#<JPT!_g/\>;\ 74NXK/}z>.[)P~:Lk|Jrs~h8b=x"3X*<P7^\vJ5b_FNjF' from birdy import views <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- from wtforms import Form, StringField, SubmitField, validators class CommandForm(Form): cmd = StringField("Enter bird command (ex : show route) :", [validators.Required()]) submit = SubmitField('Submit') <file_sep># birdy-src A small looking glass for bird
334ce8989b20bf68bdc8e87ef993e4c331138f7b
[ "Markdown", "Python", "HTML" ]
6
Python
nicolasvion/birdy-src
0f06d9a5e8f6ba96346c954958e3af94b8824372
371a14022564cfc48dd7de56c774bac878ec4495
refs/heads/master
<file_sep>import Vue from 'vue' import App from './App' import VueRouter from 'vue-router' import VueResource from 'vue-resource' //路由 import Message from './views/message.vue' import Search from './views/search.vue' import Me from './views/me.vue' import Home from './views/home.vue' import pullToRefresh from './directives/pullToRefresh'; Vue.use(VueRouter); Vue.use(VueResource); //directive 自定义指令 Vue.directive('pullToRefresh', pullToRefresh); const router = new VueRouter({ mode: 'history', saveScrollPosition : true, //当用户点击后退时用popstate事件相应 routes: [ // a single route can define multiple named components // which will be rendered into <router-view>s with corresponding names. {path: '/', components: {default: Home,}}, {path: '/home', components: {default: Home,}}, {path: '/search', components: {default: Search}}, {path: '/message', components: {default: Message}}, {path: '/me', components: {default: Me}} ] }) window.router = router; /* eslint-disable no-new */ new Vue({ router, el: '#app', template: '<app/>', components: {App} }).$mount('#app') <file_sep>import Vue from 'vue' import App from './App' //import VueRouter from 'vue-router' //import routerConfig from './router' /* eslint-disable no-new */ new Vue({ el: '#app', template: '<App/>', components: { App } }) // Router /*Vue.use(VueRouter); var router = new VueRouter( { hashbang: true, //为true的时候 example.com/#!/foo/bar , false的时候 example.com/#/foo/bar //abstract:true, //地址栏不会有变化 //以下设置需要服务端设置 //history: false, //当使用 HTML5 history 模式时,服务器需要被正确配置 以防用户在直接访问链接时会遇到404页面。 //saveScrollPosition: false linkActiveClass:'custom-active-class' //全局设置连接匹配时的类名 参考http://vuejs.github.io/vue-router/en/link.html } ); routerConfig(router); router.start(App, '#app'); window.router = router;*/
d3e2aebbcb9b445bffd94f3b4739e6457b16f90a
[ "JavaScript" ]
2
JavaScript
a364514921/workplace-vue
5b7f4ebf40328d9026317ef49a9c20f615c652ed
efb7a724e3479871d7a28c85b46e0a543cb05869
refs/heads/master
<repo_name>kotatsumuri/otenkikun<file_sep>/wdata.py import serial,time def write_data(ser,status): #print(hex(status)) ser.write(chr(status).encode()) #time.sleep(1); <file_sep>/rand.py import random import time import sys while True: for i in range(208): print(chr(random.randint(33,126)),end="") print("\r") sys.stdout.flush() time.sleep(0.05) <file_sep>/jread.py import json def read(jsonfile,s): r=open(jsonfile,"r") dic=json.load(r) return str(dic[str(s)]) <file_sep>/otenkikun.php <html> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="otenkikun.css"> <title>NAMAEHAMADANAI</title> <link rel="shortcut icon" href="icon.ico"> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"> </head> <body class='section1'> <div class="title">SETUP</br></div> <label class="control-label"></label> <!--<div class="select-wrap select-primary">--> <form action="form.php" method="post"> <?php while(date('s')%2==0){ sleep(1); } $url = "info.json"; $json = file_get_contents($url); $arr = json_decode($json,TRUE); echo'<div class="time_title">ON TIME</div>'; echo '<div class="time_label">'; echo'<div class="select-wrap select-primary" >'; echo '<select class="time" id="hour" name="hour" >'; for($i=0;$i<=23;$i++){ if($i==$arr['hour']){ echo '<option value="'.$i.'"selected>'.$i.'h</option>'; } else{ echo '<option value="'.$i.'">'.$i.'h</option>'; } } echo '</select>'; echo '<select class="time" id="minute" name="minute">'; for($i=0;$i<=11;$i++){ if(($i*5)==$arr['minute']){ echo '<option value="'.($i*5).'"selected>'.($i*5).'m</option>'; } else{ echo '<option value="'.($i*5).'">'.($i*5).'m</option>'; } } echo '</select>'; echo '</br>'; echo '</div>'; echo '</div>'; echo'<div class="place_title">PLACE</div>'; echo'<div class="select-wrap select-primary">'; echo '<select id="place" name="place">'; // ◯◯◯.csvに先程保存したCSVファイル名を入力します。 $filename = 'place.csv'; // fopenでファイルを開きます。 $fp = fopen($filename, 'r'); $i=0; // CSVファイルの行数の数だけ実行 while($data = fgetcsv($fp)){ // csvファイルの列数だけ実行 if($data[1]==$arr['place']){ echo '<option value="'.$data[1].'"selected>'.$data[0].'</option>'; } else{ echo '<option value="'.$data[1].'">'.$data[0].'</option>'; } $i++; } // fcloseでファイルを閉じます。 fclose($fp); echo'</select>'; echo '</br>'; echo '</div>'; ?> <label class="label-checkbox"> <input type="checkbox" id='light' name='light' value='1'/> <span class="lever">LIGHT</span> </label> <input class='send' type="submit"  value="SEND"> </form> </body> </html> <file_sep>/form.php <html> <head><title>form.php</title> <link rel="stylesheet" type="text/css" href="form.css"></head> <body> <?php $place = $_POST['place']; $hour =$_POST['hour']; $minute =$_POST['minute']; $light=$_POST['light']; $value_arry=[ 'place'=>$place, 'hour'=>(int)$hour, 'minute'=>(int)$minute, 'light'=>(int)$light, 'now'=>(int)date('m')*60+(int)date('s') ]; while(date('s')%2==0){ sleep(1); } $jsonstr=json_encode($value_arry,JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT); file_put_contents("info.json",$jsonstr); //print($place); ?> <meta http-equiv ='Refresh' content='0;url=otenkikun.php'> </body> </html> <file_sep>/otenkikun/otenkikun.ino #include <Adafruit_NeoPixel.h> #define RGBLED_OUTPIN 8 #define NUMRGBLED 1 Adafruit_NeoPixel RGBLED = Adafruit_NeoPixel(NUMRGBLED, RGBLED_OUTPIN, NEO_RGB + NEO_KHZ800); int bright_var; int noti_counter=0; boolean noti_status=0; int tokidoki_counter=0; boolean tokidoki_status=0; byte get_value=0; int b_status=0; int b_weather=4; int a_weather=4; int weather_status=0; void setup() { Serial.begin(115200); RGBLED.begin() ; pinMode(9,INPUT); } int weather_pattarn[5][3]={{0xff,0x4f,0x00},{0x00,0x60,0xff},{0xb5,0xff,0xff},{0x00,0xff,0xa5},{0,0,0}}; //晴、雨、曇、雪 void loop() { if (Serial.available() > 0) { // 受信したデータが存在する get_value= Serial.read(); // 受信データを読み込む } date_sorting(get_value); btn(); if(b_status==1){ bright_var=bright_volume(); switch(weather_status){ case 0: only(b_weather,bright_var); break; case 1: tokidoki(b_weather,a_weather,bright_var); break; case 2: noti(b_weather,a_weather,bright_var); break; } } else if(b_status==2){ status_reset(); off(); } } void btn(){ int btn_value=digitalRead(9); switch(btn_value){ case 0: Serial.println('0'); break; case 1: Serial.println('1'); break; } } void status_reset(){ noti_counter=0; noti_status=0; tokidoki_counter=0; tokidoki_status=0; } int bright_volume(){ int var=analogRead(4); if(var>512) var=512; int bright=map(var,0,512,0,255); return bright; } void date_sorting(int var){ b_status=var/0x40; var=var%0x40; if(b_status==0){ a_weather=var/0x10; var=var%0x10; weather_status=var/0x04; var=var%0x04; b_weather=var; } } void only(int weather,int bright){ RGBLED.setBrightness(bright) ; RGBLED.setPixelColor(0, weather_pattarn[weather][0],weather_pattarn[weather][1],weather_pattarn[weather][2]) ; RGBLED.show() ; delay(1); } void noti(int before,int after,int bright){ int weather[2]={before,after}; RGBLED.setBrightness(bright*(-0.5*cos(PI/180*noti_counter)+0.5)) ; RGBLED.setPixelColor(0, weather_pattarn[weather[noti_status]][0],weather_pattarn[weather[noti_status]][1],weather_pattarn[weather[noti_status]][2]) ; RGBLED.show() ; delay(5); if(noti_status==true&&noti_counter==360) delay(1000); if(noti_counter==360){ noti_counter=0; noti_status=!noti_status; } noti_counter++; } void tokidoki(int before,int after,int bright){ int weather[2]={before,after}; if(tokidoki_counter<150||(tokidoki_counter>=250&&tokidoki_counter<400)){ RGBLED.setBrightness(bright) ; RGBLED.setPixelColor(0, weather_pattarn[weather[tokidoki_status]][0],weather_pattarn[weather[tokidoki_status]][1],weather_pattarn[weather[tokidoki_status]][2]) ; RGBLED.show(); delay(1); } if((tokidoki_counter>=150&&tokidoki_counter<250)||tokidoki_counter>=400){ RGBLED.setBrightness(0); RGBLED.show() ; delay(1); } tokidoki_counter++; if(tokidoki_counter==250 ||tokidoki_counter==1400) tokidoki_status=!tokidoki_status; if(tokidoki_counter>=1400) tokidoki_counter=0; } void off(){ RGBLED.setBrightness(0) ; RGBLED.show() ; } <file_sep>/main.py #!/anaconda3/bin/python3 import time from datetime import datetime, timezone, timedelta import wthr,wdata,jread import serial import os ser=0 for file in os.listdir('/dev'): if "cu.usb" in file: ser=serial.Serial('/dev/'+str(file),115200) time.sleep(1.5) info_name=['place','hour','minute','light','now'] info=[] for i in info_name: info.append(jread.read('info.json',str(i))) status=wthr.get_weather(str(info[0])) wdata.write_data(ser,status) wdata.write_data(ser,0x40) now =time.time() JST = timezone(timedelta(hours=+9), 'JST') loc = datetime.fromtimestamp(now,JST) start_second=loc.hour*3600+loc.minute*60+loc.second p_info='' p_info=str(info[0]) p=0 p=int(info[4]) while True: now =time.time() JST = timezone(timedelta(hours=+9), 'JST') loc = datetime.fromtimestamp(now,JST) r=ser.readline() if (loc.second)%2==0: p_info=str(info[0]) p=int(info[4]) for i in range(5): info[i]=jread.read('info.json',str(info_name[i])) if (loc.hour==5 or loc.hour==11 or loc.hour==17) and loc.minute==0 and loc.second==30: status=wthr.get_weather(str(info[0])) wdata.write_data(ser,status) now_second=loc.hour*3600+loc.minute*60+loc.second light_second=int(info[1])*3600+int(info[2])*60 s_second=light_second-600 f_second=light_second+600 if p_info!=str(info[0]): status=wthr.get_weather(str(info[0])) wdata.write_data(ser,status) wdata.write_data(ser,0x40) start_second=loc.hour*3600+loc.minute*60+loc.second elif p!=int(info[4]) and int(info[3])==0 : start_second=now_second-61 if s_second<0: s_second=24*3600+s_second if f_second>24*3600: f_second=s_second-24*3600 if now_second>s_second and now_second<f_second or r==b'0\r\n' or (p!=int(info[4]) and int(info[3])==1): wdata.write_data(ser,0x40) start_second=loc.hour*3600+loc.minute*60+loc.second if abs(now_second-start_second)>60 : wdata.write_data(ser,0x80) ser.close() <file_sep>/LED_test/LED_test.ino #include <Adafruit_NeoPixel.h> #define RGBLED_OUTPIN 4 #define NUMRGBLED 1 Adafruit_NeoPixel RGBLED = Adafruit_NeoPixel(NUMRGBLED, RGBLED_OUTPIN, NEO_RGB + NEO_KHZ800); void setup() { Serial.begin(9600); RGBLED.begin() ; pinMode(6,INPUT); } int val; void loop() { /*int var=analogRead(0); if(var>512) var=512; int bright=map(var,0,512,0,255); //Serial.println(var); RGBLED.setBrightness(bright) ; RGBLED.setPixelColor(0, 255,255,255) ; RGBLED.show() ; */ val=digitalRead(6); Serial.println(val); } <file_sep>/wthr.py # coding: UTF-8 import urllib.request from bs4 import BeautifulSoup import re import requests def get_weather(url): if url[0]=='h': html = urllib.request.urlopen(url) soup = BeautifulSoup(html, "html.parser") dic=soup.find_all(class_="pict") string=re.split('[><]',str(dic[0])) else: string=['0']*5 string[4]=url print(string[4]) array=[] char_pattern=['晴','雨','曇','雪','時','の'] for c in string[4]: for i in char_pattern: if c==i: array.append(c) status=0 for i in range(len(array)): for j in range(4): if array[i]==char_pattern[j]: status=status+j*pow(4,i) for k in range(2): if array[i]==char_pattern[k+4]: status=status+(k+1)*4 return status
8cfbcd08c96d84a5d3159bb5ffced9710b247603
[ "Python", "C++", "PHP" ]
9
Python
kotatsumuri/otenkikun
2a59db34eb3b33388a5f0c79e872372dad2ecd5e
581d761c3740e834dc7c4c80b5a8ee7d60765695
refs/heads/main
<file_sep>package main import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/x509" "encoding/pem" "fmt" "os" ) const ( PRIKEY = "private.pem" PUBKEY = "public.pem" ) func main() { // 生成公钥和私钥 buf, err := readKeyFile(PRIKEY) if err != nil { // 私钥不存在 生成并保存 privateKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) err = savePirvateKey(privateKey) if err != nil { fmt.Println(err) return } err = savePublicKey(privateKey.PublicKey) if err != nil { fmt.Println(err) return } // 重新读入数据 buf, err = readKeyFile(PRIKEY) } //============================================ // 解码数据流 block, _ := pem.Decode(buf) // 还原成私钥 privateKey, err := x509.ParseECPrivateKey(block.Bytes) if err != nil { fmt.Println(err) return } //============================================ buffer, err := readKeyFile(PUBKEY) // 解码数据流 b, _ := pem.Decode(buffer) // 还原成私钥 publicKey, err := x509.ParsePKIXPublicKey(b.Bytes) if err != nil { fmt.Println(err) return } //============================================ msg := []byte("dsa签名") // 对message进入签名操作 r, s, _ := ecdsa.Sign(rand.Reader, privateKey, msg) switch Key := publicKey.(type) { case *ecdsa.PublicKey: fmt.Println(ecdsa.Verify(Key, msg, r, s), "数据未被修改") default: fmt.Println(false, "数据已被修改") } } func readKeyFile(keyFile string) ([]byte, error) { file, err := os.Open(keyFile) if err != nil { return nil, err } defer file.Close() fileInfo, err := file.Stat() if err != nil { panic("file.Stat err!") } buf := make([]byte, fileInfo.Size()) file.Read(buf) return buf, nil } func savePirvateKey(p *ecdsa.PrivateKey) error { priByte, err := x509.MarshalECPrivateKey(p) if err != nil { return err } block := pem.Block{ Type: "PRIVATE KEY", Bytes: priByte, } file, err := os.Create("private.pem") if err != nil { return err } defer file.Close() // 写入私钥到文件存储 err = pem.Encode(file, &block) if err != nil { fmt.Println("写入私钥到文件出错了") return err } return nil } func savePublicKey(publicKey ecdsa.PublicKey) error { pub, err := x509.MarshalPKIXPublicKey(&publicKey) if err != nil { return err } block := pem.Block{ Type: "PUBLICK KEY", Bytes: pub, } file, err := os.Create("public.pem") if err != nil { return err } defer file.Close() // 写入私钥到文件存储 err = pem.Encode(file, &block) if err != nil { fmt.Println("写入公钥到文件出错了") return err } return nil } <file_sep>module "github.com/xushiwang/license"
e35e5ba3d64aa9f673988591f32a5e504e983f1d
[ "Go Module", "Go" ]
2
Go
xushiwang/license
c3ba3250b8afadd9968fa30e37f22e1ef311c35a
0d4cebe91788a7c5ffd982e3bf2eedf02e93defc
refs/heads/main
<file_sep>package com.example.rimodesignpart; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class LoginActivity extends AppCompatActivity { private Button loginBtn; private EditText phoneNumber,password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); loginBtn=findViewById(R.id.login_id); phoneNumber=findViewById(R.id.phoneNumber_id); password=findViewById(R.id.password_id); loginBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(LoginActivity.this,RegisterActivity.class)); } }); } }
1cc38ebcad1f33c56b148692e607d067fb1eb7ef
[ "Java" ]
1
Java
MdDoyalBabu/RIMOwalletProject
b4dabb1c92c9057f7f2c8b8dd99fc220a1f3895c
bdeddd61d67a3f32f0a52e86854ddf5e8352e9f2
refs/heads/master
<repo_name>EtsSimon9/BoardPro<file_sep>/BoardPro/src/map/ComposantMap.java package map; import utilitaire.Images; /** * classe abstraite de composantes contenant les proprietes propres a une map de * celles-ci * * @author <NAME> * */ public abstract class ComposantMap implements Comparable<ComposantMap>, Point { private short coordonneX; private short coordonneY; private Images image; public ComposantMap(short x, short y,Images image) { if (image != null) { this.setImage(image); } setCoordonneX(x); setCoordonneY(y); } public Images getImage() { return image; } public void setImage(Images image) { this.image = image; } @Override public short getCoordonneY() { return coordonneY; } @Override public short getCoordonneX() { return coordonneX; } @Override public void setCoordonneX(short coordonnex) { this.coordonneX = coordonnex; } @Override public void setCoordonneY(short coordonney) { this.coordonneY = coordonney; } @Override public int compareTo(ComposantMap obj) { return (Math.sqrt(coordonneX) + Math.sqrt(coordonneY)) >= (Math.sqrt(obj.getCoordonneX()) + Math.sqrt(obj.getCoordonneY())) ? 1 : 0; } } <file_sep>/BoardPro/src/tests/CalculTest.java package tests; import static org.junit.Assert.*; import org.junit.Test; import utilitaire.Calcul; import exceptions.MathException; public class CalculTest { @Test public void testFrequenceTofrequenceAngulaire() { float f = 20; assertTrue(Calcul.frequenceTofrequenceAngulaire(f) == (float) (f * 2 * Math.PI)); } @Test public void testFrequenceAngulaireTofrequence() { float fa = 20; assertTrue(Calcul.frequenceAngulaireTofrequence(fa) == (float) (fa / (2 * Math.PI))); } @Test public void testCapaciteCondensateur() { float ddp = 20; float q = 40; try { assertTrue(Calcul.capaciteCondensateur(ddp, q) == 2); } catch (MathException e) { fail(); } try { Calcul.capaciteCondensateur(0, q); fail(); } catch (MathException e) { } } @Test public void testChargeCondensateur() { assertTrue(Calcul.chargeCondensateur(20, 10) == 200); } @Test public void testDdpCondensateur() { try { assertTrue(Calcul.ddpCondensateur(10, 200) == 20); } catch (MathException e) { fail(); } try { Calcul.ddpCondensateur(0, 20); fail(); } catch (MathException e) { } } @Test public void testCapaciteCondensateurPlan() { try { Calcul.capaciteCondensateurPlan(50, 0); fail(); } catch (MathException e) { } try { assertTrue(Calcul.capaciteCondensateurPlan(20, 20) == (float) Calcul.epsilon); } catch (MathException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void testCapaciteCondensateurCylindrique() { try { Calcul.capaciteCondensateurCylindrique(20, 20, -1); fail(); } catch (MathException e) { } try { assertTrue(Calcul.capaciteCondensateurCylindrique(20, 20, 40) == (float) (10 / ((Calcul.k) * Math.log(2)))); } catch (MathException e) { fail(); } } @Test public void testCapaciteCondensateurSpherique() { try { Calcul.capaciteCondensateurSpherique(20, -20); fail(); } catch (MathException e) { } try { assertTrue(Calcul.capaciteCondensateurSpherique(20, 40) == (float) (4*Math.PI*Calcul.epsilon*20*40/(20))); } catch (MathException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void testCalculResistance() { try { Calcul.calculResistance(20, 20, 0); fail(); } catch (MathException e) { } try { assertTrue(Calcul.calculResistance(20, 20, 2) == (float) (400/(Math.PI*4))); } catch (MathException e) { fail(); } } @Test public void testResistiviteEtTemperature() { assertTrue(Calcul.resistiviteEtTemperature(2, 20, 30, 5) == 102); } @Test public void testLoiOhmR() { try { Calcul.loiOhmR(20, 0); fail(); } catch (MathException e) { } try { assertTrue(Calcul.loiOhmR(20, 2) == (float) (10)); } catch (MathException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void testLoiOhmDDP() { assertTrue(Calcul.loiOhmDDP(20, 2) == 40); } @Test public void testLoiOhmI() { try { Calcul.loiOhmI(0, 40); fail(); } catch (MathException e) { } try { assertTrue(Calcul.loiOhmI(20, 40) == 2); } catch (MathException e) { fail(); } } @Test public void testChargeCondensateurDecharge() { } @Test public void testDdpCondesateurDecharge() { } @Test public void testCourantCondensateurDecharge() { } @Test public void testChargeCondensateurCharge() { } @Test public void testDdpCondesateurCharge() { } @Test public void testCourantCondensateurCharge() { } @Test public void testCourantDeplug() { } @Test public void testCourantPlug() { } @Test public void testImpedanceCircuitRLC() { } @Test public void testImpedanceCondensateur() { } @Test public void testImpedanceBobine() { } } <file_sep>/BoardPro/src/utilitaire/Calcul.java package utilitaire; import exceptions.MathException; import vue.ControleurVue; /** * Classe remplit de calcul utile en �lectricit�, toutes les formules et quelque * constante utile vue lors de notre cours d'�lectricit� y sont. Des * commentaires s�pares les sections pour mieux s'y retrouver. Ajouter des * m�thode de calculs au besoins. * * @author <NAME> * */ public class Calcul { public static final double chargeE = 1.602 * Math.pow(10, -19); public static final double masseElectron = 9.109 * Math.pow(10, -31); public static final double masseProton = 1.672 * Math.pow(10, -27); public static final double k = 9 * Math.pow(10, 9); public static final double epsilon = 8.854 * Math.pow(10, -12); /* * Section calcul de fr�quence * * * * * * * * * */ /** * Prend une fr�quence (en Hz) et retourne la fr�quence angulaire (en rad/s) */ public static float frequenceTofrequenceAngulaire(float frequence) { return (float) (2 * Math.PI * frequence); } /** * Prend une fr�quence angulaire (en rad/s) et retourne la fr�quence (en Hz) */ public static float frequenceAngulaireTofrequence(float frequenceAngulaire) { return (float) (frequenceAngulaire / (2 * Math.PI)); } /* * Section Condensateur * * * * * * * * * * * */ /** * Donne la capacit� du condensateur, ce calcul � besoin de la diff�rence de * potentielle et la charge sur le condensateur */ public static float capaciteCondensateur(float ddp, float q) throws MathException { float c = 0; if (ddp != 0) { c = q / ddp; } else { throw new MathException("Charge du condensateur null!"); } return c; } /** * Donne la charge sur le condensateur, ce calcul � besoin de la diff�rence de * potentielle et la capacit� du condensateur */ public static float chargeCondensateur(float ddp, float c) { return ddp * c; } /** * Donne la diff�rence de potentielle au bornes du condensateur, ce cacul � * besoin de la capacit� du condensateur et de la charge sur celui-ci. */ public static float ddpCondensateur(float c, float q) throws MathException { float ddp = 0; if (c != 0) { ddp = q / c; } else { throw new MathException("Charge du condensateur = 0!"); } return ddp; } /** * Utile pour des condensateurs customs, calcul de la capacite d'un condensateur * plan. Ce calcul � besoin de l'aire des branches qui peuvent �tre * carr�,rectangle,cercle donc on se contente de recevoir l'aire en param, et * aussi la distance entre les deux branches */ public static float capaciteCondensateurPlan(float aire, float distance) throws MathException { float capacite = 0; if (distance != 0) { capacite = (float) (Calcul.epsilon * aire / distance); } else { throw new MathException("distance entre 2 armatures de condensateur null!"); } return capacite; } /** * Utile pour des condensateurs customs, calcul de la capacite d'un condensateur * cylindrique Ce calcul � besoin de la longueur des cylindres, le rayonA du * plus petit et le rayonB du plus grand. */ public static float capaciteCondensateurCylindrique(float longueur, float rayonA, float rayonB) throws MathException { float capacite = 0; if (rayonA > 0 && rayonB > 0) { capacite = (float) (longueur / (2 * Calcul.k * Math.log(rayonB / rayonA))); } else { throw new MathException("Rayon du condensateur cylindrique invalide"); } return capacite; } /** * Utile pour des condensateurs customs, calcul de la capacit� d'un condensateur * spherique. Ce calcul � besoin du rayon de la petite sph�re rayonA et du rayon * de la grande sph�re rayonB */ public static float capaciteCondensateurSpherique(float rayonA, float rayonB) throws MathException { float capacite = 0; if (rayonB > rayonA) { capacite = (float) (4 * Math.PI * Calcul.epsilon * rayonA * rayonB / (rayonB - rayonA)); } else { throw new MathException("Rayon du condensateur cylindrique invalide"); } return capacite; } /* * Section r�sistor * * * * * * * * * * */ /** * Calcul de la r�sistance d'une r�sistance custom. Ce calcul � besoin de la * r�sistivit� du mat�riau p, de la longueur de la r�sistance et du rayon du * fil/r�sistor * @throws MathException */ public static float calculResistance(double p, float l, float rayon) throws MathException { float r = 0; if (rayon != 0) { r = (float) ((p * l) / (Math.PI * rayon * rayon)); } else { throw new MathException("Rayon de la résistance null!"); } return r; } /** * Calcul de la r�sistivit� (variant avec la temp�rature) custom d'une * r�sistance custom. Ce calcul � besoin de la r�sistvit� du mat�riaux � 20� pi, * de la temp�rature initiale ti (20� souvent) , de la temp�rature finale et du * coefficient thermique (le symbole est alpha) Voir p.199 du Lafrance pour + * d'info. */ public static double resistiviteEtTemperature(double resisti, float ti, float tf, double coef) { float deltaT = tf - ti; return (resisti * (1 + (coef * deltaT))); } /** * Calcul loi d'ohm trouvant la r�sistance */ public static float loiOhmR(float ddp, float i) throws MathException { float retour; if (i != 0) { retour = ddp / i; } else { throw new MathException("division par zero!"); } return retour; } /** * Calcul loi d'ohm trouvant la diff�rence de potentielle */ public static float loiOhmDDP(float r, float i) { return r * i; } /** * Calcul loi d'ohm trouvant le courant I */ public static float loiOhmI(float r, float ddp) throws MathException { float retour; if (r != 0) { retour = ddp / r; } else { throw new MathException("division par zero!"); } return retour; } /* * Section circuit RC : r�sistance condensateur * * * * * * * * * * */ /** * Circuit RC Calcul trouvant la charge d'un condensateur qui est en d�charge, * cette charge varie dans le temps selon une exponentielle inverse. Ce calcul � * besoin de la charge maximale du condensateur, du temps �coul� depuis le d�but * de la d�charge, de la r�sistance du r�sistor dans le circuit et de la * capacit� du condensateur */ public static float ChargeCondensateurDecharge(float ChargeMax, float t, float R, float C) { return (float) (ChargeMax * Math.exp((-t) / (R * C))); } /** * Circuit RC Calcul trouvant la diff�rence de potentielle d'un condensateur qui * est en d�charge, cette DDP varie dans le temps selon une exponentielle * inverse. Ce calcul � besoin de la diff�rence de potentielle maximale du * condensateur, du temps �coul� depuis le d�but de la d�charge, de la * r�sistance du r�sistor dans le circuit et de la capacit� du condensateur */ public static float ddpCondesateurDecharge(float ddpMax, float t, float R, float C) { return (float) (ddpMax * Math.exp((-t) / (R * C))); } /** * Circuit RC Calcul trouvant le courant d'un condensateur qui est en d�charge, * ce courant varie dans le temps selon une exponentielle inverse. Ce calcul � * besoin du courant maximal du condensateur, du temps �coul� depuis le d�but de * la d�charge, de la r�sistance du r�sistor dans le circuit et de la capacit� * du condensateur */ public static float courantCondensateurDecharge(float courantMax, float t, float R, float C) { return (float) (courantMax * Math.exp((-t) / (R * C))); } /** * Circuit RC Calcul trouvant la charge d'un condensateur qui est en charge, * cette charge varie dans le temps selon un exponentielle. Ce calcul � besoin * de la charge maximal du condensateur, du temps �coul� depuis le d�but de la * charge, de la r�sistance du r�sistor dans le circuit et de la capacit� du * condensateur */ public static float ChargeCondensateurCharge(float ChargeMax, float t, float R, float C) { return (float) (ChargeMax * (1 - Math.exp((-t) / (R * C)))); } /** * Circuit RC Calcul trouvant la diff�rence de potentielle d'un condensateur qui * est en charge, cette DDP varie dans le temps selon un exponentielle. Ce * calcul � besoin de la DDP maximal du condensateur, du temps �coul� depuis le * d�but de la charge, de la r�sistance du r�sistor dans le circuit et de la * capacit� du condensateur. */ public static float ddpCondesateurCharge(float ddpMax, float t, float R, float C) { return (float) (ddpMax * (1 - Math.exp((-t) / (R * C)))); } /** * Circuit RC Calcul trouvant le courant dans un d'un condensateur qui est en * charge, ce courant varie dans le temps selon un exponentielle. Ce calcul � * besoin du courant maximal du condensateur, du temps �coul� depuis le d�but de * la charge, de la r�sistance du r�sistor dans le circuit et de la capacit� du * condensateur. */ public static float courantCondensateurCharge(float courantMax, float t, float R, float C) { return (float) (courantMax * (1 - Math.exp((-t) / (R * C)))); } /* * Section circuit RL: r�sistance bobine d'inductance * * * * * * * * * * */ /** * Circuit RL Calcul trouvant le courant dans le circuit RL suite � l'ouverture * du circuit, ce courant varie dans le temps selon une exponentiel inverser * (chute de courant amortie, max a min avec courbe) */ public static float CourantDeplug(float CourantMax, float t, float R, float L) { return (float) (CourantMax * Math.exp((-t * R) / L)); } /** * Circuit RL Calcul trouvant le courant dans le circuit RL suite � la fermeture * du circuit Le cournat varie dans le temps selon une exponentiel (augmentation * rapide de courant amortie) */ public static float CourantPlug(float CourantMax, float t, float R, float L) { return (float) (1 - (CourantMax * Math.exp((-t * R) / L))); } /* * Section circuit RLC: R�sistance, bobine d'inductance et condensateur * * * * * * * * * */ /** * Circuit RLC Trouve l'impedance/r�sistance d'un circuit RLC */ public static float impedanceCircuitRLC(float resistance, float inductance, float capacite, float frequence) throws MathException { float z = 0; if (resistance >= 0 && capacite >= 0 && inductance >= 0) { float freqAngulaire = Calcul.frequenceTofrequenceAngulaire(frequence); float xc = Calcul.impedanceCondensateur(freqAngulaire, capacite); float xl = Calcul.impedanceBobine(freqAngulaire, inductance); z = (float) Math.sqrt(Math.pow(resistance, 2) + Math.pow(xl-xc, 2) ); } else { throw new MathException("Resistance, inductance ou capacite n�gative dans le calcul d'imp�dence RLC"); } return z; } /** * Calcul l'impedance d'un condensateur */ public static float impedanceCondensateur(float frequence, float capacite) throws MathException { float impedanceCondensateur = 0; if (frequence != 0 && capacite != 0) { float freqangulaire = Calcul.frequenceTofrequenceAngulaire(frequence); impedanceCondensateur = 1 / (freqangulaire * capacite); } else { throw new MathException("frequence ou capacite nul!"); } return impedanceCondensateur; } /** * Calcul l'impedance d'une bobine */ public static float impedanceBobine(float frequence, float inductance) { float impedanceBobine = 0; float freqangulaire = Calcul.frequenceTofrequenceAngulaire(frequence); impedanceBobine = freqangulaire * inductance; return impedanceBobine; } /** * Puisque la méthode get des gridPanes n'existe pas et on doit aller dans la liste des childrens, * cette méthode s'occupe de nous dire à quel position une composante est dans la children list en fonction * de sa position * @param x * @param y * @return Retourne la position ou -1 si pas trouver */ public static int positionDansGrille(int x,int y,ControleurVue vue) { int position = -1; for (int i = 0; i < vue.gridP.getChildren().size();i++) { int px = (int) (Math.floor((vue.gridP.getChildren().get(i).getLayoutX() + 50) / 75)); int py = (int) (Math.floor((vue.gridP.getChildren().get(i).getLayoutY() + 20 )/ 75)); if (px == x && py == y) { position = i; } } return position; } } <file_sep>/BoardPro/src/application/MainApp.java package application; import controleur.ControleurBoardPro; import javafx.application.Application; import javafx.stage.Stage; import javafx.stage.StageStyle; import javafx.stage.Window; import vue.ControleurVue; public class MainApp extends Application { private ControleurBoardPro controleur; private ControleurVue vue; public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage primaryStage) throws Exception { controleur = new ControleurBoardPro(); vue = controleur.getVue(); controleur.masterHandler(); primaryStage.setScene(vue.getScene()); primaryStage.initStyle(StageStyle.UNDECORATED); primaryStage.show(); primaryStage.setResizable(false); } public static Window getStage() { // TODO Auto-generated method stub return null; } } <file_sep>/BoardPro/src/utilitaire/Images.java package utilitaire; import java.util.ArrayList; import java.util.HashSet; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import map.ComposantMap; public class Images { public enum Composante { FilH, FilV, FilBD, FilBG, FilHG, FilHD, FilGBD, FilGHD, FilBGH, FilBDH, FilAll, Résistance, Condensateur, Bobine, Ampoule, Source }; private byte positionX; private byte positionY; private ImageView view; private Image image; private Composante nom; private static final short DIMMENSIONS = 75; private int rotation = 0; private String equationDDP = ""; private ComposantMap c; /** * dghb :Droite Gauche Haut Bas, si une image est directement à gauche de cette * image, la 2e valeur de l'arraylist est 1, sinon 0. Droite:1er position, * Gauche 2e position, Haut 3e et Bas 4e dans l'array */ private byte[] dghb; public Images(Composante nom, byte px, byte py) { if (nom != null) { this.setNom(nom); } dghb = new byte[4]; this.setPositionX(px); this.setPositionY(py); creerImage(nom); creerView(); } public ComposantMap getC() { return c; } public void setC(ComposantMap c) { this.c = c; } public String getEquationDDP() { return equationDDP; } public void setEquationDDP(String equationDDP) { this.equationDDP = equationDDP; } public int getRotation() { return rotation; } public void setRotation(int rotation) { this.rotation = rotation; } public Composante getNom() { return nom; } public void setNom(Composante nom) { this.nom = nom; } public byte getPositionX() { return positionX; } public void setPositionX(byte positionX) { this.positionX = positionX; } public byte getPositionY() { return positionY; } public void setPositionY(byte positionY) { this.positionY = positionY; } public ImageView getView() { return view; } public void setView(ImageView view) { this.view = view; } public Image getImage() { return image; } public void setImage(Image image) { this.image = image; } public void creerImage(Composante nom) { Image i = null; if (nom.equals(Composante.Résistance)) { i = new Image("/img/Composante_resistance.png"); } else if (nom.equals(Composante.Condensateur)) { i = new Image("/img/condensateur.png"); } else if (nom.equals(Composante.Bobine)) { i = new Image("/img/bobine.png"); } else if (nom.equals(Composante.FilAll)) { i = new Image("/img/4way.png"); } else if (nom.equals(Composante.FilH)) { i = new Image("/img/Composante_fil.png"); this.setRotation(0); } else if (nom.equals(Composante.FilV)) { i = new Image("/img/Composante_fil.png"); this.setRotation(90); } else if (nom.equals(Composante.FilBD)) { i = new Image("/img/coin.png"); this.setRotation(180); } else if (nom.equals(Composante.FilBG)) { i = new Image("/img/coin.png"); this.setRotation(270); } else if (nom.equals(Composante.FilHD)) { i = new Image("/img/coin.png"); this.setRotation(90); } else if (nom.equals(Composante.FilHG)) { i = new Image("/img/coin.png"); this.setRotation(0); } else if (nom.equals(Composante.FilBGH)) { i = new Image("/img/3 way.png"); this.setRotation(270); } else if (nom.equals(Composante.FilBDH)) { i = new Image("/img/3 way.png"); this.setRotation(90); } else if (nom.equals(Composante.FilGBD)) { i = new Image("/img/3 way.png"); this.setRotation(180); } else if (nom.equals(Composante.FilGHD)) { i = new Image("/img/3 way.png"); this.setRotation(0); } else if (nom.equals(Composante.Source)) { i = new Image("/img/source.png"); } else if (nom.equals(Composante.Ampoule)) { i = new Image("/img/ampouleEteinte.png"); } this.setImage(i); } public void creerView() { ImageView v = null; if (image != null) { v = new ImageView(this.getImage()); v.setFitWidth(DIMMENSIONS); v.setFitHeight(DIMMENSIONS); v.setRotate(this.getRotation()); } this.setView(v); } public byte[] getDghb() { return dghb; } public void setDghb(byte[] dghb) { this.dghb = dghb; } /** * * @param listeImage * @return Retourne un tableau des index des composantes qui doivent être * changer (on a ajouter qq chose près) */ public HashSet<Byte> composanteProche(ArrayList<Images> listeImage) { HashSet<Byte> indexaModif = new HashSet<Byte>(); // Vérification à Droite for (int i = 0; i < listeImage.size(); i++) { if (listeImage.get(i).getPositionX() == positionX + 1 && listeImage.get(i).getPositionY() == positionY) { this.dghb[0] = 1; // Puisque l'image à gauche doit aussi considérer l'image actuelle à sa droite listeImage.get(i).getDghb()[1] = 1; indexaModif.add((byte) i); } } // Vérification à Gauche for (int i = 0; i < listeImage.size(); i++) { if (listeImage.get(i).getPositionX() == positionX - 1 && listeImage.get(i).getPositionY() == positionY) { this.dghb[1] = 1; // Puisque l'image à gauche doit aussi considérer l'image actuelle à sa droite listeImage.get(i).getDghb()[0] = 1; indexaModif.add((byte) i); } } // Vérification Haut for (int i = 0; i < listeImage.size(); i++) { if (listeImage.get(i).getPositionX() == positionX && listeImage.get(i).getPositionY() == positionY - 1) { this.dghb[2] = 1; // Puisque l'image à gauche doit aussi considérer l'image actuelle à sa gauche listeImage.get(i).getDghb()[3] = 1; indexaModif.add((byte) i); } } // Vérification Bas for (int i = 0; i < listeImage.size(); i++) { if (listeImage.get(i).getPositionX() == positionX && listeImage.get(i).getPositionY() == positionY + 1) { this.dghb[3] = 1; // Puisque l'image à gauche doit aussi considérer l'image actuelle à sa gauche listeImage.get(i).getDghb()[2] = 1; indexaModif.add((byte) i); } } return indexaModif; } public Composante choisirImage(Images i) { Composante retour = null; if (i.dghb[2] == 1 || i.dghb[3] == 1) { i.setRotation(90); } if (i.dghb[0] == 1 || i.dghb[1] == 1) { i.setRotation(0); } if (i.dghb[2] == 1 && i.dghb[3] == 1) { i.setRotation(90); } if (i.dghb[0] == 1 && i.dghb[1] == 1) { i.setRotation(0); } if (i.getNom().toString().substring(0, 3).equals("Fil")) { retour = choisirImageFil(i); } else if (i.getNom().equals(Composante.Condensateur)) { retour = Composante.Condensateur; } else if (i.getNom().equals(Composante.Ampoule)) { retour = Composante.Ampoule; } else if (i.getNom().equals(Composante.Bobine)) { retour = Composante.Bobine; } else if (i.getNom().equals(Composante.Résistance)) { retour = Composante.Résistance; } else if (i.getNom().equals(Composante.Source)) { retour = Composante.Source; } return retour; } public Composante choisirImageFil(Images i) { Composante retour = Composante.FilH; if (i.getDghb()[0] == 1 && i.getDghb()[1] == 1 && i.getDghb()[2] == 1 && i.getDghb()[3] == 1) { retour = Composante.FilAll; } else if (i.getDghb()[0] == 1 && i.getDghb()[1] == 1 && i.getDghb()[2] == 1 && i.getDghb()[3] == 0) { retour = Composante.FilGHD; } else if (i.getDghb()[0] == 1 && i.getDghb()[1] == 1 && i.getDghb()[2] == 0 && i.getDghb()[3] == 1) { retour = Composante.FilGBD; } else if (i.getDghb()[0] == 1 && i.getDghb()[1] == 0 && i.getDghb()[2] == 1 && i.getDghb()[3] == 1) { retour = Composante.FilBDH; } else if (i.getDghb()[0] == 0 && i.getDghb()[1] == 1 && i.getDghb()[2] == 1 && i.getDghb()[3] == 1) { retour = Composante.FilBGH; } else if (i.getDghb()[0] == 1 && i.getDghb()[1] == 0 && i.getDghb()[2] == 0 && i.getDghb()[3] == 1) { retour = Composante.FilBD; } else if (i.getDghb()[0] == 0 && i.getDghb()[1] == 1 && i.getDghb()[2] == 0 && i.getDghb()[3] == 1) { retour = Composante.FilBG; } else if (i.getDghb()[0] == 0 && i.getDghb()[1] == 1 && i.getDghb()[2] == 1 && i.getDghb()[3] == 0) { retour = Composante.FilHG; } else if (i.getDghb()[0] == 1 && i.getDghb()[1] == 0 && i.getDghb()[2] == 1 && i.getDghb()[3] == 0) { retour = Composante.FilHD; } if (i.getDghb()[0] == 1 && i.getDghb()[1] == 1 && i.getDghb()[2] == 0 && i.getDghb()[3] == 0) { retour = Composante.FilH; } else if (i.getDghb()[0] == 0 && i.getDghb()[1] == 0 && i.getDghb()[2] == 1 && i.getDghb()[3] == 1) { retour = Composante.FilV; } else if (i.getDghb()[0] == 0 && i.getDghb()[1] == 0 && i.getDghb()[2] == 1 && i.getDghb()[3] == 0) { retour = Composante.FilV; } else if (i.getDghb()[0] == 0 && i.getDghb()[1] == 0 && i.getDghb()[2] == 0 && i.getDghb()[3] == 1) { retour = Composante.FilV; } return retour; } public HashSet<Byte> modifierAutourRetrait(ArrayList<Images> listeImage) { HashSet<Byte> indexaModif = new HashSet<Byte>(); // Vérification à Droite for (int i = 0; i < listeImage.size(); i++) { if (listeImage.get(i).getPositionX() == positionX + 1 && listeImage.get(i).getPositionY() == positionY) { listeImage.get(i).getDghb()[1] = 0; indexaModif.add((byte) i); } } // Vérification à Gauche for (int i = 0; i < listeImage.size(); i++) { if (listeImage.get(i).getPositionX() == positionX - 1 && listeImage.get(i).getPositionY() == positionY) { // Puisque l'image à gauche doit aussi considérer l'image actuelle à sa droite listeImage.get(i).getDghb()[0] = 0; indexaModif.add((byte) i); } } // Vérification Haut for (int i = 0; i < listeImage.size(); i++) { if (listeImage.get(i).getPositionX() == positionX && listeImage.get(i).getPositionY() == positionY - 1) { // Puisque l'image à gauche doit aussi considérer l'image actuelle à sa gauche listeImage.get(i).getDghb()[3] = 0; indexaModif.add((byte) i); } } // Vérification Bas for (int i = 0; i < listeImage.size(); i++) { if (listeImage.get(i).getPositionX() == positionX && listeImage.get(i).getPositionY() == positionY + 1) { // Puisque l'image à gauche doit aussi considérer l'image actuelle à sa gauche listeImage.get(i).getDghb()[2] = 0; indexaModif.add((byte) i); } } return indexaModif; } } <file_sep>/BoardPro/src/tests/MapParcourableTest.java package tests; import static org.junit.Assert.assertTrue; // -------- import java.util.ArrayList; import org.ejml.simple.SimpleMatrix; import org.junit.Before; import org.junit.Test; import composantesCircuit.Fil; import composantesCircuit.Resistance; import exceptions.ComposantException; import map.ComposantMap; import map.MapParcourable; import utilitaire.MatriceUtilitaires; public class MapParcourableTest { MapParcourable map1, map2, map3,map4; Resistance res1, res2, res3, res4, res5; @Before public void mapParcourableTest() { map1 = new MapParcourable(); map2 = new MapParcourable(); map3 = new MapParcourable(); map4 = new MapParcourable(); try { res1 = new Resistance(0,(short) 0, (short) 0,null); res2 = new Resistance(0,(short) 0, (short) 1,null); res3 = new Resistance(0,(short) 1, (short) 0,null); res4 = new Resistance(0,(short) 1, (short) 3,null); res5 = new Resistance(0,(short) 3, (short) 1,null); } catch (ComposantException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void testgenrerNoeuds() { Fil fil1, fil3, fil5, fil7; Resistance res6 = null, res8 = null; // voici un circtuit de forme // // o-o // | | // o-o // les {-,|} sont des resistances et {o} representent des composantes try { fil1 = new Fil((short) 30, (short) 30,null); res2 = new Resistance(0,(short) 30, (short) 31,null); fil3 = new Fil((short) 30, (short) 32,null); res4 = new Resistance(0,(short) 31, (short) 32,null); res4.setSens(true); fil5 = new Fil((short) 32, (short) 32,null); res6 = new Resistance(0,(short) 32, (short) 31,null); fil7 = new Fil((short) 32, (short) 30,null); res8 = new Resistance(0,(short) 31, (short) 30,null); res8.setSens(true); map1.addComposant(fil1); map1.addComposant(res2); map1.addComposant(fil3); map1.addComposant(res4); map1.addComposant(fil5); map1.addComposant(res6); map1.addComposant(fil7); map1.addComposant(res8); } catch (ComposantException e) { // TODO Auto-generated catch block e.printStackTrace(); } map1.genrerNoeuds(); assertTrue(map1.getNoeudsCircuit().size()==0); Fil fil10, fil12; Resistance res9, res11 = null, res13 = null; try { // voici un circtuit de forme // // o-o-o // | | | // o-o-o // les {-,|} sont des resistances et {o} representent des composantes fil1 = new Fil((short) 0, (short) 0,null); res2 = new Resistance(0,(short) 0, (short) 1,null); fil3 = new Fil((short) 0, (short) 2,null); res4 = new Resistance(0,(short) 1, (short) 2,null); res4.setSens(true); fil5 = new Fil((short) 2, (short) 2,null); res6 = new Resistance(0,(short) 2, (short) 1,null); fil7 = new Fil((short) 2, (short) 0,null); res8 = new Resistance(0,(short) 1, (short) 0,null); res8.setSens(true); res9 = new Resistance(0,(short) 0, (short) 3,null); fil10 = new Fil((short) 0, (short) 4,null); res11 = new Resistance(0,(short) 1, (short) 4,null); res11.setSens(true); fil12 = new Fil((short) 2, (short) 4,null); res13 = new Resistance(0,(short) 2, (short) 3,null); map2.addComposant(fil1); map2.addComposant(res2); map2.addComposant(fil3); map2.addComposant(res4); map2.addComposant(fil5); map2.addComposant(res6); map2.addComposant(fil7); map2.addComposant(res8); map2.addComposant(res9); map2.addComposant(fil10); map2.addComposant(res11); map2.addComposant(fil12); map2.addComposant(res13); } catch (ComposantException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } map2.genrerNoeuds(); assertTrue(map2.getNoeudsCircuit().size()==2); } @Test public void testGetMaillsesCircuitsFermes() { Fil fil1, fil3, fil5, fil7; Resistance res6, res8; try { // voici un circtuit de forme // // o-o // | | // o-o // les {-,|} sont des resistances et {o} representent des composantes fil1 = new Fil((short) 30, (short) 30,null); res2 = new Resistance(0,(short) 30, (short) 31,null); fil3 = new Fil((short) 30, (short) 32,null); res4 = new Resistance(0,(short) 31, (short) 32,null); res4.setSens(true); fil5 = new Fil((short) 32, (short) 32,null); res6 = new Resistance(0,(short) 32, (short) 31,null); fil7 = new Fil((short) 32, (short) 30,null); res8 = new Resistance(0,(short) 31, (short) 30,null); res8.setSens(true); map1.addComposant(fil1); map1.addComposant(res2); map1.addComposant(fil3); map1.addComposant(res4); map1.addComposant(fil5); map1.addComposant(res6); map1.addComposant(fil7); map1.addComposant(res8); } catch (ComposantException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } map1.genererMailles(); map3.setMaillesCircuitsFermes(map1.getMaillesCircuitsFermes()); assertTrue(map3.getMaillesCircuitsFermes() == map1.getMaillesCircuitsFermes()); } @Test public void testSetMaillsesCircuitsFermes() { Fil fil1, fil3, fil5, fil7; Resistance res6, res8; try { // voici un circtuit de forme // // o-o // | | // o-o // les {-,|} sont des resistances et {o} representent des composantes fil1 = new Fil((short) 5, (short) 5,null); res2 = new Resistance(0,(short) 5, (short) 6,null); fil3 = new Fil((short) 5, (short) 7,null); res4 = new Resistance(0,(short) 6, (short) 7,null); res4.setSens(true); fil5 = new Fil((short) 7, (short) 7,null); res6 = new Resistance(0,(short) 7, (short) 6,null); fil7 = new Fil((short) 7, (short) 5,null); res8 = new Resistance(0,(short) 6, (short) 5,null); res8.setSens(true); map1.addComposant(fil1); map1.addComposant(res2); map1.addComposant(fil3); map1.addComposant(res4); map1.addComposant(fil5); map1.addComposant(res6); map1.addComposant(fil7); map1.addComposant(res8); } catch (ComposantException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } map1.genererMailles(); map2.setMaillesCircuitsFermes(map1.getMaillesCircuitsFermes()); assertTrue(map2.getMaillesCircuitsFermes() == map1.getMaillesCircuitsFermes()); } @Test public void testGenrerNoeuds() { // Test pas encore disponible puisque cette partie n est pas a faire pour le // deuxieme sprint } @Test public void testGenererMailles() { try { map3.addComposant(res1); map3.addComposant(res2); map3.addComposant(res3); map3.addComposant(res4); map3.addComposant(res5); } catch (ComposantException e) { // TODO Auto-generated catch block e.printStackTrace(); } map3.genererMailles(); assertTrue(map3.getMaillesCircuitsFermes().size() == 0); Fil fil1, fil3, fil5, fil7; Resistance res6, res8; try { // voici un circtuit de forme // // o-o // | | // o-o // les {-,|} sont des resistances et {o} representent des composantes fil1 = new Fil((short) 0, (short) 0,null); res2 = new Resistance(0,(short) 0, (short) 1,null); res2.setSens(true); fil3 = new Fil((short) 0, (short) 2,null); res4 = new Resistance(0,(short) 1, (short) 2,null); fil5 = new Fil((short) 2, (short) 2,null); res6 = new Resistance(0,(short) 2, (short) 1,null); res6.setSens(true); fil7 = new Fil((short) 2, (short) 0,null); res8 = new Resistance(0,(short) 1, (short) 0,null); map1.addComposant(fil1); map1.addComposant(res2); map1.addComposant(fil3); map1.addComposant(res4); map1.addComposant(fil5); map1.addComposant(res6); map1.addComposant(fil7); map1.addComposant(res8); } catch (ComposantException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } map1.genererMailles(); ArrayList<ComposantMap> composantsActuels = map1.getComposantsActuels(); ArrayList<ArrayList<ComposantMap>> maillsesCircuitsFermes = map1.getMaillesCircuitsFermes(); for (int i = 0; i < maillsesCircuitsFermes.size(); i++) { for (ComposantMap comp : maillsesCircuitsFermes.get(i)) { assertTrue(composantsActuels.contains(comp)); } assertTrue(maillsesCircuitsFermes.get(i).size() == 8); } Fil fil10, fil12; Resistance res9, res11, res13; try { // voici un circtuit de forme // // o-o-o // | | | // o-o-o // les {-,|} sont des resistances et {o} representent des composantes fil1 = new Fil((short) 0, (short) 0,null); res2 = new Resistance(0,(short) 0, (short) 1,null); res2.setSens(true); fil3 = new Fil((short) 0, (short) 2,null); res4 = new Resistance(0,(short) 1, (short) 2,null); fil5 = new Fil((short) 2, (short) 2,null); res6 = new Resistance(0,(short) 2, (short) 1,null); res6.setSens(true); fil7 = new Fil((short) 2, (short) 0,null); res8 = new Resistance(0,(short) 1, (short) 0,null); res9 = new Resistance(0,(short) 0, (short) 3,null); res9.setSens(true); fil10 = new Fil((short) 0, (short) 4,null); res11 = new Resistance(0,(short) 1, (short) 4,null); fil12 = new Fil((short) 2, (short) 4,null); res13 = new Resistance(0,(short) 2, (short) 3,null); res13.setSens(true); map2.addComposant(fil1); map2.addComposant(res2); map2.addComposant(fil3); map2.addComposant(res4); map2.addComposant(fil5); map2.addComposant(res6); map2.addComposant(fil7); map2.addComposant(res8); map2.addComposant(res9); map2.addComposant(fil10); map2.addComposant(res11); map2.addComposant(fil12); map2.addComposant(res13); } catch (ComposantException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } map2.genererMailles(); maillsesCircuitsFermes = map2.getMaillesCircuitsFermes(); // verifie qu il y a 6 mailles produites assertTrue(maillsesCircuitsFermes.size() == 6); byte nombreMaillesDeHuit = 4; byte nombreMaillesDeDouze = 2; for (int i = 0; i < maillsesCircuitsFermes.size(); i++) { if (maillsesCircuitsFermes.get(i).size() == 8) { nombreMaillesDeHuit--; } if (maillsesCircuitsFermes.get(i).size() == 12) { nombreMaillesDeDouze--; } } // veririfie qu il y a 2 maille de 12 composantes et 4 de 8 assertTrue(nombreMaillesDeHuit == 0); assertTrue(nombreMaillesDeDouze == 0); Fil fil15, fil17; Resistance res14, res16, res18; // voici un circtuit de forme // o-o // | | // o-o-o // | | | // o-o-o // les {-,|} sont des resistances et {o} representent des composantes try { fil1 = new Fil((short) 0, (short) 0,null); res2 = new Resistance(0,(short) 0, (short) 1,null); res2.setSens(true); fil3 = new Fil((short) 0, (short) 2,null); res4 = new Resistance(0,(short) 1, (short) 2,null); fil5 = new Fil((short) 2, (short) 2,null); res6 = new Resistance(0,(short) 2, (short) 1,null); res6.setSens(true); fil7 = new Fil((short) 2, (short) 0,null); res8 = new Resistance(0,(short) 1, (short) 0,null); res9 = new Resistance(0,(short) 0, (short) 3,null); res9.setSens(true); fil10 = new Fil((short) 0, (short) 4,null); res11 = new Resistance(0,(short) 1, (short) 4,null); fil12 = new Fil((short) 2, (short) 4,null); res13 = new Resistance(0,(short) 2, (short) 3,null); res13.setSens(true); res14 = new Resistance(0,(short) 3, (short) 0,null); fil15 = new Fil((short) 4, (short) 0,null); res16 = new Resistance(0,(short) 4, (short) 1,null); res16.setSens(true); fil17 = new Fil((short) 4, (short) 2,null); res18 = new Resistance(0,(short) 3, (short) 2,null); map4.addComposant(fil1); map4.addComposant(res2); map4.addComposant(fil3); map4.addComposant(res4); map4.addComposant(fil5); map4.addComposant(res6); map4.addComposant(fil7); map4.addComposant(res8); map4.addComposant(res9); map4.addComposant(fil10); map4.addComposant(res11); map4.addComposant(fil12); map4.addComposant(res13); map4.addComposant(res14); map4.addComposant(fil15); map4.addComposant(res16); map4.addComposant(fil17); map4.addComposant(res18); } catch (ComposantException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } map4.genererMailles(); maillsesCircuitsFermes = map4.getMaillesCircuitsFermes(); assertTrue(maillsesCircuitsFermes.size()==12); nombreMaillesDeHuit = 6; nombreMaillesDeDouze = 4; byte nombreMaillesDeSeize = 2; for (int i = 0; i < maillsesCircuitsFermes.size(); i++) { if (maillsesCircuitsFermes.get(i).size() == 8) { nombreMaillesDeHuit--; } if (maillsesCircuitsFermes.get(i).size() == 12) { nombreMaillesDeDouze--; } if (maillsesCircuitsFermes.get(i).size() == 16) { nombreMaillesDeSeize--; } } assertTrue(nombreMaillesDeHuit == 0); assertTrue(nombreMaillesDeDouze == 0); assertTrue(nombreMaillesDeSeize == 0); } @Test public void testAddComposant() { try { map2.addComposant(res1); map2.addComposant(res2); map2.addComposant(res3); map2.addComposant(res4); map2.addComposant(res5); } catch (ComposantException e) { e.printStackTrace(); } boolean estDedant1 = false; boolean estDedant2 = false; boolean estDedant3 = false; boolean estDedant4 = false; boolean estDedant5 = false; for (ComposantMap comp : map2.getComposantsActuels()) { if (comp == res1) { estDedant1 = true; } if (comp == res2) { estDedant2 = true; } if (comp == res3) { estDedant3 = true; } if (comp == res4) { estDedant4 = true; } if (comp == res5) { estDedant5 = true; } } assertTrue(estDedant1); assertTrue(estDedant2); assertTrue(estDedant3); assertTrue(estDedant4); assertTrue(estDedant5); } @Test public void testEstDansMap() { map1 = new MapParcourable(); try { map1.addComposant(res1); } catch (ComposantException e) { // TODO Auto-generated catch block e.printStackTrace(); } assertTrue(map1.estDansMap(res1)); try { map1.addComposant(res2); } catch (ComposantException e) { // TODO Auto-generated catch block e.printStackTrace(); } assertTrue(map1.estDansMap(res2)); try { map1.addComposant(res3); } catch (ComposantException e) { // TODO Auto-generated catch block e.printStackTrace(); } assertTrue(map1.estDansMap(res3)); try { map1.addComposant(res4); } catch (ComposantException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } assertTrue(map1.estDansMap(res4)); try { map1.addComposant(res5); } catch (ComposantException e) { // TODO Auto-generated catch block e.printStackTrace(); } assertTrue(map1.estDansMap(res4)); } @Test public void testGetComposantsActuels() { ArrayList<ComposantMap> truc = new ArrayList<ComposantMap>(); truc.add(res1); truc.add(res2); truc.add(res3); truc.add(res4); truc.add(res5); map1.setComposantsActuels(truc); assertTrue(map1.getComposantsActuels() == truc); } @Test public void testSetComposantsActuels() { ArrayList<ComposantMap> truc = new ArrayList<ComposantMap>(); truc.add(res1); truc.add(res2); truc.add(res3); truc.add(res4); truc.add(res5); map1.setComposantsActuels(truc); assertTrue(map1.getComposantsActuels() == truc); } ////////////////////////////////// test GetBranches @Test public void testerGetBranches() { try { map3.addComposant(res1); map3.addComposant(res2); map3.addComposant(res3); map3.addComposant(res4); map3.addComposant(res5); } catch (ComposantException e) { // TODO Auto-generated catch block e.printStackTrace(); } map3.genererMailles(); assertTrue(map3.getMaillesCircuitsFermes().size() == 0); Fil fil1, fil3, fil5, fil7; Resistance res6, res8; try { // voici un circtuit de forme // // o-o // | | // o-o // les {-,|} sont des resistances et {o} representent des composantes fil1 = new Fil((short) 0, (short) 0,null); res2 = new Resistance(0,(short) 0, (short) 1,null); res2.setSens(true); fil3 = new Fil((short) 0, (short) 2,null); res4 = new Resistance(0,(short) 1, (short) 2,null); fil5 = new Fil((short) 2, (short) 2,null); res6 = new Resistance(0,(short) 2, (short) 1,null); res6.setSens(true); fil7 = new Fil((short) 2, (short) 0,null); res8 = new Resistance(0,(short) 1, (short) 0,null); map1.addComposant(fil1); map1.addComposant(res2); map1.addComposant(fil3); map1.addComposant(res4); map1.addComposant(fil5); map1.addComposant(res6); map1.addComposant(fil7); map1.addComposant(res8); } catch (ComposantException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } assertTrue(map1.getBranches().size()==1); Fil fil10, fil12; Resistance res9, res11, res13; try { // voici un circtuit de forme // // o-o-o // | | | // o-o-o // les {-,|} sont des resistances et {o} representent des composantes fil1 = new Fil((short) 0, (short) 0,null); res2 = new Resistance(0,(short) 0, (short) 1,null); res2.setSens(true); fil3 = new Fil((short) 0, (short) 2,null); res4 = new Resistance(0,(short) 1, (short) 2,null); fil5 = new Fil((short) 2, (short) 2,null); res6 = new Resistance(0,(short) 2, (short) 1,null); res6.setSens(true); fil7 = new Fil((short) 2, (short) 0,null); res8 = new Resistance(0,(short) 1, (short) 0,null); res9 = new Resistance(0,(short) 0, (short) 3,null); res9.setSens(true); fil10 = new Fil((short) 0, (short) 4,null); res11 = new Resistance(0,(short) 1, (short) 4,null); fil12 = new Fil((short) 2, (short) 4,null); res13 = new Resistance(0,(short) 2, (short) 3,null); res13.setSens(true); map2.addComposant(fil1); map2.addComposant(res2); map2.addComposant(fil3); map2.addComposant(res4); map2.addComposant(fil5); map2.addComposant(res6); map2.addComposant(fil7); map2.addComposant(res8); map2.addComposant(res9); map2.addComposant(fil10); map2.addComposant(res11); map2.addComposant(fil12); map2.addComposant(res13); } catch (ComposantException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // vérifie qu'il y a bel et bien 12 branches différentes (2fois le nombre de branches présentes dans chaque maille(2)) assertTrue(map2.getBranches().size()==3); map2.genererMailles(); map2.genrerNoeuds(); System.out.println(map2.toString()); float[][] matrice = map2.toMatrice(); float[][] reponse = new float[map2.getBranches().size()][1]; String s =""; for(int i = 0; i < matrice.length; i++){ for(int j = 0; j < matrice[i].length; j++){ s+=matrice[i][j]+ " "; } s += "\n"; } System.out.println(s); //System.out.println(MatriceUtilitaires.resolveEquation(matrice, reponse)); Fil fil15, fil17; Resistance res14, res16, res18; // voici un circtuit de forme // o-o // | | // o-o-o // | | | // o-o-o // les {-,|} sont des resistances et {o} representent des composantes try { fil1 = new Fil((short) 0, (short) 0,null); res2 = new Resistance(0,(short) 0, (short) 1,null); res2.setSens(true); fil3 = new Fil((short) 0, (short) 2,null); res4 = new Resistance(0,(short) 1, (short) 2,null); fil5 = new Fil((short) 2, (short) 2,null); res6 = new Resistance(0,(short) 2, (short) 1,null); res6.setSens(true); fil7 = new Fil((short) 2, (short) 0,null); res8 = new Resistance(0,(short) 1, (short) 0,null); res9 = new Resistance(0,(short) 0, (short) 3,null); res9.setSens(true); fil10 = new Fil((short) 0, (short) 4,null); res11 = new Resistance(0,(short) 1, (short) 4,null); fil12 = new Fil((short) 2, (short) 4,null); res13 = new Resistance(0,(short) 2, (short) 3,null); res13.setSens(true); res14 = new Resistance(0,(short) 3, (short) 0,null); fil15 = new Fil((short) 4, (short) 0,null); res16 = new Resistance(0,(short) 4, (short) 1,null); res16.setSens(true); fil17 = new Fil((short) 4, (short) 2,null); res18 = new Resistance(0,(short) 3, (short) 2,null); map4.addComposant(fil1); map4.addComposant(res2); map4.addComposant(fil3); map4.addComposant(res4); map4.addComposant(fil5); map4.addComposant(res6); map4.addComposant(fil7); map4.addComposant(res8); map4.addComposant(res9); map4.addComposant(fil10); map4.addComposant(res11); map4.addComposant(fil12); map4.addComposant(res13); map4.addComposant(res14); map4.addComposant(fil15); map4.addComposant(res16); map4.addComposant(fil17); map4.addComposant(res18); } catch (ComposantException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //vériife que le nombre de branches produites est de 12 (2 fois le nombre de mailles) assertTrue(map4.getBranches().size()==5); } } //--------<file_sep>/BoardPro/src/vue/ControleurDrawerVue.java package vue; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import com.jfoenix.transitions.hamburger.HamburgerBackArrowBasicTransition; import controleur.ControleurBoardPro; import graphics.Axes; import graphics.GraphiqueTemps; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.ToggleButton; import javafx.scene.control.ToggleGroup; import javafx.scene.input.ClipboardContent; import javafx.scene.input.Dragboard; import javafx.scene.input.MouseEvent; import javafx.scene.input.TransferMode; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.VBox; public class ControleurDrawerVue { @FXML public ToggleButton btnfil; @FXML public ToggleButton btnresistance; @FXML public ToggleButton btnsource; @FXML public ToggleButton btncondensateur; @FXML public ToggleButton btnbobine; @FXML public ToggleButton btnampoule; public ToggleButton btnfil1; @FXML void dragDetectedF(MouseEvent event) { ControleurBoardPro.composante = "fil"; Dragboard db = ((ToggleButton) event.getSource()).startDragAndDrop(TransferMode.ANY); ClipboardContent content = new ClipboardContent(); content.putString("THIS HAS BEEN DROPPED"); db.setContent(content); event.consume(); } @FXML void dragDetectedR(MouseEvent event) { ControleurBoardPro.composante = "resistance"; Dragboard db = ((ToggleButton) event.getSource()).startDragAndDrop(TransferMode.ANY); ClipboardContent content = new ClipboardContent(); content.putString("THIS HAS BEEN DROPPED"); db.setContent(content); event.consume(); } @FXML void dragDetectedC(MouseEvent event) { ControleurBoardPro.composante = "condensateur"; Dragboard db = ((ToggleButton) event.getSource()).startDragAndDrop(TransferMode.ANY); ClipboardContent content = new ClipboardContent(); content.putString("THIS HAS BEEN DROPPED"); db.setContent(content); event.consume(); } @FXML void dragDetectedB(MouseEvent event) { ControleurBoardPro.composante = "bobine"; Dragboard db = ((ToggleButton) event.getSource()).startDragAndDrop(TransferMode.ANY); ClipboardContent content = new ClipboardContent(); content.putString("THIS HAS BEEN DROPPED"); db.setContent(content); event.consume(); } @FXML void dragDetectedA(MouseEvent event) { ControleurBoardPro.composante = "ampoule"; Dragboard db = ((ToggleButton) event.getSource()).startDragAndDrop(TransferMode.ANY); ClipboardContent content = new ClipboardContent(); content.putString("THIS HAS BEEN DROPPED"); db.setContent(content); event.consume(); } @FXML void dragDetectedS(MouseEvent event) { ControleurBoardPro.composante = "source"; Dragboard db = ((ToggleButton) event.getSource()).startDragAndDrop(TransferMode.ANY); ClipboardContent content = new ClipboardContent(); content.putString("THIS HAS BEEN DROPPED"); db.setContent(content); event.consume(); } @FXML private void selectWire(ActionEvent event) { ControleurBoardPro.composante = ("fil"); } @FXML private void selectResistor(ActionEvent event) { ControleurBoardPro.composante = ("resistance"); } @FXML private void selectSource(ActionEvent event) { ControleurBoardPro.composante = ("source"); } @FXML private void selectCondensator(ActionEvent event) { ControleurBoardPro.composante = ("condensateur"); } @FXML private void selectBobine(ActionEvent event) { ControleurBoardPro.composante = ("bobine"); } @FXML private void selectAmpoule(ActionEvent event) { ControleurBoardPro.composante = ("ampoule"); } public ToggleGroup cGroup; public ControleurBoardPro controleur2; public VBox box; public void initialize() { /* * cGroup = new ToggleGroup(); * * btnfil.setToggleGroup(cGroup); btnresistance.setToggleGroup(cGroup); * btnsource.setToggleGroup(cGroup); btncondensateur.setToggleGroup(cGroup); * btnbobine.setToggleGroup(cGroup); btnampoule.setToggleGroup(cGroup); */ } public VBox getBox() { return box; } } <file_sep>/BoardPro/src/exceptions/MathException.java package exceptions; public class MathException extends Exception { /** * */ private static final long serialVersionUID = -1916688105817411016L; public MathException() { super("Erreur de type: MathException"); } public MathException(String message) { super(message); } } <file_sep>/BoardPro/src/vue/ControleurPopRes.java package vue; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXTextField; import application.MainApp; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.ChoiceBox; import javafx.scene.input.KeyEvent; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.StageStyle; public class ControleurPopRes { @FXML public JFXTextField PopResLongueur; @FXML public JFXTextField PopResTemperature; @FXML public JFXTextField PopResRayon; @FXML public ChoiceBox<String> choixMateriaux; @FXML public JFXTextField PopResOhmTF; @FXML public JFXTextField PopResTestTF; @FXML public JFXButton PopExit; @FXML public JFXButton PopResSave; @FXML void exitBtn(ActionEvent event) { stage.close(); } @FXML void saveBtn(ActionEvent event) { } public void show() { stage.showAndWait(); } private Stage stage; private Parent root; public ControleurPopRes() { FXMLLoader loader = new FXMLLoader(getClass().getResource("/vue/PopResOverview.fxml")); loader.setController(this); try { root = loader.load(); } catch (Exception e) { e.printStackTrace(); } Scene scene = new Scene(root); choixMateriaux.getItems().addAll("Aluminium", "Cuivre", "Fer", "Laiton", "Nichrome", "Nickel", "Or", "Platine", "Plomb", "Tungstene", "Argent"); scene.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm()); stage = new Stage(StageStyle.UTILITY); stage.initStyle(StageStyle.UNDECORATED); stage.setScene(scene); stage.sizeToScene(); stage.setAlwaysOnTop(true); stage.initOwner(MainApp.getStage()); stage.initModality(Modality.WINDOW_MODAL); } public void initialize() { PopResOhmTF.setPromptText("Default number"); PopResOhmTF.setOnKeyTyped(tfNumOnly()); } private EventHandler<KeyEvent> tfNumOnly() { EventHandler<KeyEvent> retour = new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent event) { String c = event.getCharacter(); for (int i = 0; i < 10; i++) { if ((c.equals(String.valueOf(0))) || (c.equals(String.valueOf(1))) || (c.equals(String.valueOf(2))) || (c.equals(String.valueOf(3))) || (c.equals(String.valueOf(4))) || (c.equals(String.valueOf(5))) || (c.equals(String.valueOf(6))) || (c.equals(String.valueOf(7))) || (c.equals(String.valueOf(8))) || (c.equals(String.valueOf(9)))) { } else { event.consume(); } } } }; return retour; } }<file_sep>/BoardPro/src/utilitaire/Materiaux.java package utilitaire; /** * La r�sistivit� est exposant 10^-8 et le coefficient thermique exposant 10^-3 * Les m�thodes get s'occupent de ces multiplications. Faite donc attention en vous servant * de ces chiffres, DE SI PETIT NOMBRE PEUVENT SEULEMENT AVOIR DES DOUBLES COMME TYPE. * * @author <NAME> */ public enum Materiaux { ALUMINIUM(2.65, 3.9, "Aluminium"), ARGENT(1.59, 3.8, "Argent"), CUIVRE(1.68, 3.9, "Cuivre"), FER(8.57, 5, "Fer"), LAITON(6.08, 2, "Laiton"), NICHROME(108, 0.4, "Nichrome"), NICKEL(6.93, 5.9, "Nickel"), OR(2.21, 3.4, "Or"), PLATINE(10.5, 3.92, "Platine"), PLOMB(19.2, 4.3, "Plomb"), TUNGSTENE(5.28, 4.5, "Tungstène"); private double resistivite; private double coefThermique; private String nom; /** * * @param p r�sitivit� du mat�riaux * @param a coefficient thermique du mat�riaux * @param nom nom du mat�riaux */ private Materiaux(double p, double a, String nom) { this.setResistivite(p); this.setCoefThermique(a); this.setNom(nom); } public double getResistivite() { return resistivite * Math.pow(10, -8); } private void setResistivite(double resistivite) { this.resistivite = resistivite; } public double getCoefThermique() { return coefThermique * Math.pow(10, -3); } private void setCoefThermique(double coefThermique) { this.coefThermique = coefThermique; } public String getNom() { return nom; } private void setNom(String nom) { this.nom = nom; } /** * Simplement pour les tests jUnit */ @Override public String toString() { String s = ""; s += "Le mat�riaux est " + this.getNom() + ", sa r�sistivit� est de " + this.getResistivite() + " et son coefficient thermique est de " + this.getCoefThermique() + "."; return s; } }<file_sep>/BoardPro/src/graphics/GraphiqueTemps.java package graphics; import javafx.concurrent.ScheduledService; import javafx.concurrent.Task; import temps.Temps; public class GraphiqueTemps { Graphique graph; Axes axes; Temps temp; int fps; public GraphiqueTemps(String fonction, Axes axes, int fps) { super(); this.graph = new Graphique(fonction, axes); graph.setStyle("-fx-background-color: rgb(35, 39, 50);"); this.axes = axes; fps = 1000 / fps; } public Graphique getGraphique() { return this.graph; } public void start() { temp = new Temps(); temps.setOnSucceeded(e -> { graph.tirerGraphique(-(float) (temp.getDeltaT() * axes.getMesurePixelUnite() * axes.getBonds())); temp.setTZero(); }); temps.start(); } public void stop() { temps.cancel(); } public void reset() { temps.reset(); } ScheduledService<Void> temps = new ScheduledService<Void>() { @Override protected Task<Void> createTask() { // TODO Auto-generated method stub return new Task<Void>() { @Override protected Void call() throws Exception { try { Thread.sleep(fps); } catch (InterruptedException ie) { } return null; } }; } }; } <file_sep>/BoardPro/src/tests/ResistanceTest.java package tests; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import composantesCircuit.Resistance; import exceptions.ComposantException; import utilitaire.Materiaux; public class ResistanceTest { Resistance r1; @Before public void creerResistor() { try { r1 = new Resistance(0,(short) 10, (short) 10,null); } catch (ComposantException e) { // Pas sens� se rendre ici fail(); } } @Test public void testResistor() { assertTrue(r1.getImpedence() == 20); assertTrue(r1.getCourant() == 0); assertTrue(r1.getDdp() == 0); } @Test public void testResistorCustom() { // Test 1 float longueur = 20; float rayon = 2; float t = 20; Materiaux m = Materiaux.ALUMINIUM; float resistanceCalc = (float) ((20 * m.getResistivite()) / (Math.PI * rayon * rayon)); Resistance r = new Resistance((short) 0, (short) 0, longueur, rayon, m, t,null); assertTrue(r.getImpedence() == resistanceCalc); // Test 2 t = 50; double nouveauP =(m.getResistivite() * (1 + (m.getCoefThermique() * 30))); resistanceCalc = (float) ((20 * nouveauP) / (Math.PI * rayon * rayon)); r = new Resistance((short) 0, (short) 0, longueur, rayon, m, t,null); assertTrue(r.getImpedence() == resistanceCalc); } } <file_sep>/BoardPro/src/controleur/ControleurBoardPro.java package controleur; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import composante.CE2Entrees; import composantesCircuit.Bobine; import composantesCircuit.Condensateur; import composantesCircuit.Fil; import composantesCircuit.Resistance; import composantesCircuit.SourceCourant; import exceptions.ComposantException; import javafx.animation.Animation; import javafx.animation.FadeTransition; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.embed.swing.SwingFXUtils; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.SnapshotParameters; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.image.WritableImage; import javafx.scene.input.DragEvent; import javafx.scene.input.Dragboard; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.input.ScrollEvent; import javafx.scene.input.TransferMode; import javafx.scene.text.Font; import javafx.scene.transform.Scale; import javafx.stage.FileChooser; import javafx.util.Duration; import map.ComposantMap; import map.MapParcourable; import utilitaire.Images; import utilitaire.Images.Composante; import utilitaire.Materiaux; import vue.ControleurDrawerVue; import vue.ControleurPopAmp; import vue.ControleurPopBob; import vue.ControleurPopCon; import vue.ControleurPopRes; import vue.ControleurPopSrc; import vue.ControleurVue; public class ControleurBoardPro { private ControleurVue vue; private ControleurDrawerVue vue2; double OgScale = 1; public static String composante = "fil"; private ArrayList<Images> listeImage = new ArrayList<Images>(); public int numero = 1; MapParcourable map = new MapParcourable(); Label nom = new Label(); boolean effacer = false; boolean playing = false; ArrayList<FadeTransition> listeFade = new ArrayList<FadeTransition>(); ComposantMap enModif; public ControleurBoardPro() { vue = new ControleurVue(this); } public ControleurVue getVue() { return vue; } public ControleurDrawerVue getVue2() { return vue2; } public void masterHandler() { vue.exitBtn.setOnMouseClicked(genererExitButton()); nom.setFont(new Font(50)); nom.setTranslateX(150); vue.paneGraph.getChildren().add(nom); vue.scrollP.setHvalue(0.5); vue.scrollP.setVvalue(0.5); vue.gridP.setOnScroll(genererZoomHandler()); vue.gridP.setOnMouseClicked(genererOnMouseClicked()); vue.tbReset.setOnAction(resetHandler()); vue.tbRemove.setOnAction(enleverHandler()); vue.tbPlay.setOnAction(play()); vue.rlc.setOnMouseClicked(rlcHandler()); vue.rl.setOnMouseClicked(rlHandler()); vue.rc.setOnMouseClicked(rcHandler()); vue.r.setOnMouseClicked(rHandler()); vue.c.setOnMouseClicked(cHandler()); vue.l.setOnMouseClicked(lHandler()); vue.gridP.setOnDragDropped(dragDropped()); vue.gridP.setOnDragOver(dragOver()); vue.tbEnregistrer.setOnAction(enregistrerHandler()); vue.tbOuvrir.setOnAction(ouvrirHandler()); vue.tbReset.setOnAction(resetHandler()); vue.tbScreenShot.setOnAction(screenshotHandler()); } private EventHandler<ActionEvent> play() { EventHandler<ActionEvent> retour = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { if (playing == false) { map.genererMailles(); if (map.getMaille().size() != 0) { playing = true; vue.tbPlay.setStyle("-fx-background-color:c4c297"); vue.graphiqueTemps.reset(); vue.graphiqueTemps.start(); byte compteur = 0; for (int a = 0; a < listeImage.size(); a++) { for (int b = 0; b < map.getMaille().size(); b++) { if (map.getMaille().get(b).contains(listeImage.get(a).getC()) || !listeImage.get(a).getNom().toString().substring(0, 3).equals("Fil")) { if (listeImage.get(a).getView().getId() != null && listeImage.get(a).getView().getId().equals("/img/ampouleEteinte.png")) { listeImage.get(a).setImage(new Image("/img/ampouleAlumer.png")); } if (compteur >= listeImage.size()) { break; } FadeTransition fadeTransition = new FadeTransition(Duration.seconds(0.8), listeImage.get(a).getView()); fadeTransition.setFromValue(1.0); fadeTransition.setToValue(0.3); fadeTransition.setAutoReverse(true); fadeTransition.setCycleCount(Animation.INDEFINITE); listeFade.add(fadeTransition); fadeTransition.play(); } } } } } else { for (int i = 1; i < vue.gridP.getChildren().size(); i++) { ImageView v = (ImageView) vue.gridP.getChildren().get(i); if (v.getId() != null && v.getId().equals("Ampoule")) { v.setImage(new Image("/img/ampouleEteinte.png")); } } playing = false; vue.tbPlay.setStyle(null); vue.graphiqueTemps.stop(); for (FadeTransition i : listeFade) { i.pause(); i.jumpTo(Duration.ZERO); } } } }; return retour; } private EventHandler<ActionEvent> enleverHandler() { EventHandler<ActionEvent> retour = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { vue.tbRemove.setStyle("-fx-background-color:c4c297"); if (!effacer) { effacer = true; // Activer handler enlève pour la grille vue.gridP.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { byte positionX = (byte) (Math.floor(event.getX() / 75)); byte positionY = (byte) (Math.floor(event.getY() / 75)); for (byte i = 0; i < listeImage.size(); i++) { if (listeImage.get(i).getPositionX() == positionX && listeImage.get(i).getPositionY() == positionY) { enlever(listeImage.get(i)); } } } }); } else { effacer = false; vue.gridP.setOnMouseClicked(genererOnMouseClicked()); vue.tbRemove.setStyle(null); } } }; return retour; } private EventHandler<ActionEvent> resetHandler() { EventHandler<ActionEvent> retour = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { reset(); } }; return retour; } private EventHandler<ActionEvent> screenshotHandler() { EventHandler<ActionEvent> retour = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { FileChooser fichierSelecteur = new FileChooser(); FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("*.png", "*.jpg"); fichierSelecteur.getExtensionFilters().add(extFilter); File fichier = fichierSelecteur.showSaveDialog(vue.getScene().getWindow()); if (fichier != null) { Group g = new Group(); for (int i = 0; i < listeImage.size(); i++) { g.getChildren().add(listeImage.get(i).getView()); } WritableImage image = g.snapshot(new SnapshotParameters(), null); try { ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", fichier); g = null; for (int i = 0; i < listeImage.size(); i++) { vue.gridP.add(listeImage.get(i).getView(), listeImage.get(i).getPositionX(), listeImage.get(i).getPositionY()); } } catch (IOException e) { } } } }; return retour; } private EventHandler<ActionEvent> ouvrirHandler() { EventHandler<ActionEvent> retour = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { FileChooser fichierSelecteur = new FileChooser(); FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt"); fichierSelecteur.getExtensionFilters().add(extFilter); File fichier = fichierSelecteur.showOpenDialog(vue.getScene().getWindow()); if (fichier != null) { reset(); ouvrirTexte(fichier); } } }; return retour; } private void ouvrirTexte(File fichier) { BufferedReader br; try { br = new BufferedReader(new FileReader(fichier)); String st; while ((st = br.readLine()) != null) { String nom = st; Composante c = null; if (nom.equals("FilH")) { c = Composante.FilH; } else if (nom.equals("FilV")) { c = Composante.FilV; } else if (nom.equals("FilHD")) { c = Composante.FilHD; } else if (nom.equals("FilHG")) { c = Composante.FilHG; } else if (nom.equals("FilBD")) { c = Composante.FilBD; } else if (nom.equals("FilBG")) { c = Composante.FilBG; } else if (nom.equals("FilGBD")) { c = Composante.FilGBD; } else if (nom.equals("FilGHD")) { c = Composante.FilGHD; } else if (nom.equals("FilBGH")) { c = Composante.FilBGH; } else if (nom.equals("FilBDH")) { c = Composante.FilBDH; } else if (nom.equals("FilAll")) { c = Composante.FilAll; } else if (nom.equals("Résistance")) { c = Composante.Résistance; } else if (nom.equals("Condensateur")) { c = Composante.Condensateur; } else if (nom.equals("Ampoule")) { c = Composante.Ampoule; } else if (nom.equals("Source")) { c = Composante.Source; } else if (nom.equals("Bobine")) { c = Composante.Bobine; } st = br.readLine(); if (st != null) { byte posX = (byte) Integer.parseInt(st); st = br.readLine(); if (st != null) { byte posY = (byte) Integer.parseInt(st); genererAutre(posX, posY, c); } } } } catch (Exception e) { e.printStackTrace(); } } private EventHandler<ActionEvent> enregistrerHandler() { EventHandler<ActionEvent> retour = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { String texte = ""; for (int i = 0; i < listeImage.size(); i++) { texte += listeImage.get(i).getNom() + "\n"; texte += listeImage.get(i).getPositionX() + "\n"; texte += listeImage.get(i).getPositionY() + "\n"; } FileChooser fichierSelecteur = new FileChooser(); FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt"); fichierSelecteur.getExtensionFilters().add(extFilter); File fichier = fichierSelecteur.showSaveDialog(vue.getScene().getWindow()); if (fichier != null) { enregistrerTexte(texte, fichier); } } }; return retour; } private void enregistrerTexte(String contenu, File fichier) { try { PrintWriter writer; writer = new PrintWriter(fichier); writer.println(contenu); writer.close(); } catch (IOException ex) { Logger.getLogger(ControleurBoardPro.class.getName()).log(Level.SEVERE, null, ex); } } private EventHandler<DragEvent> dragOver() { EventHandler<DragEvent> retour = new EventHandler<DragEvent>() { @Override public void handle(DragEvent event) { Dragboard db = event.getDragboard(); if (db.hasString()) { event.acceptTransferModes(TransferMode.COPY_OR_MOVE); } event.consume(); } }; return retour; } private EventHandler<DragEvent> dragDropped() { EventHandler<DragEvent> retour = new EventHandler<DragEvent>() { @Override public void handle(DragEvent event) { Dragboard db = event.getDragboard(); if (db.hasString()) { event.acceptTransferModes(TransferMode.COPY_OR_MOVE); } event.consume(); byte positionX = (byte) (Math.floor(event.getX() / 75)); byte positionY = (byte) (Math.floor(event.getY() / 75)); if (composante.equals("fil")) { genererFil(positionX, positionY); } else if (composante.equals("resistance")) { genererAutre(positionX, positionY, Composante.Résistance); } else if (composante.equals("condensateur")) { genererAutre(positionX, positionY, Composante.Condensateur); } else if (composante.equals("bobine")) { genererAutre(positionX, positionY, Composante.Bobine); } else if (composante.equals("source")) { genererAutre(positionX, positionY, Composante.Source); } else if (composante.equals("ampoule")) { genererAutre(positionX, positionY, Composante.Ampoule); } } }; return retour; } private EventHandler<ScrollEvent> genererZoomHandler() { EventHandler<ScrollEvent> retour = new EventHandler<ScrollEvent>() { @Override public void handle(ScrollEvent event) { double zoomPower = 1.03092783505; double delta_y = event.getDeltaY(); if (delta_y < 0) { zoomPower = 0.97; if (OgScale > .80) { OgScale = OgScale * zoomPower; } } if (delta_y > 0) { OgScale = OgScale * zoomPower; } Scale newScale = new Scale(); newScale.setPivotX(vue.gridP.getWidth() / 2); newScale.setPivotY(vue.gridP.getHeight() / 2); newScale.setX(vue.gridP.getScaleX() * zoomPower); newScale.setY(vue.gridP.getScaleY() * zoomPower); if (OgScale > .80) { vue.gridP.getTransforms().add(newScale); } else { OgScale = .81; } event.consume(); } }; return retour; } private EventHandler<MouseEvent> genererExitButton() { EventHandler<MouseEvent> retour = new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { // vue.boardToolb.setVisible(false); // vue.tbCompList.setExpanded(true); // vue.tbCompList.depthProperty().set(1); System.exit(1); } }; return retour; } private EventHandler<MouseEvent> genererOnMouseClicked() { EventHandler<MouseEvent> retour = new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { byte positionX = (byte) (Math.floor(event.getX() / 75)); byte positionY = (byte) (Math.floor(event.getY() / 75)); // Clique droit if (event.getButton().equals(MouseButton.SECONDARY)) { nom.setText(""); for (int i = 0; i < listeImage.size(); i++) { if (listeImage.get(i).getPositionX() == positionX && listeImage.get(i).getPositionY() == positionY) { String text = listeImage.get(i).getNom().toString(); if (text.substring(0, 3).equals("Fil")) { text = "Fil"; } if (event.isControlDown() == true) { enModif = map.getComposantsActuels().get(i); if (text.equals("Résistance")) { ControleurPopRes popup = new ControleurPopRes(); popup.PopResSave.setOnAction(modifierResistance((Resistance) enModif, popup)); popup.show(); } else if (text.equals("Condensateur")) { ControleurPopCon popup = new ControleurPopCon(); popup.PopSave.setOnAction(modifierCondensateur((Condensateur) enModif, popup)); popup.show(); } else if (text.equals("Bobine")) { ControleurPopBob popup = new ControleurPopBob(); popup.PopSave.setOnAction(modifierBobine((Bobine) enModif, popup)); popup.show(); } else if (text.equals("Source")) { ControleurPopSrc popup = new ControleurPopSrc(); popup.PopSave.setOnAction(modifierSource((SourceCourant) enModif, popup)); popup.show(); } else if (text.equals("Ampoule")) { ControleurPopAmp popup = new ControleurPopAmp(); popup.show(); } } else { text += " à la position (X, Y): (" + listeImage.get(i).getPositionX() + ", " + listeImage.get(i).getPositionY() + ")"; nom.setText(text); vue.tabView.getSelectionModel().select(1); } vue.graphiqueTemps.getGraphique().changerFonction(""); vue.graphiqueTemps.getGraphique().changerFonction("5sin(30x)"); } } } // Clique gauche else { if (composante.equals("fil")) { genererFil(positionX, positionY); } else if (composante.equals("resistance")) { genererAutre(positionX, positionY, Composante.Résistance); } else if (composante.equals("condensateur")) { genererAutre(positionX, positionY, Composante.Condensateur); } else if (composante.equals("bobine")) { genererAutre(positionX, positionY, Composante.Bobine); } else if (composante.equals("source")) { genererAutre(positionX, positionY, Composante.Source); } else if (composante.equals("ampoule")) { genererAutre(positionX, positionY, Composante.Ampoule); } } } }; return retour; } private void genererAutre(byte x, byte y, Composante nom) { Images i = new Images(nom, x, y); HashSet<Byte> aChanger = i.composanteProche(listeImage); changerImage(aChanger); i.choisirImage(i); Composante n = i.choisirImage(i); i.setNom(n); i.creerImage(i.getNom()); i.creerView(); ajoutComposante(i, null); } private void genererFil(byte x, byte y) { Images image = new Images(Composante.FilH, x, y); /* * Cette ligne fait deux chose, trouve les composantes proches de l'image (1) et * puisque ces images proches doivent peut-être changer, garde la liste des * images a changer */ HashSet<Byte> aChanger = image.composanteProche(listeImage); changerImage(aChanger); Composante nom = image.choisirImage(image); image.setNom(nom); image.creerImage(image.getNom()); image.creerView(); ajoutComposante(image, null); } private void changerImage(HashSet<Byte> lesIndexs) { ArrayList<Images> liste = new ArrayList<Images>(); for (Byte i : lesIndexs) { liste.add(listeImage.get(i)); } for (int j = 0; j < liste.size(); j++) { Composante avant = liste.get(j).getNom(); int rotAvant = liste.get(j).getRotation(); Composante apres = liste.get(j).choisirImage(liste.get(j)); int rotApres = liste.get(j).getRotation(); if (!avant.equals(apres) || rotAvant != rotApres) { ImageView aEnlever = liste.get(j).getView(); liste.get(j).setNom(apres); liste.get(j).creerImage(apres); liste.get(j).creerView(); ajoutComposante(liste.get(j), aEnlever); } } } private void ajoutComposante(Images image, ImageView aEnlever) { // Remove si à la meme position for (byte i = 0; i < listeImage.size(); i++) { if (listeImage.get(i) == image || (listeImage.get(i).getPositionX() == image.getPositionX() && listeImage.get(i).getPositionY() == image.getPositionY())) { map.removeComposante(i); vue.gridP.getChildren().remove(listeImage.get(i).getView()); if (aEnlever == null) { aEnlever = listeImage.get(i).getView(); } vue.gridP.getChildren().remove(aEnlever); listeImage.remove(i); } } listeImage.add(image); ImageView v = image.getView(); v.setRotate(image.getRotation()); vue.gridP.add(v, image.getPositionX(), image.getPositionY()); // -----------------------Ajout dans composante Map-------------------- try { ComposantMap compo = null; CE2Entrees composante = null; if (image.getNom().equals(Composante.Ampoule)) { composante = new Resistance((short) image.getPositionX(), (short) image.getPositionY(), image); composante.getImage().getView().setId("Ampoule"); if (composante.getImage().getRotation() == 90) { composante.setSens(true); } } else if (image.getNom().equals(Composante.Bobine)) { composante = new Bobine((short) image.getPositionX(), (short) image.getPositionY(), image); if (composante.getImage().getRotation() == 90) { composante.setSens(true); } } else if (image.getNom().equals(Composante.Condensateur)) { composante = new Condensateur((short) image.getPositionX(), (short) image.getPositionY(), image); if (composante.getImage().getRotation() == 90) { composante.setSens(true); } } else if (image.getNom().equals(Composante.Résistance)) { composante = new Resistance((short) image.getPositionX(), (short) image.getPositionY(), image); if (composante.getImage().getRotation() == 90) { composante.setSens(true); } } else if (image.getNom().equals(Composante.Source)) { composante = new SourceCourant((short) image.getPositionX(), (short) image.getPositionY(), image); if (composante.getImage().getRotation() == 90) { composante.setSens(true); } } else { compo = new Fil((short) image.getPositionX(), (short) image.getPositionY(), image); } if (compo != null) { map.addComposant(compo); image.setC(compo); } if (composante != null) { map.addComposant(composante); } } catch (ComposantException e) { e.printStackTrace(); } } private void reset() { listeImage.clear(); map.getComposantsActuels().clear(); nom.setText(""); Node n = vue.gridP.getChildren().get(0); vue.gridP.getChildren().clear(); vue.gridP.add(n, 0, 0); } private void enlever(Images image) { HashSet<Byte> aModif = image.modifierAutourRetrait(listeImage); changerImage(aModif); vue.gridP.getChildren().remove(image.getView()); map.getComposantsActuels().remove(listeImage.indexOf(image)); listeImage.remove(image); } private EventHandler<MouseEvent> rlcHandler() { EventHandler<MouseEvent> retour = new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { reset(); File f = new File("./res/circuitPrefait/RLC.txt"); ouvrirTexte(f); vue.tabView.getSelectionModel().select(0); // Résistance 16 listeImage.get(16).setEquationDDP(""); // Bobine 17 listeImage.get(17).setEquationDDP(""); // Condensateur 19 listeImage.get(19).setEquationDDP(""); } }; return retour; } private EventHandler<MouseEvent> rlHandler() { EventHandler<MouseEvent> retour = new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { reset(); File f = new File("./res/circuitPrefait/RL.txt"); ouvrirTexte(f); vue.tabView.getSelectionModel().select(0); // Résistance listeImage.get(18).setEquationDDP(""); // Bobine listeImage.get(19).setEquationDDP(""); } }; return retour; } private EventHandler<MouseEvent> rcHandler() { EventHandler<MouseEvent> retour = new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { reset(); File f = new File("./res/circuitPrefait/RC.txt"); ouvrirTexte(f); vue.tabView.getSelectionModel().select(0); // Résistance listeImage.get(18).setEquationDDP(""); // Condensateur listeImage.get(19).setEquationDDP(""); } }; return retour; } private EventHandler<MouseEvent> rHandler() { EventHandler<MouseEvent> retour = new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { reset(); File f = new File("./res/circuitPrefait/R.txt"); ouvrirTexte(f); vue.tabView.getSelectionModel().select(0); listeImage.get(19).setEquationDDP(""); } }; return retour; } private EventHandler<MouseEvent> cHandler() { EventHandler<MouseEvent> retour = new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { reset(); File f = new File("./res/circuitPrefait/C.txt"); ouvrirTexte(f); vue.tabView.getSelectionModel().select(0); listeImage.get(19).setEquationDDP(""); } }; return retour; } private EventHandler<MouseEvent> lHandler() { EventHandler<MouseEvent> retour = new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { reset(); File f = new File("./res/circuitPrefait/L.txt"); ouvrirTexte(f); vue.tabView.getSelectionModel().select(0); listeImage.get(19).setEquationDDP(""); } }; return retour; } private EventHandler<ActionEvent> modifierCondensateur(Condensateur s, ControleurPopCon p) { EventHandler<ActionEvent> retour = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { try { s.setCapacite(Float.parseFloat(p.PopConCap.getText())); } catch (Exception e) { s.setCapacite(100); } } }; return retour; } private EventHandler<ActionEvent> modifierBobine(Bobine s, ControleurPopBob p) { EventHandler<ActionEvent> retour = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { try { s.setInductence(Float.parseFloat(p.PopBobInd.getText())); } catch (Exception e) { s.setInductence(20); } } }; return retour; } private EventHandler<ActionEvent> modifierSource(SourceCourant s, ControleurPopSrc p) { EventHandler<ActionEvent> retour = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { try { s.setCourant(Float.parseFloat(p.PopSrcAmp.getText())); s.setDdp(Float.parseFloat(p.PopSrcVol.getText())); s.setFrequence(Float.parseFloat(p.frequence.getText())); } catch (Exception e) { s.setCourant(0); s.setDdp(0); s.setFrequence(0); } } }; return retour; } private EventHandler<ActionEvent> modifierResistance(Resistance r, ControleurPopRes p) { EventHandler<ActionEvent> retour = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { if (p.PopResLongueur.getText().equals("") || p.PopResTemperature.getText().equals("") || (p.PopResRayon.getText().equals(""))) { try { float res = Float.parseFloat(p.PopResOhmTF.getText()); r.setImpedence(res); } catch (Exception e) { r.setImpedence(20); } } else { try { r.setTemperature(273 + Float.parseFloat(p.PopResTemperature.getText())); r.setRayon(Float.parseFloat(p.PopResRayon.getText())); r.setLongueur(Float.parseFloat(p.PopResLongueur.getText())); String materiaux = p.choixMateriaux.getValue(); if (materiaux.equals("Argent")) { r.setMateriau(Materiaux.ARGENT); } else if (materiaux.equals("Aluminium")) { r.setMateriau(Materiaux.ALUMINIUM); } else if (materiaux.equals("Cuivre")) { r.setMateriau(Materiaux.CUIVRE); } else if (materiaux.equals("Fer")) { r.setMateriau(Materiaux.FER); } else if (materiaux.equals("Laiton")) { r.setMateriau(Materiaux.LAITON); } else if (materiaux.equals("Nichrome")) { r.setMateriau(Materiaux.NICHROME); } else if (materiaux.equals("Nickel")) { r.setMateriau(Materiaux.NICKEL); } else if (materiaux.equals("Or")) { r.setMateriau(Materiaux.OR); } else if (materiaux.equals("Platine")) { r.setMateriau(Materiaux.PLATINE); } else if (materiaux.equals("Plomb")) { r.setMateriau(Materiaux.PLOMB); } else if (materiaux.equals("Tungstène")) { r.setMateriau(Materiaux.TUNGSTENE); } } catch (Exception e) { r.setImpedence(20); } } } }; return retour; } } <file_sep>/BoardPro/src/utilitaire/SolveurEquations.java package utilitaire; import java.util.*; import java.io.IOException; import java.text.*; /** * * @author lx_user */ public class SolveurEquations { static HashMap<String, Integer> opPrecedence = new HashMap<String, Integer>(); public static void initPrecedence() { opPrecedence.put("^", 4); opPrecedence.put("*", 3); opPrecedence.put("/", 3); opPrecedence.put("+", 2); opPrecedence.put("-", 2); opPrecedence.put(")", 1); opPrecedence.put("(", 1); } private static String[] convvertirSymboles(String expression) { ArrayList<String> symboles = new ArrayList<String>(); String[] output; int outputSize = 0; boolean prevWasOperator = true; // use this to check for unary operators (-) for (int i = 0; i < expression.length(); i++) { switch (expression.charAt(i)) { case '^': symboles.add("^"); symboles.add(""); prevWasOperator = true; break; case '*': symboles.add("*"); symboles.add(""); prevWasOperator = true; break; case '/': symboles.add("/"); symboles.add(""); prevWasOperator = true; break; case '+': symboles.add("+"); symboles.add(""); prevWasOperator = true; break; case '-': if (prevWasOperator && expression.charAt(i + 1) != '(') { symboles.add("-"); } else if (prevWasOperator && expression.charAt(i + 1) == '(') { symboles.add("-1"); symboles.add("*"); } else { symboles.add("-"); symboles.add(""); prevWasOperator = true; } break; case '(': symboles.add("("); symboles.add(""); prevWasOperator = true; break; case ')': symboles.add(")"); symboles.add(""); prevWasOperator = false; break; case ' ': // remove whitespace break; case '[': String scientificNotation = ""; for (int j = i + 1; j < expression.length(); j++) { if (expression.charAt(j) == ']') { i = j; break; } scientificNotation += expression.charAt(j); } symboles.add(scientificNotation); prevWasOperator = false; break; default: // alphanumeric characters if (symboles.size() < 1) symboles.add(""); String item = symboles.get(symboles.size() - 1) + expression.charAt(i); symboles.remove(symboles.size() - 1); symboles.add(item); prevWasOperator = false; } } for (int i = 0; i < symboles.size(); i++) { if (symboles.get(i).length() > 0) outputSize++; } output = new String[outputSize]; int j = 0; for (int i = 0; i < symboles.size(); i++) { if (symboles.get(i).length() > 0) { output[j] = symboles.get(i); j++; } } return output; } private static String infixToPostfix(String expression) { if (expression == "") // empty string return ""; Stack<String> operationStack = new Stack<String>(); String[] lettres = convvertirSymboles(expression); String ret = ""; for (String let : lettres) { if (let.equals("(")) { operationStack.push(let); } else if (let.equals(")")) { while (!operationStack.peek().equals("(")) ret += operationStack.pop() + " "; operationStack.pop(); } else if (opPrecedence.containsKey(let)) { while (!operationStack.isEmpty() && opPrecedence.get(operationStack.peek()) >= opPrecedence.get(let)) ret += operationStack.pop() + " "; operationStack.push(let); } else { ret += let + " "; } } while (!operationStack.isEmpty()) ret += operationStack.pop() + " "; return ret; } private static double evaluaterPostfix(String expression) { if (expression == "") return 0; Stack<Double> operandStack = new Stack<Double>(); String[] tokens = expression.split(" "); for (String tok : tokens) { double num1, num2; switch (tok) { case "+": num2 = (double) operandStack.pop(); num1 = (double) operandStack.pop(); operandStack.push(num1 + num2); break; case "-": num2 = (double) operandStack.pop(); num1 = (double) operandStack.pop(); operandStack.push(num1 - num2); break; case "*": num2 = (double) operandStack.pop(); num1 = (double) operandStack.pop(); operandStack.push(num1 * num2); break; case "/": num2 = (double) operandStack.pop(); num1 = (double) operandStack.pop(); operandStack.push(num1 / num2); break; case "^": num2 = (double) operandStack.pop(); num1 = (double) operandStack.pop(); operandStack.push(Math.pow(num1, num2)); break; default: operandStack.push(Double.parseDouble(tok)); } } return (double) operandStack.pop(); } private static boolean possedeFonction(String expression) { return expression.contains("log") || expression.contains("sin") || expression.contains("cos") || expression.contains("tan") || expression.contains("abs") ; } private static boolean isOperator(char c) { return c == '^' || c == '*' || c == '/' || c == '-' || c == '+'; } private static boolean isTerm2(char c) { return c == '(' || c == '[' || (c - 'a' < 26 && c - 'a' >= 0); } private static boolean isTerm1(char c) { return c == ')' || c == ']' || (c - '0' <= 9 && c - '0' >= 0); } private static String getMultiplicationImplicite(String expression) { String ret = expression; boolean scanned = false; do { scanned = false; for (int i = 1; i < ret.length(); i++) { if (isTerm2(ret.charAt(i)) && isTerm1(ret.charAt(i - 1)) || isTerm1(ret.charAt(i - 1)) && isTerm2(ret.charAt(i))) { ret = ret.substring(0, i) + "*" + ret.substring(i); scanned = true; break; } } } while (scanned); return ret; } public static double evaluer(String expression) { return evaluaterUtile(getMultiplicationImplicite(expression)); } private static double evaluaterUtile(String expression) { while (possedeFonction(expression)) { String expressionDouble = expression; int start = 0; Stack<Integer> bracketStack = new Stack<Integer>(); if (expression.indexOf("log") != -1) start = expression.indexOf("log"); else if (expression.indexOf("sin") != -1) start = expression.indexOf("sin"); else if (expression.indexOf("cos") != -1) start = expression.indexOf("cos"); else if (expression.indexOf("tan") != -1) start = expression.indexOf("tan"); else if (expression.indexOf("abs") != -1) start = expression.indexOf("abs"); for (int i = start + 3; i < expression.length(); i++) { if (expression.charAt(i) == '(') bracketStack.push(i); else if (expression.charAt(i) == ')') bracketStack.pop(); if (bracketStack.isEmpty()) { String expressionSimplifie = ""; String function = expression.substring(start, start + 3); expressionSimplifie += expression.substring(0, start); switch (function) { case "sin": expressionSimplifie += Math.sin(evaluer(expression.substring(start + 4, i))); break; case "log": expressionSimplifie += Math.log10(evaluer(expression.substring(start + 4, i))); break; case "cos": expressionSimplifie += Math.cos(evaluer(expression.substring(start + 4, i))); break; case "tan": expressionSimplifie += Math.tan(evaluer(expression.substring(start + 4, i))); break; case "abs": expressionSimplifie += Math.abs(evaluer(expression.substring(start + 4, i))); break; } expressionSimplifie += expression.substring(i + 1); return evaluer(expressionSimplifie); } } if(expressionDouble.equals(expression)) { throw new NumberFormatException(); } } return evaluaterPostfix(infixToPostfix(expression)); } }<file_sep>/BoardPro/src/tests/MatriceUtilitairesTest.java package tests; import static org.junit.Assert.*; import org.junit.Test; import utilitaire.MatriceUtilitaires; public class MatriceUtilitairesTest { int[][] mat4; int[][] mat1 = { { 1, 3, 7 }, { 2, 4, 8 }, { 5, 0, 6 } }; int[][] mat2 = { { 1, 2, 1, 0 }, { 0, 3, 1, 1 }, { -1, 0, 3, 1 }, { 3, 1, 2, 0 } }; int[][] mat3 = { { 1, 2 }, { 2, -2 } }; int[][] mat7 = { { 7 } }; @Test public void testToStringMat() { int[][] mat6 = {}; assertTrue(MatriceUtilitaires.toStringMat(mat4).isEmpty()); assertTrue(MatriceUtilitaires.toStringMat(mat6).isEmpty()); assertTrue(MatriceUtilitaires.toStringMat(null).isEmpty()); } @Test public void testGetMatTranspose() { int[][] mat13 = { { 1, 3 }, { 2, -2 } }; int[][] mat14 = { { 1, 2 }, { 3, -2 } }; int[][] mat5 = { { 1, 2, 5 }, { 3, 4, 0 }, { 7, 8, 6 } }; assertTrue((MatriceUtilitaires.toStringMat(MatriceUtilitaires.getMatTranspose(mat13))) .equalsIgnoreCase(MatriceUtilitaires.toStringMat(mat14))); assertTrue((MatriceUtilitaires.toStringMat(MatriceUtilitaires.getMatTranspose(mat1))) .equalsIgnoreCase(MatriceUtilitaires.toStringMat(mat5))); assertTrue(MatriceUtilitaires.toStringMat(MatriceUtilitaires.getMatTranspose(null)) == ""); } @Test public void testGetMatMultScalaire() { int[][] mat13 = { { 2, 4 }, { 4, -4 } }; int[][] mat5 = { { 2, 6, 14 }, { 4, 8, 16 }, { 10, 0, 12 } }; assertTrue(MatriceUtilitaires.toStringMat(MatriceUtilitaires.getMatMultScalaire(mat1, 2)) .equalsIgnoreCase(MatriceUtilitaires.toStringMat(mat5))); assertTrue(MatriceUtilitaires.toStringMat(MatriceUtilitaires.getMatMultScalaire(mat3, 2)) .equalsIgnoreCase(MatriceUtilitaires.toStringMat(mat13))); assertTrue(MatriceUtilitaires.toStringMat(MatriceUtilitaires.getMatMultScalaire(null, 2)) == ""); } @Test public void testGetMatModuloX() { int[][] mat13 = { { 1, 0 }, { 0, 0 } }; int[][] mat5 = { { 1, 1, 1 }, { 0, 0, 0 }, { 1, 0, 0 } }; assertTrue(MatriceUtilitaires.toStringMat(MatriceUtilitaires.getMatModuloX(mat1, 2)) .equalsIgnoreCase(MatriceUtilitaires.toStringMat(mat5))); assertTrue(MatriceUtilitaires.toStringMat(MatriceUtilitaires.getMatModuloX(mat3, 2)) .equalsIgnoreCase(MatriceUtilitaires.toStringMat(mat13))); assertTrue(MatriceUtilitaires.toStringMat(MatriceUtilitaires.getMatModuloX(null, 2)) == ""); } @Test public void testGetDeterminant() { assertTrue(MatriceUtilitaires.getDeterminant(mat2) == 16); assertTrue(MatriceUtilitaires.getDeterminant(mat3) == -6); assertTrue(MatriceUtilitaires.getDeterminant(mat7) == 7); } @Test public void testGetMatCofacteurs() { int[][] mat5 = { { 1, 2, 5 }, { 3, 4, 0 }, { 7, 8, 6 } }; int[][] mat5Cofacteur = { { 24, -18, -4 }, { 28, -29, 6 }, { -20, 15, -2 } }; assertTrue((MatriceUtilitaires.toStringMat(MatriceUtilitaires.getMatCofacteurs(mat5))) .equalsIgnoreCase(MatriceUtilitaires.toStringMat(mat5Cofacteur))); assertTrue(MatriceUtilitaires.toStringMat(MatriceUtilitaires.getMatCofacteurs(null)) == ""); } @Test public void testGetMatAdjointe() { int[][] mat5 = { { 24, -18, -4 }, { 28, -29, 6 }, { -20, 15, -2 } }; assertTrue(MatriceUtilitaires.toStringMat(MatriceUtilitaires.getMatAdjointe(mat1)) .equalsIgnoreCase(MatriceUtilitaires.toStringMat(mat5))); assertTrue(MatriceUtilitaires.toStringMat(MatriceUtilitaires.getMatAdjointe(null)) == ""); } } <file_sep>/BoardPro/src/composantesCircuit/Fil.java package composantesCircuit; import composante.CE2Entrees; import composante.ComposanteElectrique; import exceptions.ComposantException; import utilitaire.Images; /** * Classe des fils * @author <NAME> * */ public class Fil extends ComposanteElectrique { /** * TRUE si l'on n�glige la r�sistance des fils */ private boolean neglige = true; /** * Quand nous changerons la variable imp�dence d'un fil, nous devrons changer * r�sistance aussi. R�sistance est seulement utile pour garder la valeur de la * r�sistance car si l'on n�glige le fil on met l'imp�dence � 0, si on ne * n�glige plus le fil on a encore la valeur de la r�sistance. */ private float resistance; /** * Constructeur par d�faut des fils, utile lorsque l'on place un fil dans la * zone de dessin on cr�era ce fil automatiquement avec cette classe. * @throws ComposantException */ private static final float RESISTANCE_DEFAUT = 2f; public Fil(short x, short y, Images image) throws ComposantException { super(RESISTANCE_DEFAUT,x,y,image); this.setResistance(this.getImpedence()); } public boolean isNeglige() { return neglige; } /** * Le set s'occupe aussi de changer l'impedence du fil � 0 si l'on veut n�gliger * les r�sistances Puisque la classe stock la valeur de l'imp�dence avec la * variable Resistance, la classe est capable de reprendre l'imp�dence du fil * sans en entr�e une nouvelle lorsqu'on remet n�gliger � false. * * @param neglige */ public void setNeglige(boolean neglige) { if (neglige == true) { this.setImpedence(0); } if (neglige == false) { this.setImpedence(this.resistance); } this.neglige = neglige; } public float getResistance() { return resistance; } public void setResistance(float resistance) { this.resistance = resistance; } @Override public String toString() { return ""; } }
d8d825c7f8ebc9b8651acf9e12dd034ccfb4c9e9
[ "Java" ]
16
Java
EtsSimon9/BoardPro
39185ea268e86f3138f97865fc08cbe12ef44926
58c1ea46d67b0c6be238ec9fc0c7579dbbb6305b
refs/heads/master
<repo_name>chiranthsiddappa/ProjectEuler<file_sep>/Problem34.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package projecteuler; /** * * @author Chiranth */ /** * 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. * * Find the sum of all numbers which are equal to the sum of the factorial of * their digits. * * Note: as 1! = 1 and 2! = 2 are not sums they are not included. * * @author Chiranth */ public class Problem34 { public static long isEqualSum(int upperBound) { long factorialSum = 0, sum = 0, digitFactSum = 0; for (long i = 3; i <= upperBound; i++) { if (digitsFactorialSum(i) == i) { factorialSum += i; } } return factorialSum; } public static long digitsFactorialSum(long num) { long sum = 0; int nextDigit = 0, limit = length(num); for (int i = 0; i < limit; i++) { nextDigit = (int) num % 10; sum += factorial(nextDigit); num -= nextDigit; num /= 10; } return sum; } public static int length(double x) { return (int) java.lang.Math.floor(java.lang.Math.log10(x) + 1); } public static long factorial(int n) { long factorial = 1; for (int i = 1; i <= n; i++) { factorial *= i; } return factorial; } public static void main(String args[]) { // System.out.println(isEqualSum(100000)); } } <file_sep>/Problem43.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package projecteuler; import java.lang.Math; /** * * @author chiranth */ /** * The number, 1406357289, is a 0 to 9 pandigital number because it is made up * of each of the digits 0 to 9 in some order, but it also has a rather * interesting sub-string divisibility property. * * Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note * the following: d2d3d4=406 is divisible by 2 d3d4d5=063 is divisible by 3 * d4d5d6=635 is divisible by 5 d5d6d7=357 is divisible by 7 d6d7d8=572 is * divisible by 11 d7d8d9=728 is divisible by 13 d8d9d10=289 is divisible by 17 * * Find the sum of all 0 to 9 pandigital numbers with this property. */ public class Problem43 { public static int length(long x) { return (int) Math.floor(Math.log10(x) + 1); } public static String replaceChar(String str, int index, char replace) { if (str == null) { return str; } else if (index < 0 || index >= str.length()) { return str; } char[] chars = str.toCharArray(); chars[index] = replace; return String.valueOf(chars); } public static long lexicographicPermutationSum(String string) { String tempS = "", reverse = "", temp = string; char tempC = '\n'; boolean foundAk = false, foundAl = false; int nPermutations = factorial(string.length()), permutation = 0; int ak = 0, al = 0; long sum = 0; //First permutation is the starting string temp = string; // make a copy for the first combination do { if (hasDivisibilityProperties(temp)) { sum += Long.parseLong(temp); } //reset variables foundAk = false; foundAl = false; //Step 1 a[k] < a[k + 1] for (int k = 0; k < temp.length() - 1; k++) { if (temp.charAt(k) < temp.charAt(k + 1)) { ak = k; foundAk = true; } } //Step 2 find a[k] < a[l], if another perm exists if (foundAk) { for (int l = ak + 1; l < string.length(); l++) { if (temp.charAt(l) > temp.charAt(ak)) { al = l; } } //Step 3 swap a[k] with a[l] tempC = temp.charAt(ak); tempS = replaceChar(temp, ak, temp.charAt(al)); tempS = replaceChar(tempS, al, tempC); //Step 4 reverse the sequence from a[k+1], switch the numbers backwards reverse = tempS.substring(ak + 1); //Still needs work... for (int charNext = ak + 1, charRev = reverse.length() - 1; charNext < tempS.length() && charRev >= 0; charNext++, charRev--) { tempS = replaceChar(tempS, charNext, reverse.charAt(charRev)); } temp = tempS; } } while (foundAk && permutation < nPermutations); return sum; } public static int factorial(int n) { int factorial = 1; for (int i = 1; i <= n; i++) { factorial *= i; } return factorial; } public static boolean hasDivisibilityProperties(String x) { boolean d234by2, d345by3, d456by5, d567by7, d678by11, d789by13, d8910by17; d234by2 = Long.parseLong(x.substring(1, 4)) % 2 == 0; d345by3 = Long.parseLong(x.substring(2, 5)) % 3 == 0; d456by5 = Long.parseLong(x.substring(3, 6)) % 5 == 0; d567by7 = Long.parseLong(x.substring(4, 7)) % 7 == 0; d678by11 = Long.parseLong(x.substring(5, 8)) % 11 == 0; d789by13 = Long.parseLong(x.substring(6, 9)) % 13 == 0; d8910by17 = Long.parseLong(x.substring(7, 10)) % 17 == 0; if (d234by2 && d345by3 && d456by5 && d567by7 && d678by11 && d789by13 && d8910by17) { return true; } else { return false; } } public static void main(String[] args) { long sum = lexicographicPermutationSum("1023456789"); System.out.println(sum); } } <file_sep>/Problem44.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package projecteuler; import java.lang.Math; import java.util.Arrays; /** * * @author chiranth */ /** * Pentagonal numbers are generated by the formula, Pn=n(3n-1)/2. The first ten * pentagonal numbers are: * * 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ... * * It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, * 70 22 = 48, is not pentagonal. * * Find the pair of pentagonal numbers, Pj and Pk, for which their sum and * difference is pentagonal and D = |Pk Pj| is minimised; what is the value of * D? * * Solving Pn=n(3n-1)/2 produces sqrt(1 + 24*n) % 6 == 5 % 6 */ public class Problem44 { public static int Pn(int n) { return n*(3*n - 1) / 2; } public static boolean isPentagonal(int x) { return Math.sqrt(24*x + 1) % 6 == 5; } public static int[] push(int[] current, int newInt) { int[] newStack = Arrays.copyOf(current, current.length + 1); newStack[current.length] = newInt; return newStack; } public static int pentagonalDifference() { int D = 0; int Pk = 0; int Pj = 0; int tempP = 0; int[] pentagonals = new int[1]; pentagonals[0] = 0; boolean pentagonalDFound = false; //Calculate D with Math.abs(Pk - Pj), two for loops for(Pk = 1; !pentagonalDFound; Pk = Pj) { tempP = Pn(Pk); pentagonals = push(pentagonals, tempP); // test the values just in case... for(Pj = 1; Pj <= Pk && !pentagonalDFound; Pj++) { D = Math.abs(pentagonals[Pk] - pentagonals[Pj]); pentagonalDFound = isPentagonal(pentagonals[Pk] + pentagonals[Pj]) && isPentagonal(D); } } return D; } public static void main(String[] args) { System.out.println(pentagonalDifference()); } } <file_sep>/Problem61.rb aTri = [] aSquare = [] aPent = [] aHex = [] aHept = [] aOct = [] cyclicals = [] perms = [] def triangle(n, aTri) if (aTri.length() - 1) < n for i in (aTri.length())..(n) aTri.push i*(i + 1) / 2 end return aTri[n] else return aTri[n] end end def square(n, aSquare) if (aSquare.length() - 1) < n for i in (aSquare.length())..(n) aSquare.push i**2 end return aSquare[n] else return aSquare[n] end end def pentagonal(n, aPent) if (aPent.length() - 1) < n for i in (aPent.length())..(n) aPent.push i*(3*i - 1)/2 end return aPent[n] else return aPent[n] end end def hexagonal(n, aHex) if (aHex.length() -1) < n for i in (aHex.length())..(n) aHex.push i*(2*i - 1) end return aHex[n] else return aHex[n] end end def heptagonal(n, aHept) if (aHept.length() -1) < n for i in (aHept.length())..(n) aHept.push i*(5*i - 3)/2 end return aHept[n] else return aHept[n] end end def octagonal(n, aOct) if (aOct.length() - 1) < n for i in (aOct.length())..(n) aOct.push i*(3*i - 2) end return aOct[n] else return aOct[n] end end def next_triangle(aTri) triangle(aTri.length, aTri) end def next_square(aSquare) square(aSquare.length, aSquare) end def next_pentagonal(aPent) pentagonal(aPent.length, aPent) end def next_hexagonal(aHex) hexagonal(aHex.length, aHex) end def next_heptagonal(aHept) heptagonal(aHept.length, aHept) end def next_octagonal(aOct) octagonal(aOct.length, aOct) end def isCyclic?(set) valid = true curr_digits = [] curr_string = "" for i in 0..set.length() - 2 curr_string = set[i].to_s curr_digits[0] = curr_string[curr_string.length - 1] curr_digits[1] = curr_string[curr_string.length - 2] return false if ((curr_digits[0] != set[i+1].to_s[0] or curr_digits[1] != set[i+1].to_s[1]) and (curr_digits[0] != set[i+1].to_s[1] or curr_digits[1] != set[i+1].to_s[0])) end curr_string = set[set.length() -1].to_s curr_digits[0] = curr_string[curr_string.length - 1] curr_digits[1] = curr_string[curr_string.length - 2] return ((curr_digits[0] == set[0].to_s[0] and curr_digits[1] == set[0].to_s[1]) or (curr_digits[0] == set[0].to_s[1] and curr_digits[1] == set[0].to_s[0])) end def lex_perm(a) permutations = [] begin k = -1 l = -1 index = 0 permutations.push [] a.each {|int| permutations[permutations.length() -1].push int} for i in 0..(a.length - 2) do k = i if a[i] < a[i + 1] end for i in 0..(a.length - 1) do l = i if a[k] < a[i] end if k >= 0 a[k],a[l] = a[l],a[k] a[k+1, a.length-1] = a[k+1, a.length-1].reverse end end while k >= 0 return permutations end puts isCyclic?([8128, 2882, 8281]) for i in 1..8 perms.push lex_perm((0..(i -1)).to_a) end puts "Perm array created." <file_sep>/Problem17.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package projecteuler; /** * * @author Chiranth */ /* * If the numbers 1 to 5 are written out in words: one, two, three, four, five, * then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. * * If all the numbers from 1 to 1000 (one thousand) inclusive were written out * in words, how many letters would be used? * * * NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and * forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 * letters. The use of "and" when writing out numbers is in compliance with * British usage. * */ public class Problem17 { public static int digits(int n) { int i; int mod; for (i = 0; n > 0; i++) { mod = n % 10; n -= mod; n /= 10; } return i; } public static String stringOfNumbersInWords(int n) { int i; String stringOfNumbers = ""; for (i = 1; i <= n; i++) { stringOfNumbers += stringOfNumber(i); } return stringOfNumbers; } public static String stringOfNumber(int n) { if (n < 10) { if (n == 1) { return "one"; } else if (n == 2) { return "two"; } else if (n == 3) { return "three"; } else if (n == 4) { return "four"; } else if (n == 5) { return "five"; } else if (n == 6) { return "six"; } else if (n == 7) { return "seven"; } else if (n == 8) { return "eight"; } else if (n == 9) { return "nine"; } } else if (n >= 10 && n < 100) { if (n >= 10 && n < 20) { if (n == 10) { return "ten"; } else if (n == 11) { return "eleven"; } else if (n == 12) { return "twelve"; } else if (n == 13) { return "thirteen"; } else if (n == 14) { return stringOfNumber(4) + "teen"; } else if (n == 15) { return "fifteen"; } else if (n == 16) { return stringOfNumber(6) + "teen"; } else if (n == 17) { return stringOfNumber(7) + "teen"; } else if (n == 18) { return stringOfNumber(8) + "een"; } else if (n == 19) { return stringOfNumber(9) + "teen"; } } else if (n >= 20 && n < 30) { return "twenty" + stringOfNumber(n % 10); } else if (n >= 30 && n < 40) { return "thirty" + stringOfNumber(n % 10); } else if (n >= 40 && n < 50) { return "forty" + stringOfNumber(n % 10); } else if (n >= 50 && n < 60) { return "fifty" + stringOfNumber(n % 10); } else if (n >= 60 && n < 70) { return "sixty" + stringOfNumber(n % 10); } else if (n >= 70 && n < 80) { return "seventy" + stringOfNumber(n % 10); } else if (n >= 80 && n < 90) { return "eighty" + stringOfNumber(n % 10); } else if (n >= 90 && n < 100) { return "ninety" + stringOfNumber(n % 10); } } else if (n >= 100 && n < 1000) { if (n % 100 == 0) { return stringOfNumber(n / 100) + "hundred"; } else { return stringOfNumber(n / 100) + "hundredand" + stringOfNumber(n % 100); } } else if (n >= 1000 && n < 10000) { return stringOfNumber(n / 1000) + "thousand" + stringOfNumber(n % 1000); } else { return ""; } return ""; } public static void main(String[] args) { System.out.println(stringOfNumbersInWords(1000).length()); } } <file_sep>/README.markdown #Project Euler Solutions This repository contains solutions to over 30 Project Euler problems, solved in Java, Python, Ruby, and C, by <NAME>. This code has been provided as a reference only. <file_sep>/Problem61.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package projecteuler; import java.util.Arrays; import java.lang.Math; /** * * @author Chiranth */ /*Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal numbers * are all figurate (polygonal) numbers and are generated by the following * formulae: * Triangle P3,n=n(n+1)/2 1, 3, 6, 10, 15, ... Square P4,n=n2 1, 4, 9, 16, 25, ... Pentagonal P5,n=n(3n1)/2 1, 5, 12, 22, 35, ... Hexagonal P6,n=n(2n1) 1, 6, 15, 28, 45, ... Heptagonal P7,n=n(5n3)/2 1, 7, 18, 34, 55, ... Octagonal P8,n=n(3n2) 1, 8, 21, 40, 65, ... The ordered set of three 4-digit numbers: 8128, 2882, 8281, has three * interesting properties. The set is cyclic, in that the last two digits of each number is the first two * digits of the next number (including the last number with the first). Each polygonal type: triangle (P3,127=8128), square (P4,91=8281), and * pentagonal (P5,44=2882), is represented by a different number in the set. This is the only set of 4-digit numbers with this property. Find the sum of the only ordered set of six cyclic 4-digit numbers for which * each polygonal type: triangle, square, pentagonal, hexagonal, heptagonal, * and octagonal, is represented by a different number in the set. */ public class Problem61 { public static int length(int n) { return (int) Math.floor(Math.log10(n) + 1); } public static int factorial(int n) { int factorial = 1; for (int i = 1; i <= n; i++) { factorial *= i; } return factorial; } public static int triangleForm(int n) { return n * (n + 1) / 2; } public static int squareForm(int n) { return n * n; } public static int pentForm(int n) { return n * (3 * n - 1) / 2; } public static int hexForm(int n) { return n * (2 * n - 1); } public static int heptForm(int n) { return n * (5 * n - 3) / 2; } public static int octForm(int n) { return n * (3 * n - 2); } public static int[] bubbleSortIncreasing(int[] n) { int temp; boolean moves = true; while (moves) { moves = false; for (int i = 0; i < n.length - 1; i++) { if (n[i] > n[i + 1]) { moves = true; temp = n[i + 1]; n[i + 1] = n[i]; n[i] = temp; } } } return n; } public static boolean testTwoDigits(int[] x, int[] y) { if ((x[0] == y[0] && x[1] == y[1]) || (x[0] == y[1] && x[1] == y[0]) || (x[1] == y[0] && x[0] == y[1])) { return true; } else { return false; } } //Assumes the length of all numbers is 4 public static boolean checkOrderedSet(int[][] set) { int[] prevDigits = new int[2]; int[] currDigits = new int[2]; boolean valid; for (int i = 0; i < set.length; i++) { //length of the array[][] valid = true; for (int n = 0; n < set[i].length && valid; n++) { //length of the array[] prevDigits[0] = (set[i][n] % 100) % 10; prevDigits[1] = ((set[i][n] % 100) - (set[i][n] % 10)) / 10; if (n < set[i].length - 1) { currDigits[0] = set[i][n + 1] / 1000; currDigits[1] = (set[i][n + 1] / 100) % 10; } else { // wrap around currDigits[0] = set[i][0] / 1000; currDigits[1] = (set[i][0] / 100) % 10; } if (testTwoDigits(prevDigits, currDigits)) { valid = true; } else { valid = false; } } if (valid) { return true; } } return false; } //Find the largest index k such that a[k] < a[k + 1]. If no such index exists, the permutation is the last permutation. //Find the largest index l such that a[k] < a[l]. Since k + 1 is such an index, l is well defined and satisfies k < l. //Swap a[k] with a[l]. //Reverse the sequence from a[k + 1] up to and including the final element a[n]. public static int[][] permutations(int[] a) { int permutations[][] = new int[1][a.length]; int[] tempCopy, aCopy; boolean foundAk; int k = 0, l = 0, n, p = 0, al, ak, r; a = bubbleSortIncreasing(a); //reset the array for algorithm permutations[p++] = Arrays.copyOf(a, a.length); aCopy = permutations[0]; for (; p < factorial(aCopy.length); p++) { foundAk = false; //reset variable //Step 1 find k such that a[k] < a[k+1] for (ak = 0; ak < a.length - 1; ak++) { if (aCopy[ak] < aCopy[ak + 1]) { foundAk = true; k = ak; } } if (foundAk) { //Step 2 find the largest l such that a[k] < a[l] for (al = k + 1; al < aCopy.length; al++) { if (aCopy[k] < aCopy[al]) { l = al; } } //Step 3 swap a[k] with a[l] ak = aCopy[k]; aCopy[k] = aCopy[l]; aCopy[l] = ak; //Step 4 reverse sequence from a[k+1] inclusively to final element tempCopy = Arrays.copyOfRange(aCopy, k + 1, aCopy.length); //revisit loop to use the numbers from tempCopy properly for (r = k + 1, n = tempCopy.length - 1; r < aCopy.length && n >= 0; r++, n--) { aCopy[r] = tempCopy[n]; } permutations = arrayAddLine(permutations, aCopy); } } return permutations; } public static int[] arrayAddInt(int[] arr, int next) { int[] temp; temp = Arrays.copyOf(arr, arr.length + 1); temp[arr.length] = next; return temp; } public static int[][] arrayAddLine(int[][] orig, int[] newLine) { int[][] temp = new int[orig.length + 1][orig.length]; for (int i = 0; i < orig.length; i++) { temp[i] = Arrays.copyOf(orig[i], orig[i].length); } temp[temp.length - 1] = Arrays.copyOf(newLine, newLine.length); return temp; } public static void printArray(int[] a) { for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } System.out.println(); } public static int sumArray(int[] a) { int sum = 0; for (int i = 0; i < a.length; i++) { sum += a[i]; } return sum; } public static void main(String[] args) { int hept, hex, oct, pent, square, triangle, sum = 0, tempCalc, tempLength; boolean foundCyclic = false; int[] aHept = new int[0], aHex = new int[0], aOct = new int[0], aPent = new int[0], aSquare = new int[0], aTriangle = new int[0], nthArr = new int[6]; boolean foundHept = false, foundHex = false, foundOct = false, foundPent = false, foundSquare = false, foundTriangle = false; for (int n = 1; !foundHept || !foundHex || !foundOct || !foundPent || !foundSquare || !foundTriangle; n++) { if (!foundHept) { tempCalc = heptForm(n); tempLength = length(tempCalc); if (tempLength == 4) { aHept = arrayAddInt(aHept, tempCalc); } else if (tempLength == 5) { foundHept = true; } } if (!foundHex) { tempCalc = hexForm(n); tempLength = length(tempCalc); if (tempLength == 4) { aHex = arrayAddInt(aHex, tempCalc); } else if (tempLength == 5) { foundHex = true; } } if (!foundOct) { tempCalc = octForm(n); tempLength = length(tempCalc); if (tempLength == 4) { aOct = arrayAddInt(aOct, tempCalc); } else if (tempLength == 5) { foundOct = true; } } if (!foundPent) { tempCalc = pentForm(n); tempLength = length(tempCalc); if (tempLength == 4) { aPent = arrayAddInt(aPent, tempCalc); } else if (tempLength == 5) { foundPent = true; } } if (!foundSquare) { tempCalc = squareForm(n); tempLength = length(tempCalc); if (tempLength == 4) { aSquare = arrayAddInt(aSquare, tempCalc); } else if (tempLength == 5) { foundSquare = true; } } if (!foundTriangle) { tempCalc = triangleForm(n); tempLength = length(tempCalc); if (tempLength == 4) { aTriangle = arrayAddInt(aTriangle, tempCalc); } else if (tempLength == 5) { foundTriangle = true; } } } for (hept = 0; hept < aHept.length; hept++) { nthArr[0] = aHept[hept]; for (hex = 0; hex < aHex.length; hex++) { nthArr[1] = aHex[hex]; for (oct = 0; oct < aOct.length; oct++) { nthArr[2] = aOct[oct]; for (pent = 0; pent < aPent.length; pent++) { nthArr[3] = aPent[pent]; if (checkOrderedSet(permutations(Arrays.copyOfRange(nthArr, 0, 4)))) { for (square = 0; square < aSquare.length; square++) { for (triangle = 0; triangle < aTriangle.length; triangle++) { nthArr[4] = aSquare[square]; nthArr[5] = aTriangle[triangle]; printArray(nthArr); if (checkOrderedSet(permutations(nthArr))) { sum = sumArray(nthArr); } } } } } } } } System.out.println(sum); } } <file_sep>/Problem100.py def gcd(a , b): t = 0 while(b != 0): t = b b = a % t a = t return a a = 4 b = 12 print(gcd(a , b)) print(gcd(1071, 462)) print(gcd(462, 1071)) <file_sep>/Problem70.rb include Math def lex_perm(a) permutations = [] begin k = -1 l = -1 index = 0 permutations.push [] a.each {|int| permutations[permutations.length() -1].push int} for i in 0..(a.length - 2) do k = i if a[i] < a[i + 1] end for i in 0..(a.length - 1) do l = i if a[k] < a[i] end if k >= 0 a[k],a[l] = a[l],a[k] a[k+1, a.length-1] = a[k+1, a.length-1].reverse end end while k >= 0 return permutations end def compare_with_permutations(num, phi_n, perms) return false if num.to_s.length() != phi_n.to_s.length() isSame = false arr_str = "" perms[phi_n.to_s.length].each do |perm| arr_str = "" for ii in 0..(perm.length() - 1) arr_str << phi_n.to_s[perm[ii]] end puts arr_str return true if num == arr_str.to_i end return false end perms = [[]] for nLength in 0..7 tempPermArr = [] for ii in 0..nLength tempPermArr.push ii end perms.push lex_perm(tempPermArr) end puts (compare_with_permutations(102, 210, perms)) <file_sep>/Problem57.py import math def length(n): return math.floor(math.log10(n) + 1) numerator = 3 denominator = 2 iterations = 0 longerNumerators = 0 while (iterations < 1000): numerator = numerator + 2*denominator denominator = numerator - denominator if length(numerator) > length(denominator) : longerNumerators = longerNumerators + 1 iterations = iterations + 1 print(longerNumerators) <file_sep>/Problem104.rb panSum = 1+2+3+4+5+6+7+8+9 def strAddition(x , y) return 0.to_s end def first_pandigital(x) if x.length < 9 return false else arr = [] for iter in 0..8 arr.push(x[iter] - 48) end for iter in 1..9 if !arr.include?(iter) return false end end return true end end def last_pandigital(x) if x.length < 9 return false else arr = [] for iter in (x.length - 9)..(x.length - 1) arr.push(x[iter] - 48) end for iter in 1..9 if !arr.include?(iter) return false end end return true end end def fibonacci(k) iter = 0 fk = 0 fk_0 = 0 fk_1 = 0 if k == 0 return 0 elsif k == 1 return 1 elsif k > 1 iter = 2 fk = 1 fk_0 = 0 fk_1 = 1 while(iter <= k) fk = fk_0 + fk_1 fk_0 = fk_1 fk_1 = fk iter += 1 end return fk else return 0 end end def find_k_pandigital k = 1 fk = 1 fk_0 = 0 fk_1 = 1 while(last_pandigital(fk.to_s) == false || first_pandigital(fk.to_s) == false) fk = fk_0 + fk_1 fk_0 = fk_1 fk_1 = fk k += 1 end return k end puts first_pandigital(fibonacci(2749).to_s) puts last_pandigital(fibonacci(541).to_s) puts find_k_pandigital() <file_sep>/Problem160.py def removeZeros(n): nCopy = n while nCopy % 10 == 0: nCopy = nCopy / 10 return nCopy def reduceSize(n): return n % 100000 x = 1 lastFive = 1 while x < 1000000000000 : lastFive = lastFive*(reduceSize(removeZeros(x))) lastFive = reduceSize(removeZeros(lastFive)) x = x + 1 print(lastFive) <file_sep>/Problem25.py import math def nthFibonacciNum(nthTerm): phi = (1 + math.sqrt(5)) / 2 n = math.pow(phi, nthTerm)/math.sqrt(5) + 1/2 return math.floor(n) def thousandDigitFibonacci(): fibonacci = 0 f1 = 1 f2 = 1 term = 2 digits = 0 while (digits < 1000): term = 1 + term fibonacci = f1 + f2 f1 = f2 f2 = fibonacci digits = math.floor(math.log10(fibonacci) + 1) return term print(math.floor(math.log10(nthFibonacciNum(12)) + 1)) print(thousandDigitFibonacci()) <file_sep>/Problem21.py def sumOfFactors(x): sum = 0 for i in range(1, x/2 + 1): if(x % i == 0): sum = sum + i return sum def d(a, secondNumber, b): sum = 0 if(secondNumber == 0): sum = sumOfFactors(a) return d(a, True, sum) elif(secondNumber == 1): return a == sumOfFactors(b) #sumOfAmicableNumbers not working def sumOfAmicableNumbers(x): sum = 0 for i in range(0, x): if(d(x, False, 0) == True): sum = sum + i return sum print(sumOfAmicableNumbers(10000)) <file_sep>/Problem71.rb require 'rational' fractions = [] n = 1 d = 1*10**6 dMax = 1*10**4 maxRat = 3/7.to_f minDiff = 1 immediateRational = Rational(3,7) currDiff = 1 def euclid_gcd(m , n) while n != 0 r = m % n m = n n = r end return m end while(d > 1) do n = (d/4).ceil currFrac = Rational(n,d) while (currFrac.to_f) <= maxRat do if euclid_gcd(d,n) == 1 currDiff = maxRat - currFrac.to_f if(currDiff < minDiff && currDiff > 0) immediateRational = currFrac minDiff = currDiff end end n += 1 currFrac = Rational(n,d) end puts immediateRational d -= 1 end puts "Done looping..." puts immediateRational <file_sep>/Problem30.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package projecteuler; import java.lang.Math; /** * * @author Chiranth */ public class Problem30 { public static int length(double x) { return (int) java.lang.Math.floor(java.lang.Math.log10(x) + 1); } public static double factorial(int n) { double factorial = 1; if (n <= 1) { //When you get to one, return return 1; } else { factorial = (double) n * factorial(n - 1); //multiply andstack down to 2 return factorial; } } public static boolean checkNumber(int num) { int length = length(num), factNumSum = 0; int currentDigit; for(int i = 0, j = length -1; i < length; i++, j--) { currentDigit = (int) num / (int) Math.pow(10, j); factNumSum += factorial(currentDigit); } return false; // Just return false, cause I don't know what it's doing } public static void main(String args[]) { } } <file_sep>/Problem1.rb divisibles = [] for i in 1..(1000-1) divisibles.push i if (i % 3 == 0 or i % 5 == 0) end sum = 0 divisibles.each {|nextNum| sum += nextNum} puts sum <file_sep>/Problem60.rb require 'mathn' class OptimusPrime def initialize() @primes = [2 , 3] end def primeSieve(n) isPrimeArr = Array.new(n + 1 , true) for i in 2..Math.sqrt(n) if(isPrimeArr[i] == true) index = i*i while(index <= n) isPrimeArr[index] = false index += i end end end return isPrimeArr end def addUpTo(n) puts "Checking #{n}" sieveList = primeSieve(n) primesList = Array.new sieveList.each_with_index {|isPrime , index| primesList << index if isPrime == true } primesList.delete 0 primesList.delete 1 primesList.each do |prime| if(!(@primes.include? prime)) @primes.push prime end end puts "Done" end def isPrime?(n) if(@primes[@primes.length - 1] >= n) return @primes.include? n else addUpTo n return @primes.include? n end end def printPrimes @primes.each {|prime| puts "#{prime}"} end def nthPrime(n) if(n < @primes.length) return @primes[n] else return false end end def numOfPrimes return @primes.length end end def isPrimePairSet?(primesObj , set) set.each do |n1| set.each do |n2| if(n1 != n2) if(!(primesObj.isPrime? (n1.to_s + n2.to_s).to_i)) return false end end end end return true end def setSum(set) sum = 0 set.each {|n| sum += n} return sum end def factorial(n) fact = 1 for i in 1..n fact *= i end return fact end def addPrimeSet(primesObj , length , pPairSet) foundSetLength = false primes = 0 iterations = 0 nextSet = [] while(not foundSetLength) primes += 1 for i in 0..length-1 #check for the lengths if(i == 0) for n in 0..primes if(!(pPairSet.include? [(primesObj.nthPrime n)])) pPairSet.push [(primesObj.nthPrime n)] end end foundSetLength = length == 1 else #end checking for single primes for n in 0..primes pPairSet.each do |set| #check prime set logic here nextSet = (set + [(primesObj.nthPrime n)]).sort if(!(set.include? primesObj.nthPrime n) and (isPrimePairSet?(primesObj , nextSet))) if(!(pPairSet.include? nextSet)) pPairSet.push nextSet end foundSetLength = pPairSet[pPairSet.length - 1].length == length end end end #primes end #else end #end checking individual lengths end end primesObj = OptimusPrime.new primesObj.isPrime?(51) primesObj.isPrime?(200000) primesObj.printPrimes pPairSet = [] addPrimeSet(primesObj , 3 , pPairSet) puts "Set Listing: #{pPairSet}" pPairSet.each do |set| if(set.length == 3) puts "#{set} Sum: #{setSum set}" end end<file_sep>/Problem60.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package projecteuler; /** * * @author Chiranth */ /*The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes * and concatenating them in any order the result will always be prime. For * example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these * four primes, 792, represents the lowest sum for a set of four primes with * this property. Find the lowest sum for a set of five primes for which any two primes * concatenate to produce another prime. */ import java.lang.Math; import java.util.Arrays; public class Problem60 { public static int factorial(int n) { int factorial = 1; for (int i = 1; i <= n; i++) { factorial *= i; } return factorial; } public static class OptimusPrime { private long[] primes = new long[1]; public OptimusPrime() { primes[0] = 2; } public boolean isPrime(long checkPrime) { while (primes[primes.length - 1] < checkPrime) { addNextPrime(); } if (Arrays.binarySearch(primes, checkPrime) >= 0) { return true; } else { return false; } } public boolean findIsPrime(long n) { if (n > 2) { for (int i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) { return false; } } return true; } else { return false; } } public long findNextPrime(long currPrime) { long nextPrime; for (nextPrime = ++currPrime; !findIsPrime(nextPrime); nextPrime++); return nextPrime; } public void addNextPrime() { long[] temp = Arrays.copyOf(primes, primes.length + 1); temp[temp.length - 1] = findNextPrime(temp[temp.length - 2]); primes = temp; } public void printPrimes() { for (int i = 0; i < primes.length; i++) { System.out.println(primes[i]); } } public long[] getPrimes() { return primes; } } public static long[][] lexicographic(long[] primes) { long[][] permutations = new long[factorial(primes.length)][primes.length]; Arrays.sort(primes); return permutations; } public static boolean testForAnyTwo(OptimusPrime prime, long[] test) { String concatenated; for (int i = 0; i < test.length; i++) { for (int j = 0; j < test.length; j++) { if (i != j) { concatenated = Long.toString(test[i]) + Long.toString(test[j]); if (!prime.isPrime(Long.parseLong(concatenated))) { return false; } } } } return true; } public static double sumArray(long[] arr) { double sum = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; } return sum; } public static String[] addString(String[] arr, String newS) { String[] temp = Arrays.copyOf(arr, arr.length + 1); temp[temp.length - 1] = newS; return temp; } public static void main(String[] args) { OptimusPrime primeObj = new OptimusPrime(); long[] primes = primeObj.getPrimes(), testArr = new long[5]; String[] tested = new String[0]; String currentTest; boolean foundFive = false; int currentMax = 1; int minSum = 0xFFFFF; testArr = new long[4]; testArr[0] = 3; testArr[1] = 7; testArr[2] = 109; testArr[3] = 673; System.out.println(testForAnyTwo(primeObj, testArr)); while (true) { for (int i1 = 0; i1 < currentMax; i1++) { for (int i2 = 0; i2 < currentMax && i2 != i1; i2++) { for (int i3 = 0; i3 < currentMax && i3 != i2; i3++) { for (int i4 = 0; i4 < currentMax && i4 != i3; i4++) { currentTest = "" + i1 + " " + i2 + " " + i3 + " " + i4; if (Arrays.binarySearch(tested, currentTest) < 0) { testArr[0] = primes[i1]; testArr[1] = primes[i2]; testArr[2] = primes[i3]; testArr[3] = primes[i4]; if(testForAnyTwo(primeObj , testArr)) { System.out.println(sumArray(testArr)); if(sumArray(testArr) < minSum) { minSum = (int) sumArray(testArr); System.out.println("Min: " + minSum); } } tested = addString(tested , currentTest); } } } } } primes = primeObj.getPrimes(); if(primes.length > currentMax) { ++currentMax; } else { primeObj.addNextPrime(); primes = primeObj.getPrimes(); ++currentMax; } } } } <file_sep>/Problem62.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package projecteuler; import java.lang.Math; import java.util.Arrays; /** * * @author Chiranth */ /** * Cubic permutations Problem 62 The cube, 41063625 (345^3), can be permuted to * produce two other cubes: 56623104 (384^3) and 66430125 (405^3). In fact, * 41063625 is the smallest cube which has exactly three permutations of its * digits which are also cube. * * Find the smallest cube for which exactly five permutations of its digits are * cube. * * * */ public class Problem62 { public static class Cube { private long firstCube; private long perfect; private String cubeDigits; private short instances = 0; public Cube(long perfect, long cube) { firstCube = cube; this.perfect = perfect; this.cubeDigits = sortDigits(cube); ++instances; } public String getCubeDigits() { return cubeDigits; } public boolean addInstance(long perfect) { if (this.cubeDigits.equals(sortDigits(perfect))) { ++instances; return true; } else { return false; } } public short getInstances() { return instances; } public String sortDigits(long l) { char[] arrDigits = Long.toString(l).toCharArray(); Arrays.sort(arrDigits); return new String(arrDigits); } public long getPerfect() { return perfect; } public long getFirstCube() { return firstCube; } } public static class Cubes { private short highestInstance = 0; private long highestPerfect = 0; private long highestInstanceCube = 0; Cube[] cubes = new Cube[0]; public Cubes() { } public void addCube(long perfect, long cube) { boolean added = false; for (int i = 0; i < cubes.length && !added; i++) { if (cubes[i].addInstance(cube)) { added = true; if(cubes[i].getInstances() > highestInstance) { highestInstance = cubes[i].getInstances(); highestPerfect = cubes[i].getPerfect(); highestInstanceCube = cubes[i].getFirstCube(); } } } if (!added) { Cube newCube = new Cube(perfect, cube); cubes = push(cubes, newCube); } } public Cube[] push(Cube[] current, Cube newCube) { Cube[] newStack = Arrays.copyOf(current, current.length + 1); newStack[current.length] = newCube; return newStack; } public void print() { for(int i = 0; i < cubes.length; i++) { System.out.println(cubes[i].getPerfect() + " " + cubes[i].getCubeDigits() + " " + cubes[i].getInstances()); } } public short getHighestInstance() { return highestInstance; } public long getHighestPerfect() { return highestPerfect; } public long getHighestInstanceCube() { return highestInstanceCube; } } public static void main(String[] args) { int cube = 330; long testNum = 344, testRemainder; //System.out.println(testNum / Math.pow(10, length(testNum) - 1)); Cubes c = new Cubes(); for( ; c.getHighestInstance() < 5; cube++) { c.addCube(cube, (long) Math.pow(cube, 3)); } System.out.println(c.getHighestInstance()); System.out.println(c.getHighestPerfect()); System.out.println(c.getHighestInstanceCube()); } } <file_sep>/Problem73.rb require 'mathn' require 'timeout' def euclid_gcd(m , n) while n != 0 r = m % n m = n n = r end return m end def create_sieve(d) isPrimeArr = Array.new(d+1, true) for i in 2..Math.sqrt(d) if(isPrimeArr[i] == true) index = i*i while index <= d isPrimeArr[index] = false index += i end end end return isPrimeArr end Timeout::timeout(7200) { sieve_arr = create_sieve(12000) set_length = 0 for d in 1..12000 for n in (d/3.0).round..(d/2.0).round if(Rational(n,d).to_f < 1/2.0 and Rational(n,d) > 1/3.0) if(euclid_gcd(n,d) == 1) set_length += 1 end end end end puts set_length } <file_sep>/Problem74.rb fact_arr = [1] def factorial(x, arr) if arr[x] == nil if arr[x - 1] == nil factorial(x - 1, arr) end arr[x] = arr[x -1] * x return arr[x] else return arr[x] end end def factorial_chain(x, numbers, fact_arr) if !numbers.include? x numbers.push x str = x.to_s curr_sum = 0 for i in 0..str.length() - 1 curr_sum += factorial(str[i].to_i , fact_arr) end return 1 + factorial_chain(curr_sum, numbers, fact_arr) else return 0 end end sixty = 0 for i in 0..1*10**6 - 1 puts i sixty += 1 if factorial_chain(i, [], fact_arr) == 60 end puts sixty <file_sep>/Problem22.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package projecteuler; import java.io.*; import java.util.*; /** * * @author csiddapp */ public class Problem22 { public static String[] getNames() throws FileNotFoundException { String[] names = new String[5163]; String temp = ""; int i = 0; // counter variable Scanner nameScanner = new Scanner(new File("names.txt")); for (i = 0; nameScanner.hasNext(); i++) { temp += nameScanner.next(); } for (i = 0; i < names.length; i++) { //Just clear to non-nulls names[i] = ""; } for (i = 0; temp.length() > 4; i++) { //insertion for-loop if (temp.indexOf("ALONSO") > 2) { names[i] = temp.substring(temp.indexOf("\"") + 1, temp.indexOf("\",")); temp = temp.substring(names[i].length() + 3, temp.lastIndexOf("\"") + 1); } else { names[i] = "ALONSO"; temp = ""; } } System.out.println("Names: " + i); return names; } public static int sumOfNameValues(String[] names) { int sum = 0, i = 0, j = 0, nameValue = 0; for (i = 0; i < names.length; i++) { //number in list for (j = 0; j < names[i].length(); j++) { if(names[i].charAt(j) != ' ') nameValue += (int)names[i].charAt(j) - 64; //number of each letter } sum += (nameValue * (i + 1)); nameValue = 0; } return sum; } public static void main(String[] args) throws FileNotFoundException { char blank = ' '; String[] names = getNames(); Arrays.sort(names); System.out.println(sumOfNameValues(names)); } } <file_sep>/Problem63.py import math def length(n): return math.floor(math.log10(n) + 1) def isNthPow(n): nthPow = length(n) base = 1 while(length(base**nthPow) <= nthPow): if(base**nthPow == n): return 1 #indicates that a case was found base = base + 1 return 0 #indicates that no match was found def nthPows(nthPow): base = 1 results = 0 while(length(base**nthPow) <= nthPow): if(length(base**nthPow) == nthPow): results = results + 1 base = base + 1 return results nthPow = 1 results = 0 while(nthPow < 1000): results = results + nthPows(nthPow) nthPow = nthPow + 1 print(results) <file_sep>/Problem72.rb require 'mathn' require 'timeout' =begin Find lowest gcd == 1 cases, and multiply upwards =end def euclid_gcd(m , n) while n != 0 r = m % n m = n n = r end return m end def add_multiples(set, n, d) #multiply up to 1*10**6 end Timeout::timeout(300) { set_length = 0 non_gcd_sets = [[],[]] for d in 1..1*10**6 for n in 1..(d - 1) end puts d end puts set_length } <file_sep>/Problem15.c #include <stdio.h> //standard input/output #include <stdlib.h> //standard library //Represents the function n!, uses the stack double factorial(int n) { double temp = 1; //set to a safe multiplicative value if (n <= 1) { //When you get to one, return return (double) 1; } else { temp = n * factorial(n-1); //Multiply and stack down to 2 return temp; } } //find n(n-1)(n-2)...(n-r+1) double nCrNumerator(int n, int r) { double temp = 1; // int i; //counter variable for (i = n; i >= (n - r + 1); i--) { temp *= (double) i; } return temp; } //finds ((n(n-1)(n-2)(n-3)...(n-r+1))/r!) for n choose r double nCr(int n, int r) { return (double) nCrNumerator(n, r) /(double) factorial(r); } int main() { printf("%f \n", nCr(40, 20)); return EXIT_SUCCESS; //stdlib var }<file_sep>/Problem5.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package projecteuler; /** * * @author Chiranth */ /** * 2520 is the smallest number that can be divided by each of the numbers from 1 * to 10 without any remainder. * * What is the smallest positive number that is evenly divisible by all of the * numbers from 1 to 20? * */ public class Problem5 { public static boolean isDivisible(int n) { for(int i = 1; i <= 20; i++) { if(n % i != 0) { return false; } } return true; } public static void main(String[] args) { int divisibleNumber; for(divisibleNumber = 1; !isDivisible(divisibleNumber); divisibleNumber++); System.out.println(divisibleNumber); } } <file_sep>/Problem1.py #Problem 3 sum = 0 for i in range(1,1000): if(i %3 == 0 or i % 5 == 0): sum = sum + i print(sum) <file_sep>/Problem19.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package projecteuler; /** * * @author Chiranth */ /* * You are given the following information, but you may prefer to do some * research for yourself. 1 Jan 1900 was a Monday. Thirty days has September, * April, June and November. All the rest have thirty-one, Saving February * alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. * A leap year occurs on any year evenly divisible by 4, but not on a century * unless it is divisible by 400. * * How many Sundays fell on the first of the month during the twentieth century * (1 Jan 1901 to 31 Dec 2000)? * */ /* * Use the file named Problem19.txt for all the months of the years * */ import java.io.*; import java.util.*; public class Problem19 { public static int numberOfFirstSundays() throws FileNotFoundException { Scanner calReader = new Scanner(new File("Problem19.txt")); int firstSundays = 0, i = 0, nextSunday = 0; boolean findNextSunday = false; String nextLine = ""; for (i = 0; calReader.hasNextLine(); ++i) { nextLine = calReader.nextLine(); //Find a blank line and add two by default if (nextLine.trim().isEmpty()) { nextSunday = i + 3; findNextSunday = true; } if (findNextSunday && i == nextSunday) { findNextSunday = false; if (isFirstCharNum(nextLine)) { ++firstSundays; } } } return firstSundays; } public static boolean isFirstCharNum(String nextLine) { String firstThreeChars = ""; if (nextLine.length() > 3) { firstThreeChars = nextLine.substring(0, 3); if (!firstThreeChars.isEmpty() && !firstThreeChars.trim().isEmpty() && !firstThreeChars.equalsIgnoreCase(" Su")) { return true; } else { return false; } } else { return false; } } public static void main(String[] args) throws FileNotFoundException { System.out.println(numberOfFirstSundays()); } } <file_sep>/Problem60.py import math def isPrime(n): i = 2 #counter variable while i <= math.sqrt(n): if(n % i == 0): return False i = i + 1 return True print(isPrime(25)) print(isPrime(13)) <file_sep>/Problem92.rb #number chains require 'benchmark' chain_truth = [false] squares = [0,1] def is89?(n, chain_truth, squares) curr_nums = [n] curr_num = curr_nums[0] if chain_truth[n] != nil return chain_truth[n] else chain_truth[n] = is89?(num_sum(n, squares), chain_truth, squares) end end def num_sum(n, squares) str_rep = n.to_s sum = 0 for i in 0..str_rep.length() -1 squares[str_rep[i].to_i] = (str_rep[i].to_i)**2 if squares[str_rep[i].to_i] == nil sum += squares[str_rep[i].to_i] end return sum end chain_truth[1] = false chain_truth[89] = true sum_89s = 0 puts Benchmark.realtime { for i in 0..10000000 sum_89s += 1 if is89?(i, chain_truth, squares) end } puts sum_89s <file_sep>/Problem81.py file = open("matrix.txt", 'r') matrix = [] global sum_matrix sum_matrix = [] global min_sum min_sum = 0 for line in file.readlines(): nums = [] char_strings = line.split(',') for i in char_strings: nums.append(int(i)) matrix.append(nums) def min_sum_path(matrix, x, y, curr_sum): global min_sum global sum_matrix if(x < len(matrix) - 1 and y < len(matrix) - 1): if(sum_matrix[x][y] == 0 or sum_matrix[x][y] > curr_sum + matrix[x][y]): sum_matrix[x][y] = curr_sum + matrix[x][y] min_sum_path(matrix, x + 1, y, curr_sum + matrix[x][y]) min_sum_path(matrix, x, y + 1, curr_sum + matrix[x][y]) elif (x == len(matrix) - 1 and y < len(matrix)): if(sum_matrix[x][y] == 0 or sum_matrix[x][y] > curr_sum + matrix[x][y]): sum_matrix[x][y] = curr_sum + matrix[x][y] min_sum_path(matrix, x, y + 1, curr_sum + matrix[x][y]) elif (y == len(matrix) - 1 and x < len(matrix)): if(sum_matrix[x][y] == 0 or sum_matrix[x][y] > curr_sum + matrix[x][y]): sum_matrix[x][y] = curr_sum + matrix[x][y] min_sum_path(matrix, x + 1, y, curr_sum + matrix[x][y]) else: if(min_sum == 0 or curr_sum < min_sum): print(curr_sum) min_sum = curr_sum for ii in xrange(0, len(matrix)): sum_matrix.append([]) for jj in xrange(0, len(matrix)): sum_matrix[ii].append(0) min_sum_path(matrix, 0 , 0, 0) print(min_sum) <file_sep>/Problem76.rb # for the number 5, there are six possibilities def sums_of(n , highest, sums) if(n > 1) #do something else return sums[n - 1] end end sums = [1,1,2] puts sums_of(5, sums) <file_sep>/Problem66.py import math def isDiophantine(x , y , d): return x**2 - d*y**2 == 1 def isSquare(n): return math.floor(math.sqrt(n))**2 == n def diophantineXVal(y , d): return math.floor(math.sqrt(d*y**2 + 1)) def length(n): return math.floor(math.log10(n) + 1) maxX = 0 maxD = 0 d = 215 x = 1 y = 1 minSolFound = False while(d <= 1000): x = 1 y = 1 while(not minSolFound and not isSquare(d) and length(x) <= 38): x = diophantineXVal(y , d) if(isDiophantine(x , y , d)): minSolFound = True if(x > maxX): maxX = x maxD = d y = y + 1 minSolFound = False d = d + 1 print("D: " + str(d)) print(maxD) <file_sep>/Problem155.py def capacitances(n) : if(n > 1): return (2*capacitances(n-1) + 1) else: return 1 print(capacitances(18)) <file_sep>/Problem41.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package projecteuler; import java.lang.Math; /** * * @author chiranth */ /** * We shall say that an n-digit number is pandigital if it makes use of all the * digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is * also prime. * * What is the largest n-digit pandigital prime that exists? * * Note: All pandigital numbers greater than 754321 can be divided by 3, using * the sum of digits rule, for 8 the digits = 36 */ public class Problem41 { public static int length(long x) { return (int) Math.floor(Math.log10(x) + 1); } public static boolean isPrime(long x) { if (x <= 1) { return false; } else if (x % (int) Math.sqrt(x) == 0) { return false; } else { for (long i = 2; i < Math.sqrt(x); i++) { if (x % i == 0) { return false; } } } return true; } public static boolean isPandigital(long x) { int sum = 0, i = 0, nextDigit; int lengthOfX = length(x); //length of x will change in following loop int[] numbers = new int[10]; boolean isPandigital = true; //numbers represents occurrences of the numbers, set them to 0 occurrs for (i = 0; i < numbers.length; i++) { numbers[i] = 0; } //Go through x for its' numbers for (i = 0; i < lengthOfX; i++) { nextDigit = (int) x % 10; if (nextDigit == 0 || nextDigit > lengthOfX) { return false; } numbers[nextDigit] += 1; //Another occurance of this number x -= nextDigit; x /= 10; } //Now test the numbers array for more than one occurrence for (i = 0; i < numbers.length; i++) { if (numbers[i] > 1) { isPandigital = false; return false; } } return isPandigital; } public static long maxPandigitalPrime() { long maxPandigitalPrime = 0, startPos = 0, digitsSum = 3; boolean foundPrime = false; //Find the first pandigital not divisible by 3 for(int i = 9; i > 0 && digitsSum % 3 == 0; i--) { digitsSum = 0; for(int j = 1; j <= i; j++) { digitsSum += j; } String temp = ""; if(digitsSum % 3 != 0) { for(int k = i; k >= 1; k--) { temp += k; } startPos = Long.parseLong(temp); } } for (long i = startPos; i > 4231 && !foundPrime; i--) { if (isPandigital(i)) { if (isPrime(i)) { maxPandigitalPrime = i; foundPrime = true; } } } return maxPandigitalPrime; } public static void main(String[] args) { System.out.println(maxPandigitalPrime()); } } <file_sep>/Problem20.py def factorial(upperBound): factorial = 1 for i in range(1, upperBound): factorial = factorial * i return factorial def sumOfDigits(number): sum = 0 while(number > 0): sum = sum + (number % 10) number = number - (number % 10) number = number / 10 return sum number = 0 print(sumOfDigits(factorial(100))) <file_sep>/problem1.c #include <stdlib.h> #include <stdio.h> int main() { int multiple, sum = 0, iter, limit = 1000; bool multiples[1000] = {0}; for(multiple = 3; multiple < limit; multiple += 3) multiples[multiple] = true; for(multiple = 5; multiple < limit; multiple += 5) multiples[multiple] = true; for(iter = 0; iter < limit; iter++) { if(multiples[iter]) sum += iter; } printf("%d\n", sum); return 0; }
d9f48d376bb7e6b9e41fb0017692233c6464ef1b
[ "Ruby", "Markdown", "Java", "Python", "C" ]
38
Java
chiranthsiddappa/ProjectEuler
7fa22c48d38333cb1ac2fa07e42fc4d8334809a9
5d753b8c19b84edf126b87d852102f5cdceadf6b
refs/heads/master
<repo_name>sreeyushebusiness/devopscloudxlab<file_sep>/HelloWorld.py print('Hello World') print(3+4)
9f5fefc37828bbbe1ec9521dc38829f55c3dba6a
[ "Python" ]
1
Python
sreeyushebusiness/devopscloudxlab
39476a52d0affb80e090a1b87e217ba5ab8f445c
9e86bb96d3de9fdd711b7ed33cce4eef030a160a
refs/heads/master
<file_sep># Palindrome week2-day-1 Palindrome excersice using string and list objects <file_sep>################################################################################ # hi. This program plays a game inspired by the TV show "BigBang Theory". def cleanS ( string ): cleanS = string.strip() # get read off Leading and training spaces. cleanS = cleanS.lower() return cleanS def main (): sLine = input( 'Enter a word or phrase to check palindrome: ') sLine = cleanS( sLine) indexer = list() sLen = len(sLine) indexer = range(sLen) #Create an array for 0:len( sReverse = list() sReverseLine = '' for index in indexer : ##print ((sLen-1)-index) sReverse.append( sLine[(sLen-1)-index]) sReverseLine += sReverse[index] ##print(index) print(sLine) print(sReverse) print(sReverseLine) if( sLine == sReverseLine): print( 'String \"%s\" is a palindrome' %(sLine)) ################################################################################ # ################################################################################ main()
d94868aff7c3e33bf2b02ec82707ad870b4e475b
[ "Markdown", "Python" ]
2
Markdown
carloserodriguez2000/Palindrome
28c2672d011605e01f564f6196dcb7ef3075fabf
22a953eaa83c3c53d882022d82a8a744bfeacdc6
refs/heads/master
<repo_name>SHIHUAMarryMe/opengl_demo<file_sep>/transform/main.cpp #include <cmath> #include <iostream> #include <glad/glad.h> // must include this before glfw(#error OpenGL header already included, remove this include, glad already provides it); #include <GLFW/glfw3.h> #define GLM_FORCE_CXX14 #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> #include "stb_image/stb_image.h" static constexpr int WIDTH{800}; static constexpr int HEIGHT{600}; static constexpr const char *vertexShaderSource{ "#version 330 core\n" "layout (location = 0) in vec3 aPos;\n" "layout (location = 1) in vec2 aTexCoord;\n" "out vec2 texCoord;\n" "uniform mat4 model;\n" "uniform mat4 view;\n" "uniform mat4 projection;\n" "void main()\n" "{\n" " gl_Position = projection * view * model * vec4(aPos, 1.0);\n" " texCoord = vec2(aTexCoord.x, aTexCoord.y);\n" "}"}; static constexpr const char *fragmentShaderSource{ "#version 330 core\n" "out vec4 fragmentColor;\n" "in vec2 texCoord;\n" "uniform sampler2D texture1;\n" "uniform sampler2D texture2;\n" "void main()\n" "{\n" " fragmentColor = mix(texture(texture1, texCoord), texture(texture2, texCoord), 0.2);\n" "}"}; static void processInput(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); } static void framebuffer_size_callback(GLFWwindow *window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width // and height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); } int main() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // glfw window creation // -------------------- GLFWwindow *window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); if (window == nullptr) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); // glad: load all OpenGL function pointers if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // build and compile our shader program // ------------------------------------ // vertex shader int vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexShaderSource, nullptr); glCompileShader(vertexShader); // check for shader compile errors int success{}; char infoLog[512]{}; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vertexShader, 512, nullptr, infoLog); std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl; } // fragment shader int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentShaderSource, nullptr); glCompileShader(fragmentShader); // check for shader compile errors glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fragmentShader, 512, nullptr, infoLog); std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl; } // link shaders int shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); // check for linking errors glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog); std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl; } // after linking program, you can delete shaders. glDeleteShader(vertexShader); glDeleteShader(fragmentShader); const float vertices[]{ -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f}; // world space positions of our cubes const glm::vec3 cubePositions[]{ glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3(2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3(1.3f, -2.0f, -2.5f), glm::vec3(1.5f, 2.0f, -2.5f), glm::vec3(1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f)}; GLuint VAO{}; // vertex array object. GLuint VBO{}; // vertex buffer object. glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // tell shader how to parse vertices. // position attribute. GLint offset{}; glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void *>(offset)); glEnableVertexAttribArray(0); // texture coordinate. offset = 3 * sizeof(float); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void *>(offset)); glEnableVertexAttribArray(1); // load and create a texture GLuint texture{}; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); // all upcoming GL_TEXTURE_2D operations now have // effect on this texture object // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // load image, create texture and generate mipmaps GLint width{}, height{}, nrChannels{}; unsigned char *data{stbi_load("/home/shihua/projects/learn_opengl/transform/image/container.jpg", &width, &height, &nrChannels, 0)}; if (data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); data = nullptr; GLuint texture2{}; glGenTextures(1, &texture2); glBindTexture(GL_TEXTURE_2D, texture2); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // tell stb_image.h to flip loaded texture's on the y-axis. stbi_set_flip_vertically_on_load(true); // load image, create texture and generate mipmaps data = stbi_load("/home/shihua/projects/learn_opengl/transform/image/awesomeface.png", &width, &height, &nrChannels, 0); if (data) { // note that the awesomeface.png has transparency and thus an alpha channel, // so make sure to tell OpenGL the data type is of GL_RGBA glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); data = nullptr; // tell opengl for each sampler2D to which texture unit it belongs to (only // has to be done once) glUseProgram(shaderProgram); GLint texture1Id{glGetUniformLocation(shaderProgram, "texture1")}; glUniform1i(texture1Id, 0); GLint texture2Id{glGetUniformLocation(shaderProgram, "texture2")}; glUniform1i(texture2Id, 1); // set the uniform var projection. glm::mat4 projectionMat4{glm::perspective(glm::radians(45.0f), static_cast<float>(WIDTH / HEIGHT), 0.1f, 100.0f)}; GLint projectionLocation{glGetUniformLocation(shaderProgram, "projection")}; glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, &projectionMat4[0][0]); // render loop while (!glfwWindowShouldClose(window)) { // input // ----- processInput(window); // render // ------ glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear last time depth-testing. // bind textures to specify uniform. glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture2); // render container glUseProgram(shaderProgram); // camera/view glm::mat4 view{1.0f}; GLfloat radius{45.0f}; GLfloat cameraX{static_cast<GLfloat>(std::sin(glfwGetTime())) * radius}; GLfloat cameraZ{static_cast<GLfloat>(std::cos(glfwGetTime())) * radius}; view = glm::lookAt(glm::vec3{cameraX, 0.0f, cameraZ}, glm::vec3{.0f, .0f, .0f}, glm::vec3{.0f, 1.0f, .0f}); GLint viewLocation{glGetUniformLocation(shaderProgram, "view")}; glUniformMatrix4fv(viewLocation, 1, GL_FALSE, &view[0][0]); glBindVertexArray(VAO); std::size_t cubesN{sizeof(cubePositions) / sizeof(glm::vec3)}; for (std::size_t index = 0; index < cubesN; ++index) { glm::mat4 model{1.0f}; model = glm::translate(model, cubePositions[index]); // translate local position to world position. GLfloat angle{20.0f * index}; model = glm::rotate(model, glm::radians(angle), glm::vec3{1.0f, 0.3f, 0.5f}); // initialize model(matrix4) in glsl. GLint modelLocation{glGetUniformLocation(shaderProgram, "model")}; glUniformMatrix4fv(modelLocation, 1, GL_FALSE, &model[0][0]); glDrawArrays(GL_TRIANGLES, 0, 36); } // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved // etc.) glfwSwapBuffers(window); glfwPollEvents(); } // optional: de-allocate all resources once they've outlived their purpose: glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); // glfw: terminate, clearing all previously allocated GLFW resources. glfwTerminate(); return 0; }<file_sep>/camera/main.cpp #include <iostream> #define GLM_FORCE_CXX14 #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <glad/glad.h> #include <GLFW/glfw3.h> #include "stb_image/stb_image.h" static constexpr GLint WIDTH{800}; static constexpr GLint HEIGHT{600}; static glm::vec3 cameraPos{0.0f, 0.0f, 3.0f}; static glm::vec3 cameraFront{0.0f, 0.0f, -1.0f}; static glm::vec3 cameraUp{0.0f, 1.0f, 0.0f}; // camera static float delta_time{}; static float last_frame{}; //mouse and scroll static float field_of_view{45.0f}; static bool firstMouse{true}; static float lastX{800.f / 2.f}; static float lastY{600.f / 2.f}; static float pitch{}; static float yaw{-90.f}; static void processInput(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); float camera_speed{5.0f * delta_time}; if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { cameraPos += (cameraFront * camera_speed); } if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { cameraPos -= camera_speed * cameraFront; } if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { cameraPos -= glm::normalize(glm::cross(cameraFront, cameraUp)) * camera_speed; } if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) cameraPos += glm::normalize(glm::cross(cameraFront, cameraUp)) * camera_speed; } static void framebuffer_size_callback(GLFWwindow *window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width // and height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); } static void scroll_callback(GLFWwindow *window, double xoffset, double yoffset) { if (field_of_view >= 1.0f && field_of_view <= 45.0f) { field_of_view -= yoffset; } if (field_of_view <= 1.f) { field_of_view = 1.0f; } if (field_of_view >= 45.0f) { field_of_view = 45.0f; } std::cout << xoffset << "----------->" << yoffset << " " << field_of_view << std::endl; } // glfw: whenever the mouse moves, this callback is called // ------------------------------------------------------- static void mouse_callback(GLFWwindow *window, double xpos, double ypos) { if (firstMouse) { lastX = xpos; lastY = ypos; firstMouse = false; } float xoffset = xpos - lastX; float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top lastX = xpos; lastY = ypos; float sensitivity = 0.1f; // change this value to your liking xoffset *= sensitivity; yoffset *= sensitivity; yaw += xoffset; pitch += yoffset; // make sure that when pitch is out of bounds, screen doesn't get flipped if (pitch > 89.0f) pitch = 89.0f; if (pitch < -89.0f) pitch = -89.0f; glm::vec3 front{}; front.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch)); front.y = sin(glm::radians(pitch)); front.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch)); cameraFront = glm::normalize(front); } static constexpr const GLchar *vertexShaderSource{ "#version 330 core\n" "layout (location = 0) in vec3 aPos;\n" "layout (location = 1) in vec2 aTexCoord;\n" "out vec2 TexCoord;\n" "uniform mat4 model;\n" "uniform mat4 view;\n" "uniform mat4 projection;\n" "void main()\n" "{\n" " gl_Position = projection * view * model * vec4(aPos, 1.0f);\n" " TexCoord = vec2(aTexCoord.x, aTexCoord.y);\n" "}"}; static constexpr const GLchar *fragmentShaderSource{ "#version 330 core\n" "out vec4 FragColor;\n" "in vec2 TexCoord;\n" // texture samplers "uniform sampler2D texture1;\n" "uniform sampler2D texture2;\n" "void main()\n" "{\n" // linearly interpolate between both textures (80% container, 20% awesomeface) " FragColor = mix(texture(texture1, TexCoord), texture(texture2, TexCoord), 0.2);\n" "}"}; int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X #endif // glfw window creation // -------------------- GLFWwindow *window{glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr)}; if (window == nullptr) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetScrollCallback(window, scroll_callback); glfwSetCursorPosCallback(window, mouse_callback); // tell GLFW to capture our mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } glEnable(GL_DEPTH_TEST); GLuint vertexShader{}, fragmentShader{}; // vertex shader vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexShaderSource, nullptr); glCompileShader(vertexShader); GLint success{}; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success); if (!success) { GLchar infoLog[1024]{}; glGetShaderInfoLog(vertexShader, 1024, nullptr, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } // fragment Shader fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentShaderSource, nullptr); glCompileShader(fragmentShader); success = 0; glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success); if (!success) { GLchar infoLog[1024]{}; glGetShaderInfoLog(fragmentShader, 1024, nullptr, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } // shader Program GLuint programId{glCreateProgram()}; glAttachShader(programId, vertexShader); glAttachShader(programId, fragmentShader); glLinkProgram(programId); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ const float vertices[]{ -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f}; // world space positions of our cubes const glm::vec3 cubePositions[]{ glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3(2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3(1.3f, -2.0f, -2.5f), glm::vec3(1.5f, 2.0f, -2.5f), glm::vec3(1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f)}; GLuint VBO{}, VAO{}; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void *>(0)); glEnableVertexAttribArray(0); // texture coord attribute glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void *>(3 * sizeof(float))); glEnableVertexAttribArray(1); // load and create a texture // ------------------------- GLuint texture1{}; // texture 1 // --------- glGenTextures(1, &texture1); glBindTexture(GL_TEXTURE_2D, texture1); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // load image, create texture and generate mipmaps GLint width{}, height{}, nrChannels{}; stbi_set_flip_vertically_on_load(true); // tell stb_image.h to flip loaded texture's on the y-axis. unsigned char *data = stbi_load("/home/shihua/projects/learn_opengl/camera/image/container.jpg", &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); data = nullptr; GLuint texture2{}; glGenTextures(1, &texture2); glBindTexture(GL_TEXTURE_2D, texture2); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); width = 0; height = 0; nrChannels = 0; data = stbi_load("/home/shihua/projects/learn_opengl/camera/image/awesomeface.png", &width, &height, &nrChannels, 0); if (data) { // note that the awesomeface.png has transparency and thus an alpha channel, so make sure to tell OpenGL the data type is of GL_RGBA glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); data = nullptr; glUseProgram(programId); GLint tex1_loc{glGetUniformLocation(programId, "texture1")}; glUniform1i(tex1_loc, 0); GLint tex2_loc{glGetUniformLocation(programId, "texture2")}; glUniform1i(tex2_loc, 1); while (!glfwWindowShouldClose(window)) { float currentFrame{glfwGetTime()}; delta_time = currentFrame - last_frame; last_frame = currentFrame; processInput(window); glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // bind textures on corresponding texture units glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture1); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture2); glUseProgram(programId); glm::mat4 projection{glm::perspective(glm::radians(field_of_view), static_cast<float>(WIDTH / HEIGHT), 0.1f, 100.0f)}; glUniformMatrix4fv(glGetUniformLocation(programId, "projection"), 1, GL_FALSE, &projection[0][0]); // camera/view transformation glm::mat4 view{1.0f}; // make sure to initialize matrix to identity matrix first view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp); glUniformMatrix4fv(glGetUniformLocation(programId, "view"), 1, GL_FALSE, &view[0][0]); // render boxes glBindVertexArray(VAO); for (unsigned int i = 0; i < 10; i++) { // calculate the model matrix for each object and pass it to shader before drawing glm::mat4 model{1.0f}; model = glm::translate(model, cubePositions[i]); float angle = 20.0f * i; model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.0f, 0.0f)); glUniformMatrix4fv(glGetUniformLocation(programId, "model"), 1, GL_FALSE, &model[0][0]); glDrawArrays(GL_TRIANGLES, 0, 36); } // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return 0; return 0; }<file_sep>/draw_circle/main.cpp #include <cmath> #include <iostream> #include <glad/glad.h> // must include this before glfw(#error OpenGL header already included, remove this include, glad already provides it); #include <GLFW/glfw3.h> #define GLM_FORCE_CXX14 #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "stb_image/stb_image.h" static constexpr int WIDTH{800}; static constexpr int HEIGHT{600}; static constexpr const char *vertexShaderSource{ "#version 330 core\n" "layout (location = 0) in vec3 aPos;\n" "layout (location = 1) in vec2 aTexCoord;\n" "out vec2 texCoord;\n" "uniform mat4 model;\n" "uniform mat4 view;\n" "uniform mat4 projection;\n" "void main()\n" "{\n" " gl_Position = projection * view * model * vec4(aPos, 1.0);\n" " texCoord = vec2(aTexCoord.x, aTexCoord.y);\n" "}"}; static constexpr const char *fragmentShaderSource{ "#version 330 core\n" "out vec4 fragmentColor;\n" "in vec2 texCoord;\n" "uniform sampler2D texture1;\n" "uniform sampler2D texture2;\n" "void main()\n" "{\n" " fragmentColor = mix(texture(texture1, texCoord), texture(texture2, " "texCoord), 0.2);\n" "}"}; static void processInput(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); } static void framebuffer_size_callback(GLFWwindow *window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width // and height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); } const int n = 3; const GLfloat R = 0.5f; const GLfloat pi = 3.1415926536f; int main() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // glfw window creation // -------------------- GLFWwindow *window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); if (window == nullptr) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); // glad: load all OpenGL function pointers if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // render loop while (!glfwWindowShouldClose(window)) { // input // ----- processInput(window); // render // ------ glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear last time depth-testing. int i = 0; glClear(GL_COLOR_BUFFER_BIT); // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved glfwSwapBuffers(window); glfwPollEvents(); } // glfw: terminate, clearing all previously allocated GLFW resources. glfwTerminate(); return 0; }<file_sep>/window_blending/window_blending/main.cpp #define GLM_FORCE_CXX14 #define GLM_FORCE_INTRINSICS #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glad/glad.h> #include <GLFW/glfw3.h> #include <map> #include <vector> #include <atomic> #include <iostream> #include "shader.hpp" #include "stb_image/stb_image.h" static const int WIDTH{ 1280 }; static const int HEIGHT{ 720 }; // lighting. static const glm::vec3 light_pos{ 1.2f, 1.0f, 2.0f }; // camera static glm::vec3 camera_pos{ 0.0f, 0.0f, 3.0f }; static glm::vec3 camera_front{}; static glm::vec3 camera_up{ 0.0f, 1.0f, 0.0f }; static glm::vec3 camera_right{}; static glm::vec3 world_up = camera_up; static float delta_time{}; static float last_frame{}; //mouse and scroll static float field_of_view{ 45.0f }; static std::atomic<bool> first_click{ true }; static float lastX{ WIDTH / 2.f }; static float lastY{ HEIGHT / 2.f }; static float pitch{ 0.0f }; static float yaw{ -90.f }; static float speed{ 2.5f }; static float sensitivity{ 0.05f }; static void update_camera_vectors() { // Calculate the new Front vector glm::vec3 front{}; front.x = std::cos(glm::radians(yaw)) * std::cos(glm::radians(pitch)); front.y = std::sin(glm::radians(pitch)); front.z = std::sin(glm::radians(yaw)) * std::cos(glm::radians(pitch)); camera_front = glm::normalize(front); // Also re-calculate the Right and Up vector camera_right = glm::normalize(glm::cross(camera_front, world_up)); // Normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement. camera_up = glm::normalize(glm::cross(camera_right, camera_front)); } // process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly // --------------------------------------------------------------------------------------------------------- static void process_input(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); float camera_speed{ speed * delta_time }; if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { camera_pos += (camera_front * camera_speed); } if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { camera_pos -= camera_speed * camera_front; } if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { camera_pos -= camera_right * camera_speed; } if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) { camera_pos += camera_right * camera_speed; } } // glfw: whenever the window size changed (by OS or user resize) this callback function executes // --------------------------------------------------------------------------------------------- static void framebuffer_size_callback(GLFWwindow *window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); } // glfw: whenever the mouse moves, this callback is called // ------------------------------------------------------- static void mouse_callback(GLFWwindow *window, double xpos, double ypos) { if (first_click.load()) { lastX = xpos; lastY = ypos; first_click.store(false); } float xoffset = xpos - lastX; float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top lastX = xpos; lastY = ypos; xoffset *= sensitivity; yoffset *= sensitivity; yaw += xoffset; pitch += yoffset; // make sure that when pitch is out of bounds, screen doesn't get flipped if (pitch > 89.0f) pitch = 89.0f; if (pitch < -89.0f) pitch = -89.0f; update_camera_vectors(); } // glfw: whenever the mouse scroll wheel scrolls, this callback is called // ---------------------------------------------------------------------- static void scroll_callback(GLFWwindow *window, double xoffset, double yoffset) { if (field_of_view >= 1.0f && field_of_view <= 45.0f) { field_of_view -= yoffset; } if (field_of_view <= 1.f) { field_of_view = 1.0f; } if (field_of_view >= 45.0f) { field_of_view = 45.0f; } } static GLuint load_texture(const char * path) { GLuint texture_id{}; glGenTextures(1, &texture_id); int width{}, height{}, nrComponents{}; unsigned char *data{ stbi_load(path, &width, &height, &nrComponents, 0) }; if (data) { GLenum format{}; if (nrComponents == 1) format = GL_RED; else if (nrComponents == 3) format = GL_RGB; else if (nrComponents == 4) format = GL_RGBA; glBindTexture(GL_TEXTURE_2D, texture_id); glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(data); } else { std::cout << __FUNCTION__ << " " << __LINE__ << " " << "Texture failed to load at path : " << path << std::endl; stbi_image_free(data); } data = nullptr; return texture_id; } int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // glfw window creation // -------------------- GLFWwindow *window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); if (window == nullptr) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // tell GLFW to capture our mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader(reinterpret_cast<GLADloadproc>(glfwGetProcAddress))) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // update camera parameters. update_camera_vectors(); // configure global opengl state glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); GLuint vertex_shader_id{ shader::create("C:\\Users\\shihua\\source\\repos\\opengl_demo\\depth_test\\depth_test\\glsl\\stencil_testing_vertex_shader.glsl", shader_type::vertex_shader) }; GLuint fragment_shader_id{ shader::create("C:\\Users\\shihua\\source\\repos\\opengl_demo\\depth_test\\depth_test\\glsl\\stencil_testing_fragment_shader.glsl", shader_type::fragment_shader) }; GLuint program_id{ glCreateProgram() }; glAttachShader(program_id, vertex_shader_id); glAttachShader(program_id, fragment_shader_id); glLinkProgram(program_id); glDeleteShader(vertex_shader_id); glDeleteShader(fragment_shader_id); shader::checkout_shader_state(program_id, shader_type::program); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ const float cubes_vertices[]{ // positions // texture Coords -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f }; const float floor_vertices[]{ // positions // texture Coords 5.0f, -0.5f, 5.0f, 2.0f, 0.0f, -5.0f, -0.5f, 5.0f, 0.0f, 0.0f, -5.0f, -0.5f, -5.0f, 0.0f, 2.0f, 5.0f, -0.5f, 5.0f, 2.0f, 0.0f, -5.0f, -0.5f, -5.0f, 0.0f, 2.0f, 5.0f, -0.5f, -5.0f, 2.0f, 2.0f }; const float window_vertices[]{ // positions // texture Coords (swapped y coordinates because texture is flipped upside down) 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.0f, 0.0f, 1.0f, 1.0f, -0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.0f, 1.0f, 0.0f }; GLuint cube_VAO{}; GLuint cube_VBO{}; glGenVertexArrays(1, &cube_VAO); glGenBuffers(1, &cube_VBO); glBindVertexArray(cube_VAO); glBindBuffer(GL_ARRAY_BUFFER, cube_VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(cubes_vertices), cubes_vertices, GL_STATIC_DRAW); std::size_t offset{ 0 }; glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(offset)); offset = 3 * sizeof(float); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(offset)); // notice that. glBindVertexArray(0); GLuint floor_VAO{}; GLuint floor_VBO{}; glGenVertexArrays(1, &floor_VAO); glGenBuffers(1, &floor_VBO); glBindVertexArray(floor_VAO); glBindBuffer(GL_ARRAY_BUFFER, floor_VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(floor_vertices), floor_vertices, GL_STATIC_DRAW); offset = 0; glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(offset)); offset = 3 * sizeof(float); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(offset)); // notice that glBindVertexArray(0); // transparent VAO GLuint window_VAO{}, window_VBO{}; glGenVertexArrays(1, &window_VAO); glGenBuffers(1, &window_VBO); glBindVertexArray(window_VAO); glBindBuffer(GL_ARRAY_BUFFER, window_VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(window_vertices), window_vertices, GL_STATIC_DRAW); offset = 0; glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(offset)); offset = 3 * sizeof(float); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(offset)); glBindVertexArray(0); GLuint wall_texture_id{ load_texture("C:\\Users\\shihua\\source\\repos\\opengl_demo\\window_blending\\window_blending\\image\\marble.jpg") }; GLuint floor_texture_id{ load_texture("C:\\Users\\shihua\\source\\repos\\opengl_demo\\window_blending\\window_blending\\image\\metal.png") }; GLuint window_texture_id{ load_texture("C:\\Users\\shihua\\source\\repos\\opengl_demo\\window_blending\\window_blending\\image\\blending_transparent_window.png") }; std::vector<glm::vec3> windows_locations { glm::vec3(-1.5f, 0.0f, -0.48f), glm::vec3(1.5f, 0.0f, 0.51f), glm::vec3(0.0f, 0.0f, 0.7f), glm::vec3(-0.3f, 0.0f, -2.3f), glm::vec3(0.5f, 0.0f, -0.6f) }; glUseProgram(program_id); shader::set_int(program_id, "texture_1", 0); while (!glfwWindowShouldClose(window)) { double current_time{ glfwGetTime() }; delta_time = current_time - last_frame; last_frame = current_time; process_input(window); // sort the transparent windows before rendering // --------------------------------------------- std::map<float, glm::vec3> sorted; for (std::size_t index = 0; index < windows_locations.size(); ++index) { float distance = glm::length(camera_pos - windows_locations[index]); sorted[distance] = windows_locations[index]; } glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(program_id); glm::mat4 projection{ glm::perspective(glm::radians(field_of_view), WIDTH * 1.0f / HEIGHT * 1.0f, 0.1f, 100.0f) }; glm::mat4 view{ glm::lookAt(camera_pos, camera_pos + camera_front, camera_up) }; glm::mat4 model{ 1.0f }; shader::set_mat4(program_id, "projection", projection); shader::set_mat4(program_id, "view", view); // cubes glBindVertexArray(cube_VAO); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, wall_texture_id); model = glm::translate(model, glm::vec3(-1.0f, 0.0f, -1.0f)); shader::set_mat4(program_id, "model", model); glDrawArrays(GL_TRIANGLES, 0, 36); model = glm::mat4{ 1.0f }; model = glm::translate(model, glm::vec3(2.0f, 0.0f, 0.0f)); shader::set_mat4(program_id, "model", model); glDrawArrays(GL_TRIANGLES, 0, 36); // floor glBindVertexArray(floor_VAO); glBindTexture(GL_TEXTURE_2D, floor_texture_id); model = glm::mat4(1.0f); shader::set_mat4(program_id, "model", model); glDrawArrays(GL_TRIANGLES, 0, 36); // windows (from furthest to nearest) glBindVertexArray(window_VAO); glBindTexture(GL_TEXTURE_2D, window_texture_id); for (std::map<float, glm::vec3>::reverse_iterator it = sorted.rbegin(); it != sorted.rend(); ++it) { model = glm::mat4(1.0f); model = glm::translate(model, it->second); shader::set_mat4(program_id, "model", model); glDrawArrays(GL_TRIANGLES, 0, 6); } // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glDeleteVertexArrays(1, &cube_VAO); glDeleteVertexArrays(1, &floor_VAO); glDeleteVertexArrays(1, &window_VAO); glDeleteBuffers(1, &cube_VBO); glDeleteBuffers(1, &floor_VBO); glDeleteBuffers(1, &window_VBO); glfwTerminate(); return 0; }<file_sep>/lightcasters-pointlight/CMakeLists.txt cmake_minimum_required(VERSION 3.10) project(lightcasters-pointlight) set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-ggdb -O2") set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) message(${CMAKE_CXX_FLAGS}) include_directories("../glad/include") include_directories("./stb_image") include_directories("../glm") find_package(glfw3 3.3 REQUIRED) find_package(OpenGL REQUIRED) if(glfw3_FOUND) message("found glfw3") endif() if(OpenGL_FOUND) message("found opengl") endif() add_executable(${PROJECT_NAME} main.cpp glad_src/glad.c stb_image/stb_image.cpp) target_link_libraries(${PROJECT_NAME} # Boost::system glfw3 #if do not link glfwxxx.a will: undefined reference to symbol 'pthread_key_delete@@GLIBC_2.2.5' pthread m GL GLU X11 Xxf86vm Xrandr Xi dl ) <file_sep>/exploding_object/exploding_object/main.cpp #include <assimp/Importer.hpp> #include <assimp/scene.h> #include <assimp/postprocess.h> #include <assimp/texture.h> #include <assimp/mesh.h> #define GLM_FORCE_CXX14 #define GLM_FORCE_INTRINSICS #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glad/glad.h> #include <GLFW/glfw3.h> #include <atomic> #include <iostream> #include "shader.hpp" #include "model.hpp" static constexpr const int WIDTH{ 800 }; static constexpr const int HEIGHT{ 600 }; // lighting. static const glm::vec3 light_pos{ 1.2f, 1.0f, 2.0f }; // camera static glm::vec3 camera_pos{ 0.0f, 0.0f, 3.0f }; static glm::vec3 camera_front{}; static glm::vec3 camera_up{ 0.0f, 1.0f, 0.0f }; static glm::vec3 camera_right{}; static glm::vec3 world_up = camera_up; static float delta_time{}; static float last_frame{}; //mouse and scroll static float field_of_view{ 45.0f }; static std::atomic<bool> first_click{ true }; static float lastX{ WIDTH / 2.f }; static float lastY{ HEIGHT / 2.f }; static float pitch{ 0.0f }; static float yaw{ -90.f }; static float speed{ 2.5f }; static float sensitivity{ 0.05f }; static void update_camera_vectors() { // Calculate the new Front vector glm::vec3 front{}; front.x = std::cos(glm::radians(yaw)) * std::cos(glm::radians(pitch)); front.y = std::sin(glm::radians(pitch)); front.z = std::sin(glm::radians(yaw)) * std::cos(glm::radians(pitch)); camera_front = glm::normalize(front); // Also re-calculate the Right and Up vector // Normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement. camera_right = glm::normalize(glm::cross(camera_front, world_up)); camera_up = glm::normalize(glm::cross(camera_right, camera_front)); } // process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly // --------------------------------------------------------------------------------------------------------- static void process_input(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); float camera_speed{ speed * delta_time }; if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { camera_pos += (camera_front * camera_speed); } if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { camera_pos -= camera_speed * camera_front; } if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { camera_pos -= camera_right * camera_speed; } if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) { camera_pos += camera_right * camera_speed; } } // glfw: whenever the window size changed (by OS or user resize) this callback function executes // --------------------------------------------------------------------------------------------- static void framebuffer_size_callback(GLFWwindow *window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); } // glfw: whenever the mouse moves, this callback is called // ------------------------------------------------------- static void mouse_callback(GLFWwindow *window, double xpos, double ypos) { if (first_click.load()) { lastX = xpos; lastY = ypos; first_click.store(false); } float xoffset = xpos - lastX; float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top lastX = xpos; lastY = ypos; xoffset *= sensitivity; yoffset *= sensitivity; yaw += xoffset; pitch += yoffset; // make sure that when pitch is out of bounds, screen doesn't get flipped if (pitch > 89.0f) pitch = 89.0f; if (pitch < -89.0f) pitch = -89.0f; update_camera_vectors(); } // glfw: whenever the mouse scroll wheel scrolls, this callback is called // ---------------------------------------------------------------------- static void scroll_callback(GLFWwindow *window, double xoffset, double yoffset) { if (field_of_view >= 1.0f && field_of_view <= 45.0f) { field_of_view -= yoffset; } if (field_of_view <= 1.f) { field_of_view = 1.0f; } if (field_of_view >= 45.0f) { field_of_view = 45.0f; } } int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // glfw window creation // -------------------- GLFWwindow *window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); if (window == nullptr) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // tell GLFW to capture our mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader(reinterpret_cast<GLADloadproc>(glfwGetProcAddress))) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // configure global opengl state glEnable(GL_DEPTH_TEST); GLuint vertex_shader_id{ shader::create("C:\\Users\\y\\Documents\\Visual Studio 2017\\Projects\\opengl_demo\\exploding_object\\exploding_object\\glsl\\verterx_shader.glsl", shader_type::vertex_shader) }; GLuint geometry_shader_id{ shader::create("C:\\Users\\y\\Documents\\Visual Studio 2017\\Projects\\opengl_demo\\exploding_object\\exploding_object\\glsl\\geometry_shader.glsl", shader_type::geometry_shader) }; GLuint fragment_shader_id{ shader::create("C:\\Users\\y\\Documents\\Visual Studio 2017\\Projects\\opengl_demo\\exploding_object\\exploding_object\\glsl\\fragment_shader.glsl", shader_type::fragment_shader) }; GLuint gl_program_id{ glCreateProgram() }; glAttachShader(gl_program_id, vertex_shader_id); glAttachShader(gl_program_id, geometry_shader_id); glAttachShader(gl_program_id, fragment_shader_id); glLinkProgram(gl_program_id); shader::checkout_shader_state(gl_program_id, shader_type::program); std::unique_ptr<model_loader> model_loader_ptr{ std::make_unique<model_loader>() }; model_loader_ptr->load_model("C:\\Users\\shihua\\source\\repos\\opengl_demo\\mesh\\mesh\\image\\nanosuit\\nanosuit.obj"); model_loader_ptr->load_vertices_data(); while (!glfwWindowShouldClose(window)) { double current_time{ glfwGetTime() }; delta_time = current_time - last_frame; last_frame = current_time; glClearColor(0.5f, 0.5f, 0.5f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(gl_program_id); // configure transformation matrices glm::mat4 projection{ glm::perspective(glm::radians(45.0f), (WIDTH / HEIGHT)*1.0f, 1.0f, 100.0f) }; glm::mat4 view{ 1.0f }; // make sure to initialize matrix to identity matrix first view = glm::lookAt(camera_pos, camera_pos + camera_front, camera_up); glm::mat4 model{ glm::mat4{1.0f } }; shader::set_mat4(gl_program_id, "projection", projection); shader::set_mat4(gl_program_id, "model", model); shader::set_mat4(gl_program_id, "view", view); shader::set_float(gl_program_id, "time", glfwGetTime()); // render model. model_loader_ptr->draw(gl_program_id); // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return 0; } <file_sep>/lightcasters-cllimated_light/README.MD # notice - here **material.specular_**, I use GL_TEXTURE1 for sampling. It means that the specular value of middle positions(which is wood material) are vec3(0.0); - because of **GL_TEXTURE1** is black color in middle postions, so **vec3 specularVec = light.specular_ * specularValue * texture(material.specular_, TexCoords).rgb** will be 0(zero). - so, **middle positions(GL_TEXTURE1)** just has ambient value and diffuse value. <file_sep>/multi-lightsource/multi-lightsource/main.cpp #define GLM_FORCE_CXX14 #define GLM_FORCE_INTRINSICS #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glad/glad.h> #include <GLFW/glfw3.h> #include <iostream> #include "stb_image/stb_image.h" static constexpr const int WIDTH{ 800 }; static constexpr const int HEIGHT{ 600 }; // lighting. static const glm::vec3 light_pos{ 1.2f, 1.0f, 2.0f }; // camera static glm::vec3 cameraPos{ 0.0f, 0.0f, 3.0f }; static glm::vec3 cameraFront{}; static glm::vec3 cameraUp{ 0.0f, 1.0f, 0.0f }; static glm::vec3 cameraRight{}; static glm::vec3 worldUp = cameraUp; static float delta_time{}; static float last_frame{}; //mouse and scroll static float field_of_view{ 45.0f }; static bool firstMouse{ true }; static float lastX{ WIDTH / 2.f }; static float lastY{ HEIGHT / 2.f }; static float pitch{ 0.0f }; static float yaw{ -90.f }; static float speed{ 2.5f }; static float sensitivity{ 0.05f }; static void updateCameraVectors() { // Calculate the new Front vector glm::vec3 front{}; front.x = std::cos(glm::radians(yaw)) * std::cos(glm::radians(pitch)); front.y = std::sin(glm::radians(pitch)); front.z = std::sin(glm::radians(yaw)) * std::cos(glm::radians(pitch)); cameraFront = glm::normalize(front); // Also re-calculate the Right and Up vector cameraRight = glm::normalize(glm::cross(cameraFront, worldUp)); // Normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement. cameraUp = glm::normalize(glm::cross(cameraRight, cameraFront)); } static constexpr const char *cubeVertexShaderSource{ "#version 330 core\n" "layout (location = 0) in vec3 aPos;\n" "layout (location = 1) in vec3 aNormal;\n" "layout (location = 2) in vec2 aTexCoords;\n" "out vec3 FragPos;\n" "out vec3 Normal;\n" "out vec2 TexCoords;\n" "uniform mat4 model;\n" "uniform mat4 view;\n" "uniform mat4 projection;\n" "void main()\n" "{\n" " FragPos = vec3(model * vec4(aPos, 1.0));\n" " TexCoords = aTexCoords;\n" // must use Normal Matrix, it can keep NU Scale right. " Normal = mat3(transpose(inverse(model))) * aNormal;\n" //transpose(inverse(model)) create Normal Matrix. " gl_Position = projection * view * vec4(FragPos, 1.0);\n" "}" }; static constexpr const char *cubeFragmentShaderSource{ "#version 330 core\n" "out vec4 FragColor;\n" "struct Material\n" "{\n" " sampler2D diffuse_;\n" " sampler2D specular_;\n" " float shininess_;\n" "};\n" "struct DirLight {\n" " vec3 direction_;\n" " vec3 ambient_;\n" " vec3 diffuse_;\n" " vec3 specular_;\n" "};\n" "struct PointLight\n" "{\n" " vec3 position_;\n" " float constant_;\n" " float linear_;\n" " float quadratic_;\n" " vec3 ambient_;\n" " vec3 diffuse_;\n" " vec3 specular_;\n" "};\n" "struct Material\n" "{\n" " sampler2D diffuse_;\n" //ambient color is the same with diffuse color, ususally. " sampler2D specular_;\n" " float shininess_;\n" "};\n" "struct SpotLight" "{\n" "vec3 position_;\n" // bes same with camera position. "vec3 direction_;\n" // be same with camera direction. "float cutoff_;\n" "float outer_cutoff_;\n" "float constant_;\n" "float linear_;\n" "float quadratic_;\n" "vec3 ambient_;\n" "vec3 diffuse_;\n" "vec3 specular_;\n" "};\n" "#define NR_POINT_LIGHTS 4\n" "in vec3 Normal;\n" "in vec3 FragPos;\n" "in vec2 TexCoords;\n" "uniform Material material;\n" "uniform DirLight dirLight;\n" // cllimated light "uniform PointLight pointLights[NR_POINT_LIGHTS];\n" // point lights "uniform SpotLight spotLight;\n" // flash light "uniform vec3 cameraPos;\n" //camera pos. "vec3 CalcDirLight(DirLight dir_light, vec3 normal, vec3 viewer_dir);\n" "vec3 CalcPointLight(PointLight point_light, vec3 normal, vec3 frag_pos, vec3 viewer_dir);\n" "vec3 CalcSpotLight(SpotLight spot_light, vec3 normal, vec3 frag_pos, vec3 viewer_dir);\n" "void main()\n" "{\n" // properties "vec3 norm = normalize(Normal);\n" "vec3 viewDir = normalize(cameraPos - FragPos);\n" // == ===================================================== // Our lighting is set up in 3 phases: directional, point lights and an optional flashlight // For each phase, a calculate function is defined that calculates the corresponding color // per lamp. In the main() function we take all the calculated colors and sum them up for // this fragment's final color. // == ===================================================== // phase 1: directional lighting "vec3 result = CalcDirLight(dirLight, norm, viewDir);\n" // phase 2: point lights "for (int i = 0; i < NR_POINT_LIGHTS; i++)\n" " result += CalcPointLight(pointLights[i], norm, FragPos, viewDir);\n" // phase 3: spot light "result += CalcSpotLight(spotLight, norm, FragPos, viewDir);\n" "FragColor = vec4(result, 1.0);\n" "}\n" "vec3 CalcDirLight(DirLight dir_light, vec3 normal, vec3 viewer_dir)" "{\n" "vec3 light_direction = normalize(-dir_light.direction_);\n" // diffuse "float diffuse_value = max(dot(light_direction, normal), 0.0f);\n" // specular "vec3 reflect_direction = reflect(-light_direction, normal);\n" "float specular_value = pow(max(dot(viewer_dir, reflect_direction), 0.0f), material.shininess_);\n" "vec3 ambient = dir_light.ambient_ * vec3(texture(material.diffuse_, TexCoords));\n" "vec3 diffuse = dir_light.diffuse_ * diffuse_value * vec3(texture(material.diffuse_, TexCoords));\n" "vec3 specular = dir_light.specular_ * specular_value * vec3(texture(material.specular_, TexCoords));\n" "return (ambient + diffuse + specular);\n" "}\n" "vec3 CalcPointLight(PointLight point_light, vec3 normal, vec3 frag_pos, vec3 viewer_dir)\n" "{\n" "vec3 light_direction = normalize(point_light.position_ - frag_pos);\n" // diffuse "float diffuse_value = max(dot(light_direction, normal), 0.0f);\n" // specular "vec3 reflect_direction = reflect(-light_direction, normal);\n" "float specular_value = pow(max(dot(viewer_dir, reflect_direction), 0.0), material.shininess_);\n" // attenuation "float distance = length(point_light.position_ - frag_pos);\n" "float attenuation_value = 1.0f / (point_light.constant_ + point_light.linear_ * distance + point_light.quadratic_ * (distance * distance));\n" "vec3 ambient = point_light.ambient_ * vec3(texture(material.diffuse_, TexCoords));\n" "vec3 diffuse = point_light.diffuse_ * diffuse_value * vec3(texture(material.diffuse_, TexCoords));\n" "vec3 specular = point_light.specular_ * specular_value * vec3(texture(material.specular_, TexCoords));\n" "ambient *= attenuation_value;\n" "diffuse *= attenuation_value;\n" "specular *= attenuation_value;\n" "return (ambient + diffuse + specular);\n" "}\n" // calculates the color when using a spot light. "vec3 CalcSpotLight(SpotLight spot_light, vec3 normal, vec3 frag_pos, vec3 viewer_dir)\n" "{\n" "vec3 light_direction = normalize(spot_light.position_ - frag_pos);\n" // diffuse shading "float diff = max(dot(normal, light_direction), 0.0);\n" // specular shading "vec3 reflect_direction = reflect(-light_direction, normal);\n" "float spec = pow(max(dot(viewer_dir, reflect_direction), 0.0), material.shininess_);\n" // attenuation "float distance = length(spot_light.position_ - frag_pos);\n" "float attenuation = 1.0f / (spot_light.constant_ + spot_light.linear_ * distance + spot_light.quadratic_ * (distance * distance));\n" // spotlight intensity "float theta = dot(light_direction, normalize(-spot_light.direction_));\n" "float epsilon = spot_light.cutoff_ - spot_light.outer_cutoff_;\n" "float intensity = clamp((theta - spot_light.outer_cutoff_) / epsilon, 0.0, 1.0);\n" // combine results "vec3 ambient = spot_light.ambient_ * vec3(texture(material.diffuse_, TexCoords));\n" "vec3 diffuse = spot_light.diffuse_ * diff * vec3(texture(material.diffuse_, TexCoords));\n" "vec3 specular = spot_light.specular_ * spec * vec3(texture(material.specular_, TexCoords));\n" "ambient *= attenuation * intensity;\n" "diffuse *= attenuation * intensity;\n" "specular *= attenuation * intensity;\n" "return (ambient + diffuse + specular);\n" "}\n" }; static constexpr const char *lampVertexShaderSource{ "#version 330 core\n" "layout (location = 0) in vec3 aPos;\n" "uniform mat4 model;\n" "uniform mat4 view;\n" "uniform mat4 projection;\n" "void main()\n" "{\n" " gl_Position = projection * view * model * vec4(aPos, 1.0);\n" "}" }; static constexpr const char *lampFragmentShaderSource{ "#version 330 core\n" "out vec4 FragColor;\n" "void main()\n" "{\n" " FragColor = vec4(1.0);\n" // set alle 4 vector values to 1.0 "}" }; // process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly // --------------------------------------------------------------------------------------------------------- static void processInput(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); float camera_speed{ speed * delta_time }; if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { cameraPos += (cameraFront * camera_speed); } if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { cameraPos -= camera_speed * cameraFront; } if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { cameraPos -= cameraRight * camera_speed; } if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) cameraPos += cameraRight * camera_speed; } // glfw: whenever the window size changed (by OS or user resize) this callback function executes // --------------------------------------------------------------------------------------------- void framebuffer_size_callback(GLFWwindow *window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); } // glfw: whenever the mouse moves, this callback is called // ------------------------------------------------------- static void mouse_callback(GLFWwindow *window, double xpos, double ypos) { if (firstMouse) { lastX = xpos; lastY = ypos; firstMouse = false; } float xoffset = xpos - lastX; float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top lastX = xpos; lastY = ypos; xoffset *= sensitivity; yoffset *= sensitivity; yaw += xoffset; pitch += yoffset; // make sure that when pitch is out of bounds, screen doesn't get flipped if (pitch > 89.0f) pitch = 89.0f; if (pitch < -89.0f) pitch = -89.0f; updateCameraVectors(); } // glfw: whenever the mouse scroll wheel scrolls, this callback is called // ---------------------------------------------------------------------- static void scroll_callback(GLFWwindow *window, double xoffset, double yoffset) { if (field_of_view >= 1.0f && field_of_view <= 45.0f) { field_of_view -= yoffset; } if (field_of_view <= 1.f) { field_of_view = 1.0f; } if (field_of_view >= 45.0f) { field_of_view = 45.0f; } } int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // glfw window creation // -------------------- GLFWwindow *window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); if (window == nullptr) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // tell GLFW to capture our mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader(reinterpret_cast<GLADloadproc>(glfwGetProcAddress))) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // configure global opengl state // ----------------------------- glEnable(GL_DEPTH_TEST); // notice that: count camera front/up/right vectors. updateCameraVectors(); // cube shaders. GLuint cubeVertexShader{}; GLuint cubeFragmentShader{}; cubeVertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(cubeVertexShader, 1, &cubeVertexShaderSource, nullptr); glCompileShader(cubeVertexShader); GLint success{}; glGetShaderiv(cubeVertexShader, GL_COMPILE_STATUS, &success); if (!success) { GLchar infoLog[1024]{}; glGetShaderInfoLog(cubeVertexShader, 1024, nullptr, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } cubeFragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(cubeFragmentShader, 1, &cubeFragmentShaderSource, nullptr); glCompileShader(cubeFragmentShader); success = 0; glGetShaderiv(cubeFragmentShader, GL_COMPILE_STATUS, &success); if (!success) { GLchar infoLog[1024]{}; glGetShaderInfoLog(cubeFragmentShader, 1024, nullptr, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } GLuint cubeProgramId{ glCreateProgram() }; glAttachShader(cubeProgramId, cubeVertexShader); glAttachShader(cubeProgramId, cubeFragmentShader); glLinkProgram(cubeProgramId); success = 0; glGetProgramiv(cubeProgramId, GL_LINK_STATUS, &success); if (!success) { GLchar infoLog[1024]{}; glGetProgramInfoLog(cubeProgramId, 1024, nullptr, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } // lamp shaders. GLuint lampVertexShader{}; GLuint lampFragmentShader{}; lampVertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(lampVertexShader, 1, &lampVertexShaderSource, nullptr); glCompileShader(lampVertexShader); success = 0; glGetShaderiv(lampVertexShader, GL_COMPILE_STATUS, &success); if (!success) { GLchar infoLog[1024]{}; glGetShaderInfoLog(lampVertexShader, 1024, nullptr, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } lampFragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(lampFragmentShader, 1, &lampFragmentShaderSource, nullptr); glCompileShader(lampFragmentShader); success = 0; glGetShaderiv(lampFragmentShader, GL_COMPILE_STATUS, &success); if (!success) { GLchar infoLog[1024]{}; glGetShaderInfoLog(lampFragmentShader, 1024, nullptr, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } GLuint lampProgramId{ glCreateProgram() }; glAttachShader(lampProgramId, lampVertexShader); glAttachShader(lampProgramId, lampFragmentShader); glLinkProgram(lampProgramId); success = 0; glGetProgramiv(lampProgramId, GL_LINK_STATUS, &success); if (!success) { GLchar infoLog[1024]{}; glGetProgramInfoLog(lampProgramId, 1024, nullptr, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ const float vertices[]{ // positions // normals // texture coords -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f }; // positions all containers const glm::vec3 cubePositions[]{ glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3(2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3(1.3f, -2.0f, -2.5f), glm::vec3(1.5f, 2.0f, -2.5f), glm::vec3(1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f) }; // positions of the point lights const glm::vec3 pointLightPositions[]{ glm::vec3(0.7f, 0.2f, 2.0f), glm::vec3(2.3f, -3.3f, -4.0f), glm::vec3(-4.0f, 2.0f, -12.0f), glm::vec3(0.0f, 0.0f, -3.0f) }; GLuint VBO{}; GLuint cubeVAO{}; glGenVertexArrays(1, &cubeVAO); glGenBuffers(1, &VBO); glBindVertexArray(cubeVAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); GLint offset{ 0 }; glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), reinterpret_cast<void *>(offset)); glEnableVertexAttribArray(0); offset = 3 * sizeof(float); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), reinterpret_cast<void *>(offset)); glEnableVertexAttribArray(1); offset = 6 * sizeof(float); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), reinterpret_cast<void *>(offset)); glEnableVertexAttribArray(2); GLuint lampVAO{}; glGenVertexArrays(1, &lampVAO); glBindVertexArray(lampVAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); offset = 0; glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), reinterpret_cast<void *>(offset)); glEnableVertexAttribArray(0); GLuint textureID{}; glGenTextures(1, &textureID); int width{}, height{}, nrComponents{}; unsigned char *data{ stbi_load("C:\\Users\\shihua\\source\\repos\\opengl_demo\\lightcaster-flashlight\\lightcaster-flashlight\\image\\container2.png", &width, &height, &nrComponents, 0) }; if (data) { GLenum format{}; if (nrComponents == 1) format = GL_RED; else if (nrComponents == 3) format = GL_RGB; else if (nrComponents == 4) format = GL_RGBA; glBindTexture(GL_TEXTURE_2D, textureID); glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); // set texture wrapper. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filter. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(data); } else { std::cerr << "the path of image is wrong." << std::endl; stbi_image_free(data); } data = nullptr; GLuint textureID2{}; glGenTextures(1, &textureID2); width = 0; height = 0; nrComponents = 0; data = stbi_load("C:\\Users\\shihua\\source\\repos\\opengl_demo\\lightcaster-flashlight\\lightcaster-flashlight\\image\\container2_specular.png", &width, &height, &nrComponents, 0); if (data) { GLenum format{}; if (nrComponents == 1) format = GL_RED; else if (nrComponents == 3) format = GL_RGB; else if (nrComponents == 4) format = GL_RGBA; glBindTexture(GL_TEXTURE_2D, textureID2); glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); // set texture wrapper. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filter. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(data); } else { std::cerr << "the path of image is wrong." << std::endl; stbi_image_free(data); } data = nullptr; glUseProgram(cubeProgramId); GLint texture1Id{ glGetUniformLocation(cubeProgramId, "material.diffuse_") }; glUniform1i(texture1Id, 0); GLint texture2Id{ glGetUniformLocation(cubeProgramId, "material.specular_") }; glUniform1i(texture2Id, 1); while (!glfwWindowShouldClose(window)) { // per-frame time logic float currentFrame = glfwGetTime(); delta_time = currentFrame - last_frame; last_frame = currentFrame; glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // input // ----- processInput(window); glUseProgram(cubeProgramId); // bind textures to specify uniform. glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, textureID); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, textureID2); GLint viewPosLoc{ glGetUniformLocation(cubeProgramId, "cameraPos") }; glUniform3fv(viewPosLoc, 1, &cameraPos[0]); // directional light GLint dirLightDirectionLoc{ glGetUniformLocation(cubeProgramId, "dirLight.direction_") }; glUniform3f(dirLightDirectionLoc, -0.2f, -1.0f, -0.3f); GLint dirLightAmbientLoc{ glGetUniformLocation(cubeProgramId, "dirLight.ambient_") }; glUniform3f(dirLightAmbientLoc, 0.05f, 0.05f, 0.05f); GLint dirLightDiffuseLoc{ glGetUniformLocation(cubeProgramId, "dirLight.diffuse_") }; glUniform3f(dirLightDiffuseLoc, 0.4f, 0.4f, 0.4f); GLint dirLightSpecularLoc{ glGetUniformLocation(cubeProgramId, "dirLight.specular_") }; glUniform3f(dirLightSpecularLoc, 0.5f, 0.5f, 0.5f); // point light 1 glUniform3fv(glGetUniformLocation(cubeProgramId, "pointLights[0].position_"), 1, &pointLightPositions[0][0]); glUniform3f(glGetUniformLocation(cubeProgramId, "pointLights[0].ambient_"), 0.05f, 0.05f, 0.05f); glUniform3f(glGetUniformLocation(cubeProgramId, "pointLights[0].diffuse_"), 0.8f, 0.8f, 0.8f); glUniform3f(glGetUniformLocation(cubeProgramId, "pointLights[0].specular_"), 1.0f, 1.0f, 1.0f); glUniform1f(glGetUniformLocation(cubeProgramId, "pointLights[0].constant_"), 1.0f); glUniform1f(glGetUniformLocation(cubeProgramId, "pointLights[0].linear_"), 0.09f); glUniform1f(glGetUniformLocation(cubeProgramId, "pointLights[0].quadratic_"), 0.032f); // point light 2 glUniform3fv(glGetUniformLocation(cubeProgramId, "pointLights[1].position_"), 1, &pointLightPositions[1][0]); glUniform3f(glGetUniformLocation(cubeProgramId, "pointLights[1].ambient_"), 0.05f, 0.05f, 0.05f); glUniform3f(glGetUniformLocation(cubeProgramId, "pointLights[1].diffuse_"), 0.8f, 0.8f, 0.8f); glUniform3f(glGetUniformLocation(cubeProgramId, "pointLights[1].specular_"), 1.0f, 1.0f, 1.0f); glUniform1f(glGetUniformLocation(cubeProgramId, "pointLights[1].constant_"), 1.0f); glUniform1f(glGetUniformLocation(cubeProgramId, "pointLights[1].linear_"), 0.09f); glUniform1f(glGetUniformLocation(cubeProgramId, "pointLights[1].quadratic_"), 0.032); // point light 3 glUniform3fv(glGetUniformLocation(cubeProgramId, "pointLights[2].position_"), 1, &pointLightPositions[2][0]); glUniform3f(glGetUniformLocation(cubeProgramId, "pointLights[2].ambient_"), 0.05f, 0.05f, 0.05f); glUniform3f(glGetUniformLocation(cubeProgramId, "pointLights[2].diffuse_"), 0.8f, 0.8f, 0.8f); glUniform3f(glGetUniformLocation(cubeProgramId, "pointLights[2].specular_"), 1.0f, 1.0f, 1.0f); glUniform1f(glGetUniformLocation(cubeProgramId, "pointLights[2].constant_"), 1.0f); glUniform1f(glGetUniformLocation(cubeProgramId, "pointLights[2].linear_"), 0.09f); glUniform1f(glGetUniformLocation(cubeProgramId, "pointLights[2].quadratic_"), 0.032f); // point light 4 glUniform3fv(glGetUniformLocation(cubeProgramId, "pointLights[3].position_"), 1, &pointLightPositions[1][0]); glUniform3f(glGetUniformLocation(cubeProgramId, "pointLights[3].ambient_"), 0.05f, 0.05f, 0.05f); glUniform3f(glGetUniformLocation(cubeProgramId, "pointLights[3].diffuse_"), 0.8f, 0.8f, 0.8f); glUniform3f(glGetUniformLocation(cubeProgramId, "pointLights[3].specular_"), 1.0f, 1.0f, 1.0f); glUniform1f(glGetUniformLocation(cubeProgramId, "pointLights[3].constant_"), 1.0f); glUniform1f(glGetUniformLocation(cubeProgramId, "pointLights[3].linear_"), 0.09f); glUniform1f(glGetUniformLocation(cubeProgramId, "pointLights[3].quadratic_"), 0.32f); // spotLight glUniform3fv(glGetUniformLocation(cubeProgramId, "spotLight.position_"), 1, &cameraPos[0]); glUniform3fv(glGetUniformLocation(cubeProgramId, "spotLight.direction_"), 1, &cameraFront[0]); glUniform3f(glGetUniformLocation(cubeProgramId, "spotLight.ambient_"), 0.0f, 0.0f, 0.0f); glUniform3f(glGetUniformLocation(cubeProgramId, "spotLight.diffuse_"), 1.0f, 1.0f, 1.0f); glUniform3f(glGetUniformLocation(cubeProgramId, "spotLight.specular_"), 1.0f, 1.0f, 1.0f); glUniform1f(glGetUniformLocation(cubeProgramId, "spotLight.constant_"), 1.0f); glUniform1f(glGetUniformLocation(cubeProgramId, "spotLight.linear_"), 0.09f); glUniform1f(glGetUniformLocation(cubeProgramId, "spotLight.quadratic_"), 0.032f); glUniform1f(glGetUniformLocation(cubeProgramId, "spotLight.cutoff_"), std::cos(glm::radians(12.5f))); glUniform1f(glGetUniformLocation(cubeProgramId, "spotLight.outer_cutoff_"), std::cos(glm::radians(15.0f))); GLint materialShininessLoc{ glGetUniformLocation(cubeProgramId, "material.shininess_") }; glUniform1f(materialShininessLoc, 32.0f); // view/projection transformations glm::mat4 projection{ glm::perspective(glm::radians(field_of_view), static_cast<float>(WIDTH) / static_cast<float>(HEIGHT), 0.1f, 100.0f) }; glUniformMatrix4fv(glGetUniformLocation(cubeProgramId, "projection"), 1, GL_FALSE, &projection[0][0]); // camera/view transformation glm::mat4 view{ 1.0f }; // make sure to initialize matrix to identity matrix first view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp); glUniformMatrix4fv(glGetUniformLocation(cubeProgramId, "view"), 1, GL_FALSE, &view[0][0]); // model glm::mat4 model{ 1.0f }; glUniformMatrix4fv(glGetUniformLocation(cubeProgramId, "model"), 1, GL_FALSE, &model[0][0]); // render containers glBindVertexArray(cubeVAO); for (unsigned int i = 0; i < 10; i++) { // calculate the model matrix for each object and pass it to shader before drawing glm::mat4 model{ 1.0f }; model = glm::translate(model, cubePositions[i]); float angle{ 20.0f * i }; model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); glUniformMatrix4fv(glGetUniformLocation(cubeProgramId, "model"), 1, GL_FALSE, &model[0][0]); glDrawArrays(GL_TRIANGLES, 0, 36); } // lamp glUseProgram(lampProgramId); glUniformMatrix4fv(glGetUniformLocation(lampProgramId, "projection"), 1, GL_FALSE, &projection[0][0]); glUniformMatrix4fv(glGetUniformLocation(lampProgramId, "view"), 1, GL_FALSE, &view[0][0]); // we now draw as many light bulbs as we have point lights. glBindVertexArray(lampVAO); for (std::size_t i = 0; i < 4; ++i) { model = glm::mat4{ 1.0f }; model = glm::translate(model, pointLightPositions[i]); model = glm::scale(model, glm::vec3(0.2f)); // Make it a smaller cube glUniformMatrix4fv(glGetUniformLocation(lampProgramId, "model"), 1, GL_FALSE, &model[0][0]); glDrawArrays(GL_TRIANGLES, 0, 36); } // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ glDeleteVertexArrays(1, &cubeVAO); glDeleteVertexArrays(1, &lampVAO); glDeleteBuffers(1, &VBO); // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return 0; }<file_sep>/cubemap_reflection/cubemap_reflection/main.cpp #define GLM_FORCE_CXX14 #define GLM_FORCE_INTRINSICS #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glad/glad.h> #include <GLFW/glfw3.h> #include <vector> #include <atomic> #include <iostream> #include "shader.hpp" #include "stb_image/stb_image.h" static const int WIDTH{ 1280 }; static const int HEIGHT{ 720 }; // lighting. static const glm::vec3 light_pos{ 1.2f, 1.0f, 2.0f }; // camera static glm::vec3 camera_pos{ 0.0f, 0.0f, 3.0f }; static glm::vec3 camera_front{}; static glm::vec3 camera_up{ 0.0f, 1.0f, 0.0f }; static glm::vec3 camera_right{}; static glm::vec3 world_up = camera_up; static float delta_time{}; static float last_frame{}; //mouse and scroll static float field_of_view{ 45.0f }; static std::atomic<bool> first_click{ true }; static float lastX{ WIDTH / 2.f }; static float lastY{ HEIGHT / 2.f }; static float pitch{ 0.0f }; static float yaw{ -90.f }; static float speed{ 2.5f }; static float sensitivity{ 0.05f }; static void update_camera_vectors() { // Calculate the new Front vector glm::vec3 front{}; front.x = std::cos(glm::radians(yaw)) * std::cos(glm::radians(pitch)); front.y = std::sin(glm::radians(pitch)); front.z = std::sin(glm::radians(yaw)) * std::cos(glm::radians(pitch)); camera_front = glm::normalize(front); // Also re-calculate the Right and Up vector camera_right = glm::normalize(glm::cross(camera_front, world_up)); // Normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement. camera_up = glm::normalize(glm::cross(camera_right, camera_front)); } // process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly // --------------------------------------------------------------------------------------------------------- static void process_input(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); float camera_speed{ speed * delta_time }; if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { camera_pos += (camera_front * camera_speed); } if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { camera_pos -= camera_speed * camera_front; } if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { camera_pos -= camera_right * camera_speed; } if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) { camera_pos += camera_right * camera_speed; } } // glfw: whenever the window size changed (by OS or user resize) this callback function executes // --------------------------------------------------------------------------------------------- static void framebuffer_size_callback(GLFWwindow *window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); } // glfw: whenever the mouse moves, this callback is called // ------------------------------------------------------- static void mouse_callback(GLFWwindow *window, double xpos, double ypos) { if (first_click.load()) { lastX = xpos; lastY = ypos; first_click.store(false); } float xoffset = xpos - lastX; float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top lastX = xpos; lastY = ypos; xoffset *= sensitivity; yoffset *= sensitivity; yaw += xoffset; pitch += yoffset; // make sure that when pitch is out of bounds, screen doesn't get flipped if (pitch > 89.0f) pitch = 89.0f; if (pitch < -89.0f) pitch = -89.0f; update_camera_vectors(); } // glfw: whenever the mouse scroll wheel scrolls, this callback is called // ---------------------------------------------------------------------- static void scroll_callback(GLFWwindow *window, double xoffset, double yoffset) { if (field_of_view >= 1.0f && field_of_view <= 45.0f) { field_of_view -= yoffset; } if (field_of_view <= 1.f) { field_of_view = 1.0f; } if (field_of_view >= 45.0f) { field_of_view = 45.0f; } } static GLuint load_texture(const char * path) { GLuint texture_id{}; glGenTextures(1, &texture_id); int width{}, height{}, nrComponents{}; unsigned char *data{ stbi_load(path, &width, &height, &nrComponents, 0) }; if (data) { GLenum format{}; if (nrComponents == 1) format = GL_RED; else if (nrComponents == 3) format = GL_RGB; else if (nrComponents == 4) format = GL_RGBA; glBindTexture(GL_TEXTURE_2D, texture_id); glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(data); } else { std::cout << __FUNCTION__ << " " << __LINE__ << " " << "Texture failed to load at path : " << path << std::endl; stbi_image_free(data); } data = nullptr; return texture_id; } // loads a cubemap texture from 6 individual texture faces // order: // +X (right) // -X (left) // +Y (top) // -Y (bottom) // +Z (front) // -Z (back) // ------------------------------------------------------- static GLuint load_cubemap(const std::vector<std::string>& faces) { GLuint texture_id{}; glGenTextures(1, &texture_id); glBindTexture(GL_TEXTURE_CUBE_MAP, texture_id); int width{}, height{}, nrChannels{}; for (std::size_t index = 0; index < faces.size(); ++index) { unsigned char *data{ stbi_load(faces[index].c_str(), &width, &height, &nrChannels, 0) }; if (data) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + index, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); stbi_image_free(data); } else { std::cout << "Cubemap texture failed to load at path: " << faces[index] << std::endl; stbi_image_free(data); } } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); return texture_id; } int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // glfw window creation // -------------------- GLFWwindow *window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); if (window == nullptr) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // tell GLFW to capture our mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader(reinterpret_cast<GLADloadproc>(glfwGetProcAddress))) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // update camera parameters. update_camera_vectors(); // configure global opengl state glEnable(GL_DEPTH_TEST); GLuint vertex_shader_id{ shader::create("C:\\Users\\shihua\\source\\repos\\opengl_demo\\cubemap_reflection\\cubemap_reflection\\glsl\\vertex_shader.glsl", shader_type::vertex_shader) }; GLuint fragment_shader_id{ shader::create("C:\\Users\\shihua\\source\\repos\\opengl_demo\\cubemap_reflection\\cubemap_reflection\\glsl\\fragment_shader.glsl", shader_type::fragment_shader) }; GLuint program_id{ glCreateProgram() }; glAttachShader(program_id, vertex_shader_id); glAttachShader(program_id, fragment_shader_id); glLinkProgram(program_id); glDeleteShader(vertex_shader_id); glDeleteShader(fragment_shader_id); shader::checkout_shader_state(program_id, shader_type::program); GLuint skybox_vertex_shader_id{ shader::create("C:\\Users\\shihua\\source\\repos\\opengl_demo\\cubemap_reflection\\cubemap_reflection\\glsl\\skybox_vertex_shader.glsl", shader_type::vertex_shader) }; GLuint skybox_fragment_shader_id{ shader::create("C:\\Users\\shihua\\source\\repos\\opengl_demo\\cubemap_reflection\\cubemap_reflection\\glsl\\skybox_fragment_shader.glsl", shader_type::fragment_shader) }; GLuint skybox_program_id{ glCreateProgram() }; glAttachShader(skybox_program_id, skybox_vertex_shader_id); glAttachShader(skybox_program_id, skybox_fragment_shader_id); glLinkProgram(skybox_program_id); glDeleteShader(skybox_vertex_shader_id); glDeleteShader(skybox_fragment_shader_id); shader::checkout_shader_state(skybox_program_id, shader_type::program); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ const float cube_vertices[]{ // positions // normals -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f }; const float skybox_vertices[]{ // positions -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f }; GLuint cube_VAO{}; GLuint cube_VBO{}; glGenVertexArrays(1, &cube_VAO); glGenBuffers(1, &cube_VBO); glBindVertexArray(cube_VAO); glBindBuffer(GL_ARRAY_BUFFER, cube_VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(cube_vertices), cube_vertices, GL_STATIC_DRAW); std::size_t offset{ 0 }; glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), reinterpret_cast<void*>(offset)); offset = 3 * sizeof(float); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), reinterpret_cast<void*>(offset)); // notice that. glBindVertexArray(0); GLuint skybox_VAO{}; GLuint skybox_VBO{}; glGenVertexArrays(1, &skybox_VAO); glGenBuffers(1, &skybox_VBO); glBindVertexArray(skybox_VAO); glBindBuffer(GL_ARRAY_BUFFER, skybox_VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(skybox_vertices), skybox_vertices, GL_STATIC_DRAW); offset = 0; glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), reinterpret_cast<void*>(offset)); // notice that glBindVertexArray(0); std::vector<std::string> skybox_textures { "C:\\Users\\shihua\\source\\repos\\opengl_demo\\cubemap\\cubemap\\image\\skybox\\right.jpg", "C:\\Users\\shihua\\source\\repos\\opengl_demo\\cubemap\\cubemap\\image\\skybox\\left.jpg", "C:\\Users\\shihua\\source\\repos\\opengl_demo\\cubemap\\cubemap\\image\\skybox\\top.jpg", "C:\\Users\\shihua\\source\\repos\\opengl_demo\\cubemap\\cubemap\\image\\skybox\\bottom.jpg", "C:\\Users\\shihua\\source\\repos\\opengl_demo\\cubemap\\cubemap\\image\\skybox\\front.jpg", "C:\\Users\\shihua\\source\\repos\\opengl_demo\\cubemap\\cubemap\\image\\skybox\\back.jpg" }; GLuint skybox_texture_id{ load_cubemap(skybox_textures) }; glUseProgram(program_id); shader::set_int(program_id, "skybox", 0); glUseProgram(skybox_program_id); shader::set_int(skybox_program_id, "skybox", 0); while (!glfwWindowShouldClose(window)) { double current_time{ glfwGetTime() }; delta_time = current_time - last_frame; last_frame = current_time; process_input(window); glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // draw scene as normal glUseProgram(program_id); glm::mat4 model{ 1.0f }; glm::mat4 view{ glm::lookAt(camera_pos, camera_pos + camera_front, camera_up) }; glm::mat4 projection{ glm::perspective(glm::radians(field_of_view), WIDTH * 1.0f / HEIGHT * 1.0f, 0.1f, 100.0f) }; shader::set_mat4(program_id, "model", model); shader::set_mat4(program_id, "view", view); shader::set_mat4(program_id, "projection", projection); shader::set_vec3(program_id, "camera_position", camera_pos); //draw cube. glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP, skybox_texture_id); glBindVertexArray(cube_VAO); glDrawArrays(GL_TRIANGLES, 0, 36); //restore glBindVertexArray(cube_VAO); // draw skybox as last glDepthFunc(GL_LEQUAL); // change depth function so depth test passes when values are equal to depth buffer's content glUseProgram(skybox_program_id); view = glm::mat4{ glm::mat3{glm::lookAt(camera_pos, camera_pos + camera_front, camera_up)} }; shader::set_mat4(skybox_program_id, "view", view); shader::set_mat4(skybox_program_id, "projection", projection); glBindVertexArray(skybox_VAO); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP, skybox_texture_id); glDrawArrays(GL_TRIANGLES, 0, 36); //restore glBindVertexArray(0); glDepthFunc(GL_LESS); // set depth function back to default // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glDeleteVertexArrays(1, &cube_VAO); glDeleteVertexArrays(1, &skybox_VAO); glDeleteBuffers(1, &cube_VBO); glDeleteBuffers(1, &cube_VBO); glfwTerminate(); return 0; }<file_sep>/hello_triangle/main.cpp #include <iostream> #include <glad/glad.h> #include <GLFW/glfw3.h> #include "stb_image/stb_image.h" static constexpr int WIDTH{ 800 }; static constexpr int HEIGHT{ 600 }; static constexpr const char* vertexShaderSource { "#version 330 core\n" "layout (location = 0) in vec3 aPos;\n" "layout (location = 1) in vec3 aColor;\n" "layout (location = 2) in vec2 aTexCoord;\n" "out vec3 ourColor;\n" "out vec2 texCoord;\n" "void main()\n" "{\n" " gl_Position = vec4(aPos, 1.0);\n" " ourColor = aColor;\n" " texCoord = vec2(aTexCoord.x, aTexCoord.y);\n" "}" }; static constexpr const char* fragmentShaderSource { "#version 330 core\n" "out vec4 FragColor;\n" "in vec3 ourColor;\n" "in vec2 texCoord;\n" "uniform sampler2D texture1;\n" "void main()\n" "{\n" " FragColor = texture(texture1, texCoord);\n" "}" }; static void processInput(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); } static void framebuffer_size_callback(GLFWwindow* window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); } int main() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // glfw window creation // -------------------- GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); if (window == nullptr) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); // glad: load all OpenGL function pointers if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // build and compile our shader program // ------------------------------------ // vertex shader int vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexShaderSource, nullptr); glCompileShader(vertexShader); // check for shader compile errors int success; char infoLog[512]; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vertexShader, 512, nullptr, infoLog); std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl; } // fragment shader int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentShaderSource, nullptr); glCompileShader(fragmentShader); // check for shader compile errors glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fragmentShader, 512, nullptr, infoLog); std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl; } // link shaders int shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); // check for linking errors glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog); std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl; } // after linking program, you can delete shaders. glDeleteShader(vertexShader); glDeleteShader(fragmentShader); const float vertices[]{ // positions // colors // texture coords 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top right 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom right -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom left -0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f // top left }; constexpr GLuint indices[]{ 0, 1, 3, // first triangle 1, 2, 3 // second triangle }; GLuint VAO{}; // vertex array object. GLuint VBO{}; // vertex buffer object. GLuint EBO{}; // element buffer object. glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); // tell shader how to parse vertices. // position attribute GLint offset{}; glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), reinterpret_cast<void*>(offset)); glEnableVertexAttribArray(0); // color attribute offset = 3 * sizeof(float); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), reinterpret_cast<void*>(offset)); glEnableVertexAttribArray(1); // texture coord attribute offset = 6 * sizeof(float); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), reinterpret_cast<void*>(offset)); glEnableVertexAttribArray(2); // load and create a texture GLuint texture{}; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); // all upcoming GL_TEXTURE_2D operations now have effect on this texture object // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // load image, create texture and generate mipmaps int width, height, nrChannels; unsigned char *data{ stbi_load("/home/shihua/projects/learn_opengl/hello_triangle/image/container.jpg", &width, &height, &nrChannels, 0) }; if (data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); // render loop // ----------- while (!glfwWindowShouldClose(window)) { // input // ----- processInput(window); // render // ------ glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // bind Texture // glBindTexture(GL_TEXTURE_2D, texture); // render container glUseProgram(shaderProgram); glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) glfwSwapBuffers(window); glfwPollEvents(); } // optional: de-allocate all resources once they've outlived their purpose: glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &EBO); // glfw: terminate, clearing all previously allocated GLFW resources. glfwTerminate(); return 0; }<file_sep>/exploding_object/exploding_object/shader.hpp #ifndef __SHADER_H__ #define __SHADER_H__ #include <glad/glad.h> #include <glm/glm.hpp> #include <iostream> #include <sstream> #include <fstream> #include <cassert> enum class shader_type { vertex_shader, geometry_shader, fragment_shader, program }; class shader final { public: shader() = default; shader(const shader&) = delete; shader& operator=(const shader&) = delete; static GLuint create(const std::basic_string<char>& glsl_file, shader_type type) { assert(!glsl_file.empty()); std::basic_ifstream<char> file_reader{ glsl_file }; assert(file_reader.is_open()); std::basic_ostringstream<char> file_buffer_reader{}; std::basic_filebuf<char>* file_buffer_ptr = file_reader.rdbuf(); // read data which is in file. file_buffer_reader << file_buffer_ptr; GLuint shader_id{}; if (type == shader_type::vertex_shader) { shader_id = glCreateShader(GL_VERTEX_SHADER); } if (type == shader_type::fragment_shader) { shader_id = glCreateShader(GL_FRAGMENT_SHADER); } if (type == shader_type::geometry_shader) { shader_id = glCreateShader(GL_GEOMETRY_SHADER); } std::basic_string<char> shader_source{ file_buffer_reader.str() }; const char* c_shader_source_str{ shader_source.c_str() }; glShaderSource(shader_id, 1, &c_shader_source_str, nullptr); glCompileShader(shader_id); if (!shader::checkout_shader_state(shader_id, type)) { return 0; } return shader_id; } static void set_bool(GLuint id, const std::string &name, bool value) noexcept { glUniform1i(glGetUniformLocation(id, name.c_str()), (int)value); } static void set_int(GLuint id, const std::string &name, int value) noexcept { glUniform1i(glGetUniformLocation(id, name.c_str()), value); } static void set_float(GLuint id, const std::string &name, float value) noexcept { glUniform1f(glGetUniformLocation(id, name.c_str()), value); } static void set_vec2(GLuint id, const std::string &name, const glm::vec2 &value) noexcept { glUniform2fv(glGetUniformLocation(id, name.c_str()), 1, &value[0]); } static void set_vec2(GLuint id, const std::string &name, float x, float y) noexcept { glUniform2f(glGetUniformLocation(id, name.c_str()), x, y); } static void set_vec3(GLuint id, const std::string &name, const glm::vec3 &value) noexcept { glUniform3fv(glGetUniformLocation(id, name.c_str()), 1, &value[0]); } static void set_vec3(GLuint id, const std::string &name, float x, float y, float z) noexcept { glUniform3f(glGetUniformLocation(id, name.c_str()), x, y, z); } static void set_vec4(GLuint id, const std::string &name, const glm::vec4 &value) noexcept { glUniform4fv(glGetUniformLocation(id, name.c_str()), 1, &value[0]); } static void set_vec4(GLuint id, const std::string &name, float x, float y, float z, float w)noexcept { glUniform4f(glGetUniformLocation(id, name.c_str()), x, y, z, w); } static void set_mat2(GLuint id, const std::string &name, const glm::mat2 &mat) noexcept { glUniformMatrix2fv(glGetUniformLocation(id, name.c_str()), 1, GL_FALSE, &mat[0][0]); } static void set_mat3(GLuint id, const std::string &name, const glm::mat3 &mat) noexcept { glUniformMatrix3fv(glGetUniformLocation(id, name.c_str()), 1, GL_FALSE, &mat[0][0]); } static void set_mat4(GLuint id, const std::basic_string<char> &name, const glm::mat4 &mat)noexcept { glUniformMatrix4fv(glGetUniformLocation(id, name.c_str()), 1, GL_FALSE, &mat[0][0]); } static bool checkout_shader_state(GLuint id, shader_type type) { GLint success{}; GLchar error_log[1024]{}; if (type == shader_type::vertex_shader || type == shader_type::fragment_shader || type == shader_type::geometry_shader) { glGetShaderiv(id, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(id, 1024, nullptr, error_log); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << "\n" << error_log << std::endl; return false; } } if (type == shader_type::program) { glGetProgramiv(id, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(id, 1024, nullptr, error_log); std::cout << "ERROR::PROGRAM_LINKING_ERROR of type: " << "\n" << error_log << std::endl; return false; } } return true; } }; #endif // !__SHADER_H__ <file_sep>/asteriods/asteriods/main.cpp #include <assimp/Importer.hpp> #include <assimp/scene.h> #include <assimp/postprocess.h> #include <assimp/texture.h> #include <assimp/mesh.h> #define GLM_FORCE_CXX14 #define GLM_FORCE_INTRINSICS #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glad/glad.h> #include <GLFW/glfw3.h> #include <atomic> #include <random> #include <iostream> #include "shader.hpp" #include "model.hpp" static constexpr const int WIDTH{ 800 }; static constexpr const int HEIGHT{ 600 }; // lighting. static const glm::vec3 light_pos{ 1.2f, 1.0f, 2.0f }; // camera static glm::vec3 camera_pos{ 0.0f, 0.0f, 3.0f }; static glm::vec3 camera_front{}; static glm::vec3 camera_up{ 0.0f, 1.0f, 0.0f }; static glm::vec3 camera_right{}; static glm::vec3 world_up = camera_up; static float delta_time{}; static float last_frame{}; //mouse and scroll static float field_of_view{ 45.0f }; static std::atomic<bool> first_click{ true }; static float lastX{ WIDTH / 2.f }; static float lastY{ HEIGHT / 2.f }; static float pitch{ 0.0f }; static float yaw{ -90.f }; static float speed{ 2.5f }; static float sensitivity{ 0.05f }; static void update_camera_vectors() { // Calculate the new Front vector glm::vec3 front{}; front.x = std::cos(glm::radians(yaw)) * std::cos(glm::radians(pitch)); front.y = std::sin(glm::radians(pitch)); front.z = std::sin(glm::radians(yaw)) * std::cos(glm::radians(pitch)); camera_front = glm::normalize(front); // Also re-calculate the Right and Up vector // Normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement. camera_right = glm::normalize(glm::cross(camera_front, world_up)); camera_up = glm::normalize(glm::cross(camera_right, camera_front)); } // process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly // --------------------------------------------------------------------------------------------------------- static void process_input(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); float camera_speed{ speed * delta_time }; if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { camera_pos += (camera_front * camera_speed); } if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { camera_pos -= camera_speed * camera_front; } if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { camera_pos -= camera_right * camera_speed; } if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) { camera_pos += camera_right * camera_speed; } } // glfw: whenever the window size changed (by OS or user resize) this callback function executes // --------------------------------------------------------------------------------------------- static void framebuffer_size_callback(GLFWwindow *window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); } // glfw: whenever the mouse moves, this callback is called // ------------------------------------------------------- static void mouse_callback(GLFWwindow *window, double xpos, double ypos) { if (first_click.load()) { lastX = xpos; lastY = ypos; first_click.store(false); } float xoffset = xpos - lastX; float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top lastX = xpos; lastY = ypos; xoffset *= sensitivity; yoffset *= sensitivity; yaw += xoffset; pitch += yoffset; // make sure that when pitch is out of bounds, screen doesn't get flipped if (pitch > 89.0f) pitch = 89.0f; if (pitch < -89.0f) pitch = -89.0f; update_camera_vectors(); } // glfw: whenever the mouse scroll wheel scrolls, this callback is called // ---------------------------------------------------------------------- static void scroll_callback(GLFWwindow *window, double xoffset, double yoffset) { if (field_of_view >= 1.0f && field_of_view <= 45.0f) { field_of_view -= yoffset; } if (field_of_view <= 1.f) { field_of_view = 1.0f; } if (field_of_view >= 45.0f) { field_of_view = 45.0f; } } int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // glfw window creation // -------------------- GLFWwindow *window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); if (window == nullptr) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // tell GLFW to capture our mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader(reinterpret_cast<GLADloadproc>(glfwGetProcAddress))) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // configure global opengl state glEnable(GL_DEPTH_TEST); GLuint asteriods_vertex_shader_id{ shader::create("C:\\Users\\y\\Documents\\Visual Studio 2017\\Projects\\opengl_demo\\asteriods\\asteriods\\glsl\\vertex_shader.glsl", shader_type::vertex_shader) }; GLuint asteriods_fragment_shader_id{ shader::create("C:\\Users\\y\\Documents\\Visual Studio 2017\\Projects\\opengl_demo\\asteriods\\asteriods\\glsl\\fragment_shader.glsl", shader_type::fragment_shader) }; GLuint asteriods_gl_program_id{ glCreateProgram() }; glAttachShader(asteriods_gl_program_id, asteriods_vertex_shader_id); glAttachShader(asteriods_gl_program_id, asteriods_fragment_shader_id); glLinkProgram(asteriods_gl_program_id); shader::checkout_shader_state(asteriods_gl_program_id, shader_type::program); GLuint planet_vertex_shader_id{ shader::create("C:\\Users\\y\\Documents\\Visual Studio 2017\\Projects\\opengl_demo\\asteriods\\asteriods\\glsl\\vertex_shader.glsl", shader_type::vertex_shader) }; GLuint planet_fragment_shader_id{ shader::create("C:\\Users\\y\\Documents\\Visual Studio 2017\\Projects\\opengl_demo\\asteriods\\asteriods\\glsl\\fragment_shader.glsl", shader_type::fragment_shader) }; GLuint planet_gl_program_id{ glCreateProgram() }; glAttachShader(planet_fragment_shader_id, planet_vertex_shader_id); glAttachShader(planet_fragment_shader_id, planet_fragment_shader_id); std::unique_ptr<model_loader> loaded_planet{ std::make_unique<model_loader>() }; loaded_planet->load_model("C:\\Users\\y\\Documents\\Visual Studio 2017\\Projects\\opengl_demo\\asteriods\\asteriods\\model_file\\planet\\planet.obj"); loaded_planet->load_vertices_data(); std::unique_ptr<model_loader> loaded_rock{ std::make_unique<model_loader>() }; loaded_rock->load_model("C:\\Users\\y\\Documents\\Visual Studio 2017\\Projects\\opengl_demo\\asteriods\\asteriods\\model_file\\planet\\rock.obj"); loaded_rock->load_vertices_data(); // generate a large list of semi-random model transformation matrices // ------------------------------------------------------------------ std::size_t amount{ 1000 }; std::unique_ptr<glm::mat4[]> model_matrices{ new glm::mat4[amount]{} }; std::random_device random_device{}; std::mt19937 generator{ random_device() }; std::uniform_int_distribution<> distribution{ 0, static_cast<long int>(glfwGetTime()) }; float radius{ 50.0 }; float offset{ 2.5f }; for (std::size_t index = 0; index < amount; ++index) { glm::mat4 model = glm::mat4(1.0f); // 1. translation: displace along circle with 'radius' in range [-offset, offset] float angle{ index * 1.0f / amount * 360.0f }; float displacement{ (distribution(generator) % (int)(2 * offset * 100)) / 100.0f - offset }; float x{ std::sin(angle) * radius + displacement }; displacement = (distribution(generator) % (int)(2 * offset * 100)) / 100.0f - offset; float y{ displacement * 0.4f }; // keep height of asteroid field smaller compared to width of x and z displacement = (distribution(generator) % (int)(2 * offset * 100)) / 100.0f - offset; float z{ std::cos(angle) * radius + displacement }; model = glm::translate(model, glm::vec3(x, y, z)); // 2. scale: Scale between 0.05 and 0.25f float scale{ static_cast<float>((distribution(generator) % 20) / 100.0f + 0.05) }; model = glm::scale(model, glm::vec3(scale)); // 3. rotation: add random rotation around a (semi)randomly picked rotation axis vector float rotAngle = (rand() % 360); model = glm::rotate(model, rotAngle, glm::vec3(0.4f, 0.6f, 0.8f)); // 4. now add to list of matrices model_matrices[index] = model; } // configure instanced array GLuint instanced_VBO{}; glGenBuffers(1, &instanced_VBO); glBindBuffer(GL_ARRAY_BUFFER, instanced_VBO); glBufferData(GL_ARRAY_BUFFER, amount * sizeof(glm::mat4), model_matrices.get(), GL_STATIC_DRAW); const auto& meshes_in_rock{ loaded_rock->get_meshes() }; auto rock_meshed_itr{ meshes_in_rock.cbegin() }; for (; rock_meshed_itr != meshes_in_rock.cend(); ++rock_meshed_itr) { std::size_t mesh_VAO{ (*rock_meshed_itr)->get_VAO() }; glBindVertexArray(mesh_VAO); glEnableVertexAttribArray(3); glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), reinterpret_cast<void*>(0)); glEnableVertexAttribArray(4); glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), reinterpret_cast<void*>(sizeof(glm::mat4))); glEnableVertexAttribArray(5); glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), reinterpret_cast<void*>(2 * sizeof(glm::mat4))); glEnableVertexAttribArray(6); glVertexAttribPointer(6, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), reinterpret_cast<void*>(3 * sizeof(glm::mat4))); glBindVertexArray(0); } while (!glfwWindowShouldClose(window)) { double current_time{ glfwGetTime() }; delta_time = current_time - last_frame; last_frame = current_time; // process keyboard events. process_input(window); glClearColor(0.5f, 0.5f, 0.5f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glm::mat4 projection{ glm::perspective(glm::radians(45.0f), (WIDTH / HEIGHT)*1.0f, 1.0f, 100.0f) }; glm::mat4 view{ 1.0f }; // make sure to initialize matrix to identity matrix first view = glm::lookAt(camera_pos, camera_pos + camera_front, camera_up); glUseProgram(asteriods_gl_program_id); shader::set_mat4(asteriods_gl_program_id, "projection", projection); shader::set_mat4(asteriods_gl_program_id, "view", view); glUseProgram(planet_gl_program_id); shader::set_mat4(planet_gl_program_id, "projection", projection); shader::set_mat4(planet_gl_program_id, "view", view); // draw planet glm::mat4 model{ 1.0f }; model = glm::translate(model, glm::vec3(0.0f, -3.0f, 0.0f)); model = glm::scale(model, glm::vec3(4.0f, 4.0f, 4.0f)); shader::set_mat4(planet_gl_program_id, "model", model); loaded_planet->draw(planet_gl_program_id); // draw asteriod glUseProgram(asteriods_gl_program_id); shader::set_int(asteriods_gl_program_id, "texture_diffuse_1", 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, loaded_planet->get_loaded_textures()[0].second.id_); std::size_t no_meshed_in_asteroid{ loaded_planet->get_loaded_textures().size() }; for (auto meshed_in_rock_itr_beg = loaded_planet->get_meshes().cbegin(); meshed_in_rock_itr_beg != loaded_planet->get_meshes().cend(); ++meshed_in_rock_itr_beg) { glBindVertexArray((*meshed_in_rock_itr_beg)->get_VAO()); glDrawElementsInstanced(GL_TRIANGLES, (*meshed_in_rock_itr_beg)->get_indices().size(), GL_UNSIGNED_INT, 0, amount); glBindVertexArray(0); } // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return 0; } <file_sep>/asteriods/asteriods/model.hpp #ifndef __MODEL_HPP__ #define __MODEL_HPP__ #include <glad/glad.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <assimp/Importer.hpp> #include <assimp/scene.h> #include <assimp/postprocess.h> #include "mesh.hpp" #include "stb_image/stb_image.h" #include <string> #include <fstream> #include <sstream> #include <iostream> #include <map> #include <vector> #include <list> #include <cassert> class model_loader final { private: std::list<std::shared_ptr<mesh>> meshes_; std::vector<std::pair<std::basic_string<char>, texture>> loaded_texture_{}; std::basic_string<char> texture_file_dir_{}; public: model_loader() = default; model_loader(const model_loader&) = delete; model_loader& operator=(const model_loader&) = delete; const std::list<std::shared_ptr<mesh>>& get_meshes()const noexcept { return (this->meshes_); } const std::vector<std::pair<std::basic_string<char>, texture>>& get_loaded_textures() { return (this->loaded_texture_); } void load_model(const std::basic_string<char>& model_file) { assert(!model_file.empty()); if (model_file.find_last_not_of('\\') == std::string::npos) { assert(false); } texture_file_dir_ = model_file.substr(0, model_file.find_last_of('\\')); Assimp::Importer importer{}; const aiScene* scene = importer.ReadFile(model_file, aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_CalcTangentSpace); if (!scene) { std::cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << std::endl; return; } // check for errors if (scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) // if is Not Zero { std::cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << std::endl; return; } // process ASSIMP's root node recursively process_node(scene->mRootNode, scene); } void load_vertices_data() { for (const auto& shared_mesh : meshes_) { shared_mesh->bind_VAO_VBO_EBO(); } } // draw model. inline void draw(GLuint program_id) { glUseProgram(program_id); for (const auto& shared_mesh : meshes_) { shared_mesh->bind_texture(program_id); } } private: // processes a node in a recursive fashion. Processes each individual mesh located at the node and repeats this process on its children nodes (if any). void process_node(aiNode *ai_node, const aiScene *ai_scene) { // process each mesh located at the current node for (std::size_t index = 0; index < ai_node->mNumMeshes; ++index) { // the node object only contains indices to index the actual objects in the scene. // the scene contains all the data, node is just to keep stuff organized (like relations between nodes). aiMesh* mesh_ptr = ai_scene->mMeshes[ai_node->mMeshes[index]]; meshes_.push_back(process_mesh(mesh_ptr, ai_scene)); } // after we've processed all of the meshes (if any) we then recursively process each of the children nodes for (std::size_t index = 0; index < ai_node->mNumChildren; ++index) { process_node(ai_node->mChildren[index], ai_scene); } } std::shared_ptr<mesh> process_mesh(const aiMesh* const ai_mesh, const aiScene* const ai_scene) { std::vector<vertex> vertices{}; std::vector<GLuint> indices{}; std::list<texture> textures{}; for (std::size_t index = 0; index < ai_mesh->mNumVertices; ++index) { vertex temp_vertex{}; glm::vec3 position{}; glm::vec3 normal{}; // positions position.x = ai_mesh->mVertices[index].x; position.y = ai_mesh->mVertices[index].y; position.z = ai_mesh->mVertices[index].z; // normals normal.x = ai_mesh->mNormals[index].x; normal.y = ai_mesh->mNormals[index].y; normal.z = ai_mesh->mNormals[index].z; temp_vertex.position_ = position; temp_vertex.normal_ = normal; if (ai_mesh->mTextureCoords[0]) // does the mesh contain texture coordinates? { glm::vec2 texcoord{}; // a vertex can contain up to 8 different texture coordinates. We thus make the assumption that we won't // use models where a vertex can have multiple texture coordinates so we always take the first set (0). texcoord.x = ai_mesh->mTextureCoords[0][index].x; texcoord.y = ai_mesh->mTextureCoords[0][index].y; temp_vertex.texcoord_ = texcoord; } else { temp_vertex.texcoord_ = glm::vec2{ 0, 0 }; } // tangent glm::vec3 tangent{}; tangent.x = ai_mesh->mTangents[index].x; tangent.y = ai_mesh->mTangents[index].y; tangent.z = ai_mesh->mTangents[index].z; temp_vertex.tangent_ = tangent; // bitangent glm::vec3 bitangent{}; bitangent.x = ai_mesh->mBitangents[index].x; bitangent.y = ai_mesh->mBitangents[index].y; bitangent.z = ai_mesh->mBitangents[index].z; temp_vertex.bitangent_ = bitangent; vertices.push_back(temp_vertex); } // now wak through each of the mesh's faces (a face is a mesh its triangle) and retrieve the corresponding vertex indices. for (std::size_t index = 0; index < ai_mesh->mNumFaces; ++index) { aiFace face{ ai_mesh->mFaces[index] }; for (std::size_t EBO_index = 0; EBO_index < face.mNumIndices; ++EBO_index) { indices.push_back(face.mIndices[EBO_index]); } } // process materials aiMaterial* material = ai_scene->mMaterials[ai_mesh->mMaterialIndex]; // 1. diffuse maps std::vector<texture> diffuse_texture{ load_material_texture(material, aiTextureType_DIFFUSE, texture_type::diffuse_type) }; textures.insert(textures.end(), diffuse_texture.begin(), diffuse_texture.end()); // 2. specular maps std::vector<texture> specular_texture{ load_material_texture(material, aiTextureType_SPECULAR, texture_type::specular_type) }; textures.insert(textures.end(), specular_texture.begin(), specular_texture.end()); // 3. normal maps std::vector<texture> normal_texture{ load_material_texture(material, aiTextureType_HEIGHT, texture_type::height_type) }; textures.insert(textures.end(), normal_texture.begin(), normal_texture.end()); // 4. height maps std::vector<texture> height_texture{ load_material_texture(material, aiTextureType_AMBIENT, texture_type::ambient_type) }; textures.insert(textures.end(), height_texture.begin(), height_texture.end()); std::shared_ptr<mesh> shared_mesh{ std::make_shared<mesh>() }; shared_mesh->add_vertices(vertices); shared_mesh->add_indices(indices); shared_mesh->add_textures(textures); return shared_mesh; } std::vector<texture> load_material_texture(aiMaterial * const ai_material, aiTextureType type, texture_type the_type) { std::vector<texture> textures{}; for (std::size_t index = 0; index < ai_material->GetTextureCount(type); ++index) { aiString texture_file_name{}; ai_material->GetTexture(type, index, &texture_file_name); // check if texture was loaded before and if so, continue to next iteration: skip loading a new texture bool skip{ false }; for (std::size_t load_texture_index = 0; load_texture_index < loaded_texture_.size(); ++load_texture_index) { if (std::strcmp(loaded_texture_[load_texture_index].first.c_str(), texture_file_name.C_Str()) == 0) { textures.push_back(loaded_texture_[load_texture_index].second); skip = true; // a texture with the same filepath has already been loaded, continue to next one. (optimization) break; } } if (!skip) { // if texture hasn't been loaded already, load it texture temp_texture{}; temp_texture.id_ = model_loader::load_texture_from_file(texture_file_name.C_Str(), texture_file_dir_); temp_texture.type_ = the_type; textures.push_back(temp_texture); loaded_texture_.emplace_back(std::basic_string<char>{texture_file_name.C_Str()}, temp_texture); // store it as texture loaded for entire model, to ensure we won't unnecesery load duplicate textures. } } return textures; } // gamma unused temporarily. static GLuint load_texture_from_file(const std::basic_string<char>& file_name, const std::basic_string<char>& file_path, bool gamma = false) { std::basic_string<char> file_path_name{ file_path + '\\' + file_name }; GLuint texture_id{}; glGenTextures(1, &texture_id); int width{}, height{}, nrComponents{}; unsigned char *data{ stbi_load(file_path_name.c_str(), &width, &height, &nrComponents, 0) }; if (data) { GLenum format{}; if (nrComponents == 1) format = GL_RED; else if (nrComponents == 3) format = GL_RGB; else if (nrComponents == 4) format = GL_RGBA; glBindTexture(GL_TEXTURE_2D, texture_id); glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(data); } else { std::cout << "Texture failed to load at path: " << file_path << std::endl; stbi_image_free(data); } return texture_id; } }; #endif // !__MODEL_HPP__ <file_sep>/geometry_shader/geometry_shader/main.cpp  #include <glad/glad.h> #include <GLFW/glfw3.h> #include <iostream> #include "shader.hpp" // settings const unsigned int SCR_WIDTH = 1280; const unsigned int SCR_HEIGHT = 720; int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X #endif //__APPLE__ // glfw window creation // -------------------- GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", nullptr, nullptr); glfwMakeContextCurrent(window); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // configure global opengl state // ----------------------------- glEnable(GL_DEPTH_TEST); GLuint vertex_shader_id{ shader::create("C:\\Users\\y\\Documents\\Visual Studio 2017\\Projects\\opengl_demo\\geometry_shader\\geometry_shader\\glsl\\vertex_shader.glsl", shader_type::vertex_shader) }; GLuint geometry_shader_id{ shader::create("C:\\Users\\y\\Documents\\Visual Studio 2017\\Projects\\opengl_demo\\geometry_shader\\geometry_shader\\glsl\\geometry_shader.glsl", shader_type::geometry_shader) }; GLuint fragment_shader_id{ shader::create("C:\\Users\\y\\Documents\\Visual Studio 2017\\Projects\\opengl_demo\\geometry_shader\\geometry_shader\\glsl\\fragment_shader.glsl", shader_type::fragment_shader) }; GLuint program_id{ glCreateProgram() }; glAttachShader(program_id, vertex_shader_id); glAttachShader(program_id, geometry_shader_id); glAttachShader(program_id, fragment_shader_id); glLinkProgram(program_id); glDeleteShader(vertex_shader_id); glDeleteShader(fragment_shader_id); glDeleteShader(geometry_shader_id); shader::checkout_shader_state(program_id, shader_type::program); const float points[]{ -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, // top-left 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, // top-right 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, // bottom-right -0.5f, -0.5f, 1.0f, 1.0f, 0.0f // bottom-left }; GLuint VAO{}; GLuint VBO{}; glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof points, points, GL_STATIC_DRAW); GLuint offset{ 0 }; glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(offset)); offset = 2 * sizeof(float); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(offset)); glBindVertexArray(0); while (!glfwWindowShouldClose(window)) { glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(program_id); glBindVertexArray(VAO); glDrawArrays(GL_POINTS, 0, 4); glfwSwapBuffers(window); glfwPollEvents(); } glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glfwTerminate(); return 0; } <file_sep>/framebuffer_primary/framebuffer_primary/main.cpp #define GLM_FORCE_CXX14 #define GLM_FORCE_INTRINSICS #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glad/glad.h> #include <GLFW/glfw3.h> #include <vector> #include <atomic> #include <iostream> #include "shader.hpp" #include "stb_image/stb_image.h" static const int WIDTH{ 800 }; static const int HEIGHT{ 600 }; // lighting. static const glm::vec3 light_pos{ 1.2f, 1.0f, 2.0f }; // camera static glm::vec3 camera_pos{ 0.0f, 0.0f, 3.0f }; static glm::vec3 camera_front{}; static glm::vec3 camera_up{ 0.0f, 1.0f, 0.0f }; static glm::vec3 camera_right{}; static glm::vec3 world_up = camera_up; static float delta_time{}; static float last_frame{}; //mouse and scroll static float field_of_view{ 45.0f }; static std::atomic<bool> first_click{ true }; static float lastX{ WIDTH / 2.f }; static float lastY{ HEIGHT / 2.f }; static float pitch{ 0.0f }; static float yaw{ -90.f }; static float speed{ 2.5f }; static float sensitivity{ 0.05f }; static void update_camera_vectors() { // Calculate the new Front vector glm::vec3 front{}; front.x = std::cos(glm::radians(yaw)) * std::cos(glm::radians(pitch)); front.y = std::sin(glm::radians(pitch)); front.z = std::sin(glm::radians(yaw)) * std::cos(glm::radians(pitch)); camera_front = glm::normalize(front); // Also re-calculate the Right and Up vector camera_right = glm::normalize(glm::cross(camera_front, world_up)); // Normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement. camera_up = glm::normalize(glm::cross(camera_right, camera_front)); } // process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly // --------------------------------------------------------------------------------------------------------- static void process_input(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); float camera_speed{ speed * delta_time }; if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { camera_pos += (camera_front * camera_speed); } if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { camera_pos -= camera_speed * camera_front; } if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { camera_pos -= camera_right * camera_speed; } if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) { camera_pos += camera_right * camera_speed; } } // glfw: whenever the window size changed (by OS or user resize) this callback function executes // --------------------------------------------------------------------------------------------- static void framebuffer_size_callback(GLFWwindow *window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); } // glfw: whenever the mouse moves, this callback is called // ------------------------------------------------------- static void mouse_callback(GLFWwindow *window, double xpos, double ypos) { if (first_click.load()) { lastX = xpos; lastY = ypos; first_click.store(false); } float xoffset = xpos - lastX; float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top lastX = xpos; lastY = ypos; xoffset *= sensitivity; yoffset *= sensitivity; yaw += xoffset; pitch += yoffset; // make sure that when pitch is out of bounds, screen doesn't get flipped if (pitch > 89.0f) pitch = 89.0f; if (pitch < -89.0f) pitch = -89.0f; update_camera_vectors(); } // glfw: whenever the mouse scroll wheel scrolls, this callback is called // ---------------------------------------------------------------------- static void scroll_callback(GLFWwindow *window, double xoffset, double yoffset) { if (field_of_view >= 1.0f && field_of_view <= 45.0f) { field_of_view -= yoffset; } if (field_of_view <= 1.f) { field_of_view = 1.0f; } if (field_of_view >= 45.0f) { field_of_view = 45.0f; } } static GLuint load_texture(const char * path) { GLuint texture_id{}; glGenTextures(1, &texture_id); int width{}, height{}, nrComponents{}; unsigned char *data{ stbi_load(path, &width, &height, &nrComponents, 0) }; if (data) { GLenum format{}; if (nrComponents == 1) format = GL_RED; else if (nrComponents == 3) format = GL_RGB; else if (nrComponents == 4) format = GL_RGBA; glBindTexture(GL_TEXTURE_2D, texture_id); glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(data); } else { std::cout << __FUNCTION__ << " " << __LINE__ << " " << "Texture failed to load at path : " << path << std::endl; stbi_image_free(data); } data = nullptr; return texture_id; } int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // glfw window creation // -------------------- GLFWwindow *window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); if (window == nullptr) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // tell GLFW to capture our mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader(reinterpret_cast<GLADloadproc>(glfwGetProcAddress))) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // update camera parameters. update_camera_vectors(); // configure global opengl state glEnable(GL_DEPTH_TEST); GLuint vertex_shader_id{ shader::create("C:\\Users\\shihua\\source\\repos\\opengl_demo\\framebuffer_primary\\framebuffer_primary\\glsl\\vertex_shader.glsl", shader_type::vertex_shader) }; GLuint fragment_shader_id{ shader::create("C:\\Users\\shihua\\source\\repos\\opengl_demo\\framebuffer_primary\\framebuffer_primary\\glsl\\fragment_shader.glsl", shader_type::fragment_shader) }; GLuint program_id{ glCreateProgram() }; glAttachShader(program_id, vertex_shader_id); glAttachShader(program_id, fragment_shader_id); glLinkProgram(program_id); glDeleteShader(vertex_shader_id); glDeleteShader(fragment_shader_id); shader::checkout_shader_state(program_id, shader_type::program); GLuint quad_vertex_shader_id{ shader::create("C:\\Users\\shihua\\source\\repos\\opengl_demo\\framebuffer_primary\\framebuffer_primary\\glsl\\quad_framebuffer_vertex_shader.glsl", shader_type::vertex_shader) }; GLuint quad_fragment_shader_id{ shader::create("C:\\Users\\shihua\\source\\repos\\opengl_demo\\framebuffer_primary\\framebuffer_primary\\glsl\\quad_framebuffer_fragment_shader.glsl", shader_type::fragment_shader) }; GLuint quad_program_id{ glCreateProgram() }; glAttachShader(quad_program_id, quad_vertex_shader_id); glAttachShader(quad_program_id, quad_fragment_shader_id); glLinkProgram(quad_program_id); glDeleteShader(quad_vertex_shader_id); glDeleteShader(quad_fragment_shader_id); shader::checkout_shader_state(quad_program_id, shader_type::program); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ const float cubes_vertices[]{ // positions // texture Coords -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f }; const float floor_vertices[]{ // positions // texture Coords 5.0f, -0.5f, 5.0f, 2.0f, 0.0f, -5.0f, -0.5f, 5.0f, 0.0f, 0.0f, -5.0f, -0.5f, -5.0f, 0.0f, 2.0f, 5.0f, -0.5f, 5.0f, 2.0f, 0.0f, -5.0f, -0.5f, -5.0f, 0.0f, 2.0f, 5.0f, -0.5f, -5.0f, 2.0f, 2.0f }; const float quad_vertices[]{ // vertex attributes for a quad that fills the entire screen in Normalized Device Coordinates. // positions // texCoords -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f }; GLuint cubes_VAO{}; GLuint cubes_VBO{}; glGenVertexArrays(1, &cubes_VAO); glGenBuffers(1, &cubes_VBO); glBindVertexArray(cubes_VAO); glBindBuffer(GL_ARRAY_BUFFER, cubes_VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(cubes_vertices), cubes_vertices, GL_STATIC_DRAW); std::size_t offset{ 0 }; glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(offset)); offset = 3 * sizeof(float); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(offset)); // notice that. glBindVertexArray(0); GLuint floor_VAO{}; GLuint floor_VBO{}; glGenVertexArrays(1, &floor_VAO); glGenBuffers(1, &floor_VBO); glBindVertexArray(floor_VAO); glBindBuffer(GL_ARRAY_BUFFER, floor_VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(floor_vertices), floor_vertices, GL_STATIC_DRAW); offset = 0; glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(offset)); offset = 3 * sizeof(float); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(offset)); // notice that glBindVertexArray(0); // transparent VAO GLuint quad_VAO{}, quad_VBO{}; glGenVertexArrays(1, &quad_VAO); glGenBuffers(1, &quad_VBO); glBindVertexArray(quad_VAO); glBindBuffer(GL_ARRAY_BUFFER, quad_VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(quad_vertices), quad_vertices, GL_STATIC_DRAW); offset = 0; glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 4 * sizeof(float), reinterpret_cast<void*>(offset)); offset = 2 * sizeof(float); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), reinterpret_cast<void*>(offset)); // notice that. glBindVertexArray(0); GLuint wall_texture_id{ load_texture("C:\\Users\\shihua\\source\\repos\\opengl_demo\\framebuffer_primary\\framebuffer_primary\\image\\container.jpg") }; GLuint floor_texture_id{ load_texture("C:\\Users\\shihua\\source\\repos\\opengl_demo\\framebuffer_primary\\framebuffer_primary\\image\\metal.png") }; glUseProgram(program_id); shader::set_int(program_id, "texture_1", 0); glUseProgram(quad_program_id); shader::set_int(quad_fragment_shader_id, "screen_texture", 0); // generate framebuffer. GLuint framebuffer_id{}; glGenFramebuffers(1, &framebuffer_id); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_id); GLuint color_texture_buffer_id{}; glGenTextures(1, &color_texture_buffer_id); glBindTexture(GL_TEXTURE_2D, color_texture_buffer_id); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, WIDTH, HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, color_texture_buffer_id, 0); GLuint render_buffer_id{}; glGenRenderbuffers(1, &render_buffer_id); glBindRenderbuffer(GL_RENDERBUFFER, render_buffer_id); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, WIDTH, HEIGHT); // use a single renderbuffer object for both a depth AND stencil buffer. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, render_buffer_id); // now actually attach it // now that we actually created the framebuffer and added all attachments we want to check if it is actually complete now if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { std::cout << "ERROR::FRAMEBUFFER:: Framebuffer is not complete!" << std::endl; } glBindFramebuffer(GL_FRAMEBUFFER, 0); // set our defined framebuffer as default. while (!glfwWindowShouldClose(window)) { double current_time{ glfwGetTime() }; delta_time = current_time - last_frame; last_frame = current_time; process_input(window); // bind to framebuffer and draw scene as we normally would to color texture glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_id); glEnable(GL_DEPTH_TEST); // enable depth testing; // disable depth testing before render screen-space quad. glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(program_id); glm::mat4 model{ 1.0f }; glm::mat4 view{ glm::lookAt(camera_pos, camera_pos + camera_front, camera_up) }; glm::mat4 projection{ glm::perspective(glm::radians(field_of_view), WIDTH * 1.0f / HEIGHT * 1.0f, 0.1f, 100.0f) }; shader::set_mat4(program_id, "view", view); shader::set_mat4(program_id, "projection", projection); // cubes glBindVertexArray(cubes_VAO); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, wall_texture_id); model = glm::translate(model, glm::vec3(-1.0f, 0.0f, -1.0f)); shader::set_mat4(program_id, "model", model); glDrawArrays(GL_TRIANGLES, 0, 36); model = glm::mat4{ 1.0f }; model = glm::translate(model, glm::vec3(2.0f, 0.0f, 0.0f)); shader::set_mat4(program_id, "model", model); glDrawArrays(GL_TRIANGLES, 0, 36); // floor glBindVertexArray(floor_VAO); glBindTexture(GL_TEXTURE_2D, floor_texture_id); shader::set_mat4(program_id, "model", model); glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); // now bind back to default framebuffer and draw a quad plane with the attached framebuffer color texture glBindFramebuffer(GL_FRAMEBUFFER, 0); glDisable(GL_DEPTH_TEST); // disable depth test so screen-space quad isn't discarded due to depth test. // clear all relevant buffers glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // set clear color to white (not really necessery actually, since we won't be able to see behind the quad anyways) glClear(GL_COLOR_BUFFER_BIT); glUseProgram(quad_program_id); glBindVertexArray(quad_VAO); glBindTexture(GL_TEXTURE_2D, color_texture_buffer_id); // use the color attachment texture as the texture of the quad plane glDrawArrays(GL_TRIANGLES, 0, 6); // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glDeleteVertexArrays(1, &cubes_VAO); glDeleteVertexArrays(1, &floor_VAO); glDeleteVertexArrays(1, &quad_VAO); glDeleteBuffers(1, &cubes_VBO); glDeleteBuffers(1, &floor_VBO); glDeleteBuffers(1, &quad_VBO); glfwTerminate(); return 0; }<file_sep>/README.md ## demos for learning OpenGL. these projects for learning opengl(glfw+glad). - if you want to run this demo, must change the address of pictures to yours. [![996.icu](https://img.shields.io/badge/link-996.icu-red.svg)](https://996.icu) [![LICENSE](https://img.shields.io/badge/license-Anti%20996-blue.svg)](https://github.com/996icu/996.ICU/blob/master/LICENSE) <file_sep>/hello_opengl/main.cpp #include <iostream> extern "C" { #include <glad/glad.h> #include <GLFW/glfw3.h> } static constexpr int WIDTH{ 800 }; static constexpr int HEIGHT{ 600 }; static void framebuffer_size_callback(GLFWwindow* window, int width, int height) { std::cout << "call back." << std::endl; glViewport(0, 0, width, height); } static void process_input(GLFWwindow* window) { if(glfwGetKey(window, GLFW_KEY_ENTER) == GLFW_PRESS) { std::cout << "you pressed ENTER!" << std::endl; glfwSetWindowShouldClose(window, true); } } int main() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); GLFWwindow* window{ glfwCreateWindow(800, 600, "Learn OpenGL", nullptr, nullptr) }; if(!window) { std::cout << "failed to create a window!" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); //glad: load all opengl functions. if(!gladLoadGLLoader(reinterpret_cast<GLADloadproc>(glfwGetProcAddress))) { std::cout << "failed to load functions!" << std::endl; return -1; } while(!glfwWindowShouldClose(window)) { process_input(window); glClearColor(0.2, 0.3, 0.3, 0); glClear(GL_COLOR_BUFFER_BIT); glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); //release resource. return 0; } <file_sep>/mesh/mesh/mesh.hpp #ifndef __BASIC_TYPE_H__ #define __BASIC_TYPE_H__ #include <glad/glad.h> // holds all OpenGL type declarations #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/vec2.hpp> #include <glm/vec3.hpp> #include <glm/vec4.hpp> #include <list> #include <string> #include <vector> #include <cstddef> enum class texture_type { ambient_type, diffuse_type, specular_type, height_type }; struct vertex { glm::vec3 position_; glm::vec3 normal_; glm::vec2 texcoord_; glm::vec3 tangent_; glm::vec3 bitangent_; }; struct texture { std::size_t id_; texture_type type_; }; class mesh final { private: std::vector<vertex> vertices_; std::vector<GLuint> indices_; std::list<texture> textures_; GLuint VAO_; GLuint VBO_; GLuint EBO_; public: mesh() = default; mesh(const mesh&) = delete; mesh& operator=(const mesh&) = delete; inline void add_vertices(const std::vector<vertex>& vertices)noexcept { this->vertices_ = vertices; } inline const std::vector<vertex>& get_vertices(const std::vector<vertex>& vertices)const noexcept { return this->vertices_; } inline void add_indices(const std::vector<GLuint>& indices)noexcept { this->indices_ = indices; } inline const std::vector<GLuint>& get_indices()const noexcept { return this->indices_; } inline void add_textures(const std::list<texture>& textures)noexcept { this->textures_ = textures; } const const std::list<texture> get_textures()const noexcept { return this->textures_; } const std::size_t& get_VAO()const noexcept { return this->VAO_; } const std::size_t& get_VBO()const noexcept { return this->VBO_; } const std::size_t& get_EBO()const noexcept { return this->EBO_; } void bind_texture(std::size_t program_id) { std::size_t number_of_textures{ this->textures_.size() }; auto texture_itr_beg{ this->textures_.cbegin() }; std::size_t diffuse_no{ 1 }; std::size_t specular_no{ 1 }; std::size_t ambient_no{ 1 }; std::size_t height_no{ 1 }; for (std::size_t index = 0; index < number_of_textures; ++index) { const texture& ref_texture = *texture_itr_beg; if (ref_texture.type_ == texture_type::ambient_type) { glUniform1i(glGetUniformLocation(program_id, ("ambient_texture_" + std::to_string(ambient_no++)).c_str()), index); } if (ref_texture.type_ == texture_type::diffuse_type) { glUniform1i(glGetUniformLocation(program_id, ("diffuse_texture_" + std::to_string(diffuse_no++)).c_str()), index); } if (ref_texture.type_ == texture_type::specular_type) { glUniform1i(glGetUniformLocation(program_id, ("specular_texture_" + std::to_string(specular_no++)).c_str()), index); } if (ref_texture.type_ == texture_type::height_type) { glUniform1i(glGetUniformLocation(program_id, ("height_texture_" + std::to_string(height_no++)).c_str()), index); } glActiveTexture(GL_TEXTURE0 + index); glBindTexture(GL_TEXTURE_2D, ref_texture.id_); ++texture_itr_beg; } // draw mesh glBindVertexArray(VAO_); glDrawElements(GL_TRIANGLES, indices_.size(), GL_UNSIGNED_INT, 0); // always good practice to set everything back to defaults once configured. glBindVertexArray(0); glActiveTexture(GL_TEXTURE0); } void bind_VAO_VBO_EBO() { glGenVertexArrays(1, &(VAO_)); glGenBuffers(1, &VBO_); glGenBuffers(1, &EBO_); glBindVertexArray(VAO_); glBindBuffer(GL_ARRAY_BUFFER, VBO_); glBufferData(GL_ARRAY_BUFFER, vertices_.size() * sizeof(vertex), &vertices_[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO_); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices_.size() * sizeof(GLuint), &indices_[0], GL_STATIC_DRAW); std::size_t offset{ 0 }; glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(vertex), reinterpret_cast<void*>(offset)); offset = offsetof(vertex, normal_); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(vertex), reinterpret_cast<void*>(offset)); offset = offsetof(vertex, texcoord_); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(vertex), reinterpret_cast<void*>(offset)); offset = offsetof(vertex, tangent_); glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(vertex), reinterpret_cast<void*>(offset)); offset = offsetof(vertex, bitangent_); glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(vertex), reinterpret_cast<void*>(offset)); //notice here: glBindVertexArray(0); } }; #endif // __BASIC_TYPE_H__ <file_sep>/lightcaster-flashlight/lightcaster-flashlight/main.cpp #define GLM_FORCE_CXX14 #define GLM_FORCE_INTRINSICS #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glad/glad.h> #include <GLFW/glfw3.h> #include <iostream> #include "stb_image/stb_image.h" static constexpr const int WIDTH{ 800 }; static constexpr const int HEIGHT{ 600 }; // lighting. static const glm::vec3 light_pos{ 1.2f, 1.0f, 2.0f }; // camera static glm::vec3 cameraPos{ 0.0f, 0.0f, 3.0f }; static glm::vec3 cameraFront{}; static glm::vec3 cameraUp{ 0.0f, 1.0f, 0.0f }; static glm::vec3 cameraRight{}; static glm::vec3 worldUp = cameraUp; static float delta_time{}; static float last_frame{}; //mouse and scroll static float field_of_view{ 45.0f }; static bool firstMouse{ true }; static float lastX{ WIDTH / 2.f }; static float lastY{ HEIGHT / 2.f }; static float pitch{ 0.0f }; static float yaw{ -90.f }; static float speed{ 2.5f }; static float sensitivity{ 0.05f }; static void updateCameraVectors() { // Calculate the new Front vector glm::vec3 front{}; front.x = std::cos(glm::radians(yaw)) * std::cos(glm::radians(pitch)); front.y = std::sin(glm::radians(pitch)); front.z = std::sin(glm::radians(yaw)) * std::cos(glm::radians(pitch)); cameraFront = glm::normalize(front); // Also re-calculate the Right and Up vector cameraRight = glm::normalize(glm::cross(cameraFront, worldUp)); // Normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement. cameraUp = glm::normalize(glm::cross(cameraRight, cameraFront)); } static constexpr const char *cubeVertexShaderSource{ "#version 330 core\n" "layout (location = 0) in vec3 aPos;\n" "layout (location = 1) in vec3 aNormal;\n" "layout (location = 2) in vec2 aTexCoords;\n" "out vec3 FragPos;\n" "out vec3 Normal;\n" "out vec2 TexCoords;\n" "uniform mat4 model;\n" "uniform mat4 view;\n" "uniform mat4 projection;\n" "void main()\n" "{\n" " FragPos = vec3(model * vec4(aPos, 1.0));\n" " TexCoords = aTexCoords;\n" // must use Normal Matrix, it can keep NU Scale right. " Normal = mat3(transpose(inverse(model))) * aNormal;\n" //transpose(inverse(model)) creatr Normal Matrix. " gl_Position = projection * view * vec4(FragPos, 1.0);\n" "}" }; static constexpr const char *cubeFragmentShaderSource{ "#version 330 core\n" "out vec4 FragColor;\n" "in vec3 Normal;\n" "in vec3 FragPos;\n" "in vec2 TexCoords;\n" "struct Material\n" "{\n" " sampler2D diffuse_;\n" //ambient color is the same with diffuse color, ususally. " sampler2D specular_;\n" " float shininess_;\n" "};\n" "struct Light\n" "{\n" // why here are camera_xxx? //we are simulating flashlight, so camera is light source. " vec3 camera_position_;\n" " vec3 camera_front_;\n" " float cutoff_;\n" " float outer_cutoff_;\n" " vec3 ambient_;\n" " vec3 diffuse_;\n" " vec3 specular_;\n" " float constant_;\n" " float linear_;\n" " float quadratic_;\n" "};\n" "uniform Material material;\n" "uniform Light light;\n" "uniform vec3 cameraPos;\n" //camera pos. "void main()\n" "{\n" // ambient " vec3 ambientVec = light.ambient_ * texture(material.diffuse_, TexCoords).rgb;\n" // diffuse " vec3 normalVec = normalize(Normal);\n" " vec3 lightDir = normalize(light.camera_position_ - FragPos);\n" " float diffuseValue = max(dot(normalVec, lightDir), 0.0);\n" " vec3 diffuseVec = light.diffuse_ * diffuseValue * texture(material.diffuse_, TexCoords).rgb; \n" // specular " vec3 viewDir = normalize(cameraPos - FragPos);\n" " vec3 reflectDir = reflect(-lightDir, normalVec);\n" " float specularValue = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess_);\n" " vec3 specularVec = light.specular_ * specularValue * texture(material.specular_, TexCoords).rgb;\n" // flashlight( soft edge ) " float thea = dot(lightDir, -light.camera_front_);\n" " float epsilon = light.cutoff_ - light.outer_cutoff_;\n" " float intensity = clamp((thea - light.outer_cutoff_) / epsilon, 0.0, 1.0);\n" " diffuseVec *= intensity;\n" " specularVec *= intensity;\n" // attenuation " float distance = length(light.camera_position_ - FragPos);\n" " float attenuation = 1.0 / (light.constant_ + light.linear_ * distance + light.quadratic_ * (distance * distance));\n" " ambientVec *= attenuation;\n" " diffuseVec *= attenuation;\n" " specularVec *= attenuation;\n" // here ambient need not attenuationValue. " vec3 finalColor = diffuseVec + specularVec + ambientVec;\n" " FragColor = vec4(finalColor, 1.0);\n" "}" }; static constexpr const char *lampVertexShaderSource{ "#version 330 core\n" "layout (location = 0) in vec3 aPos;\n" "uniform mat4 model;\n" "uniform mat4 view;\n" "uniform mat4 projection;\n" "void main()\n" "{\n" " gl_Position = projection * view * model * vec4(aPos, 1.0);\n" "}" }; static constexpr const char *lampFragmentShaderSource{ "#version 330 core\n" "out vec4 FragColor;\n" "void main()\n" "{\n" " FragColor = vec4(1.0);\n" // set alle 4 vector values to 1.0 "}" }; // process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly // --------------------------------------------------------------------------------------------------------- static void processInput(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); float camera_speed{ speed * delta_time }; if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { cameraPos += (cameraFront * camera_speed); } if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { cameraPos -= camera_speed * cameraFront; } if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { cameraPos -= cameraRight * camera_speed; } if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) cameraPos += cameraRight * camera_speed; } // glfw: whenever the window size changed (by OS or user resize) this callback function executes // --------------------------------------------------------------------------------------------- void framebuffer_size_callback(GLFWwindow *window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); } // glfw: whenever the mouse moves, this callback is called // ------------------------------------------------------- static void mouse_callback(GLFWwindow *window, double xpos, double ypos) { if (firstMouse) { lastX = xpos; lastY = ypos; firstMouse = false; } float xoffset = xpos - lastX; float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top lastX = xpos; lastY = ypos; xoffset *= sensitivity; yoffset *= sensitivity; yaw += xoffset; pitch += yoffset; // make sure that when pitch is out of bounds, screen doesn't get flipped if (pitch > 89.0f) pitch = 89.0f; if (pitch < -89.0f) pitch = -89.0f; updateCameraVectors(); } // glfw: whenever the mouse scroll wheel scrolls, this callback is called // ---------------------------------------------------------------------- static void scroll_callback(GLFWwindow *window, double xoffset, double yoffset) { if (field_of_view >= 1.0f && field_of_view <= 45.0f) { field_of_view -= yoffset; } if (field_of_view <= 1.f) { field_of_view = 1.0f; } if (field_of_view >= 45.0f) { field_of_view = 45.0f; } } int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // glfw window creation // -------------------- GLFWwindow *window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); if (window == nullptr) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // tell GLFW to capture our mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader(reinterpret_cast<GLADloadproc>(glfwGetProcAddress))) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // configure global opengl state // ----------------------------- glEnable(GL_DEPTH_TEST); // notice that: count camera front/up/right vectors. updateCameraVectors(); // cube shaders. GLuint cubeVertexShader{}; GLuint cubeFragmentShader{}; cubeVertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(cubeVertexShader, 1, &cubeVertexShaderSource, nullptr); glCompileShader(cubeVertexShader); GLint success{}; glGetShaderiv(cubeVertexShader, GL_COMPILE_STATUS, &success); if (!success) { GLchar infoLog[1024]{}; glGetShaderInfoLog(cubeVertexShader, 1024, nullptr, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } cubeFragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(cubeFragmentShader, 1, &cubeFragmentShaderSource, nullptr); glCompileShader(cubeFragmentShader); success = 0; glGetShaderiv(cubeFragmentShader, GL_COMPILE_STATUS, &success); if (!success) { GLchar infoLog[1024]{}; glGetShaderInfoLog(cubeFragmentShader, 1024, nullptr, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } GLuint cubeProgramId{ glCreateProgram() }; glAttachShader(cubeProgramId, cubeVertexShader); glAttachShader(cubeProgramId, cubeFragmentShader); glLinkProgram(cubeProgramId); success = 0; glGetProgramiv(cubeProgramId, GL_LINK_STATUS, &success); if (!success) { GLchar infoLog[1024]{}; glGetProgramInfoLog(cubeProgramId, 1024, nullptr, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } // lamp shaders. GLuint lampVertexShader{}; GLuint lampFragmentShader{}; lampVertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(lampVertexShader, 1, &lampVertexShaderSource, nullptr); glCompileShader(lampVertexShader); success = 0; glGetShaderiv(lampVertexShader, GL_COMPILE_STATUS, &success); if (!success) { GLchar infoLog[1024]{}; glGetShaderInfoLog(lampVertexShader, 1024, nullptr, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } lampFragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(lampFragmentShader, 1, &lampFragmentShaderSource, nullptr); glCompileShader(lampFragmentShader); success = 0; glGetShaderiv(lampFragmentShader, GL_COMPILE_STATUS, &success); if (!success) { GLchar infoLog[1024]{}; glGetShaderInfoLog(lampFragmentShader, 1024, nullptr, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } GLuint lampProgramId{ glCreateProgram() }; glAttachShader(lampProgramId, lampVertexShader); glAttachShader(lampProgramId, lampFragmentShader); glLinkProgram(lampProgramId); success = 0; glGetProgramiv(lampProgramId, GL_LINK_STATUS, &success); if (!success) { GLchar infoLog[1024]{}; glGetProgramInfoLog(lampProgramId, 1024, nullptr, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ const float vertices[]{ // positions // normals // texture coords -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f }; // positions all containers const glm::vec3 cubePositions[]{ glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3(2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3(1.3f, -2.0f, -2.5f), glm::vec3(1.5f, 2.0f, -2.5f), glm::vec3(1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f) }; GLuint VBO{}; GLuint cubeVAO{}; glGenVertexArrays(1, &cubeVAO); glGenBuffers(1, &VBO); glBindVertexArray(cubeVAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); GLint offset{ 0 }; glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), reinterpret_cast<void *>(offset)); glEnableVertexAttribArray(0); offset = 3 * sizeof(float); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), reinterpret_cast<void *>(offset)); glEnableVertexAttribArray(1); offset = 6 * sizeof(float); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), reinterpret_cast<void *>(offset)); glEnableVertexAttribArray(2); GLuint lampVAO{}; glGenVertexArrays(1, &lampVAO); glBindVertexArray(lampVAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); offset = 0; glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), reinterpret_cast<void *>(offset)); glEnableVertexAttribArray(0); GLuint textureID{}; glGenTextures(1, &textureID); int width{}, height{}, nrComponents{}; unsigned char *data{ stbi_load("C:\\Users\\shihua\\source\\repos\\opengl_demo\\lightcaster-flashlight\\lightcaster-flashlight\\image\\container2.png", &width, &height, &nrComponents, 0) }; if (data) { GLenum format{}; if (nrComponents == 1) format = GL_RED; else if (nrComponents == 3) format = GL_RGB; else if (nrComponents == 4) format = GL_RGBA; glBindTexture(GL_TEXTURE_2D, textureID); glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); // set texture wrapper. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filter. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(data); } else { std::cerr << "the path of image is wrong." << std::endl; stbi_image_free(data); } data = nullptr; GLuint textureID2{}; glGenTextures(1, &textureID2); width = 0; height = 0; nrComponents = 0; data = stbi_load("C:\\Users\\shihua\\source\\repos\\opengl_demo\\lightcaster-flashlight\\lightcaster-flashlight\\image\\container2_specular.png", &width, &height, &nrComponents, 0); if (data) { GLenum format{}; if (nrComponents == 1) format = GL_RED; else if (nrComponents == 3) format = GL_RGB; else if (nrComponents == 4) format = GL_RGBA; glBindTexture(GL_TEXTURE_2D, textureID2); glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); // set texture wrapper. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filter. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(data); } else { std::cerr << "the path of image is wrong." << std::endl; stbi_image_free(data); } data = nullptr; glUseProgram(cubeProgramId); GLint texture1Id{ glGetUniformLocation(cubeProgramId, "material.diffuse_") }; glUniform1i(texture1Id, 0); GLint texture2Id{ glGetUniformLocation(cubeProgramId, "material.specular_") }; glUniform1i(texture2Id, 1); while (!glfwWindowShouldClose(window)) { // per-frame time logic float currentFrame = glfwGetTime(); delta_time = currentFrame - last_frame; last_frame = currentFrame; glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // input // ----- processInput(window); glUseProgram(cubeProgramId); // bind textures to specify uniform. glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, textureID); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, textureID2); GLint viewPosLoc{ glGetUniformLocation(cubeProgramId, "cameraPos") }; glUniform3fv(viewPosLoc, 1, &cameraPos[0]); glm::vec3 lightAmbientColor{ 0.2f, 0.2f, 0.2f }; glm::vec3 lightDiffuseColor{ 0.5f, 0.5f, 0.5f }; glm::vec3 lightSpecularColor{ 1.0f, 1.0f, 1.0f }; GLint cameraPosLoc{ glGetUniformLocation(cubeProgramId, "light.camera_position_") }; glUniform3fv(cameraPosLoc, 1, &cameraPos[0]); GLint cameraDirectionLoc{ glGetUniformLocation(cubeProgramId, "light.camera_front_") }; glUniform3fv(cameraDirectionLoc, 1, &cameraFront[0]); GLint cutOffLoc{ glGetUniformLocation(cubeProgramId, "light.cutoff_") }; glUniform1f(cutOffLoc, std::cos(glm::radians(12.5f))); GLint outerCutOffLoc{ glGetUniformLocation(cubeProgramId, "light.outer_cutoff_") }; glUniform1f(outerCutOffLoc, std::cos(glm::radians(17.5f))); GLint lightAmbientLoc{ glGetUniformLocation(cubeProgramId, "light.ambient_") }; glUniform3f(lightAmbientLoc, 0.1f, 0.1f, 0.1f); GLint lightDiffuseLoc{ glGetUniformLocation(cubeProgramId, "light.diffuse_") }; glUniform3f(lightDiffuseLoc, 0.8f, 0.8f, 0.8f); GLint lightSpecularLoc{ glGetUniformLocation(cubeProgramId, "light.specular_") }; glUniform3f(lightSpecularLoc, 1.0, 1.0, 1.0); GLint lightConstantLoc{ glGetUniformLocation(cubeProgramId, "light.constant_") }; glUniform1f(lightConstantLoc, 1.0f); GLint lightLinearLoc{ glGetUniformLocation(cubeProgramId, "light.linear_") }; glUniform1f(lightLinearLoc, 0.09f); GLint lightQuadraticLoc{ glGetUniformLocation(cubeProgramId, "light.quadratic_") }; glUniform1f(lightQuadraticLoc, 0.032f); GLint materialShininessLoc{ glGetUniformLocation(cubeProgramId, "material.shininess_") }; glUniform1f(materialShininessLoc, 32.0f); // view/projection transformations glm::mat4 projection{ glm::perspective(glm::radians(field_of_view), static_cast<float>(WIDTH) / static_cast<float>(HEIGHT), 0.1f, 100.0f) }; glUniformMatrix4fv(glGetUniformLocation(cubeProgramId, "projection"), 1, GL_FALSE, &projection[0][0]); // camera/view transformation glm::mat4 view{ 1.0f }; // make sure to initialize matrix to identity matrix first view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp); glUniformMatrix4fv(glGetUniformLocation(cubeProgramId, "view"), 1, GL_FALSE, &view[0][0]); // model glm::mat4 model{ 1.0f }; glUniformMatrix4fv(glGetUniformLocation(cubeProgramId, "model"), 1, GL_FALSE, &model[0][0]); // render containers glBindVertexArray(cubeVAO); for (unsigned int i = 0; i < 10; i++) { // calculate the model matrix for each object and pass it to shader before drawing glm::mat4 model{ 1.0f }; model = glm::translate(model, cubePositions[i]); float angle{ 20.0f * i }; model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); glUniformMatrix4fv(glGetUniformLocation(cubeProgramId, "model"), 1, GL_FALSE, &model[0][0]); glDrawArrays(GL_TRIANGLES, 0, 36); } // // also draw the lamp object // glUseProgram(lampProgramId); // glUniformMatrix4fv(glGetUniformLocation(lampProgramId, "projection"), 1, GL_FALSE, &projection[0][0]); // glUniformMatrix4fv(glGetUniformLocation(lampProgramId, "view"), 1, GL_FALSE, &view[0][0]); // model = glm::mat4(1.0f); // model = glm::translate(model, light_pos); // model = glm::scale(model, glm::vec3(0.3f)); // a smaller lamp cube // glUniformMatrix4fv(glGetUniformLocation(lampProgramId, "model"), 1, GL_FALSE, &model[0][0]); // glBindVertexArray(lampVAO); // glDrawArrays(GL_TRIANGLES, 0, 36); // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ glDeleteVertexArrays(1, &cubeVAO); glDeleteVertexArrays(1, &lampVAO); glDeleteBuffers(1, &VBO); // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return 0; }<file_sep>/lightcasters-flashlight/main.cpp #define GLM_FORCE_CXX14 #define GLM_FORCE_INTRINSICS #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glad/glad.h> #include <GLFW/glfw3.h> #include <iostream> #include "stb_image/stb_image.h" static constexpr const int WIDTH{800}; static constexpr const int HEIGHT{600}; // lighting. static const glm::vec3 light_pos{1.2f, 1.0f, 2.0f}; // camera static glm::vec3 cameraPos{0.0f, 0.0f, 3.0f}; static glm::vec3 cameraFront{}; static glm::vec3 cameraUp{0.0f, 1.0f, 0.0f}; static glm::vec3 cameraRight{}; static glm::vec3 worldUp = cameraUp; static float delta_time{}; static float last_frame{}; //mouse and scroll static float field_of_view{45.0f}; static bool firstMouse{true}; static float lastX{WIDTH / 2.f}; static float lastY{HEIGHT / 2.f}; static float pitch{0.0f}; static float yaw{-90.f}; static float speed{2.5f}; static float sensitivity{0.05f}; static void updateCameraVectors() { // Calculate the new Front vector glm::vec3 front{}; front.x = std::cos(glm::radians(yaw)) * std::cos(glm::radians(pitch)); front.y = std::sin(glm::radians(pitch)); front.z = std::sin(glm::radians(yaw)) * std::cos(glm::radians(pitch)); cameraFront = glm::normalize(front); // Also re-calculate the Right and Up vector cameraRight = glm::normalize(glm::cross(cameraFront, worldUp)); // Normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement. cameraUp = glm::normalize(glm::cross(cameraRight, cameraFront)); } static constexpr const char *cubeVertexShaderSource{ "#version 330 core\n" "layout (location = 0) in vec3 aPos;\n" "layout (location = 1) in vec3 aNormal;\n" "layout (location = 2) in vec2 aTexCoords;\n" "out vec3 FragPos;\n" "out vec3 Normal;\n" "out vec2 TexCoords;\n" "uniform mat4 model;\n" "uniform mat4 view;\n" "uniform mat4 projection;\n" "void main()\n" "{\n" " FragPos = vec3(model * vec4(aPos, 1.0));\n" " TexCoords = aTexCoords;\n" // must use Normal Matrix, it can keep NU Scale right. " Normal = mat3(transpose(inverse(model))) * aNormal;\n" //transpose(inverse(model)) creatr Normal Matrix. " gl_Position = projection * view * vec4(FragPos, 1.0);\n" "}"}; static constexpr const char *cubeFragmentShaderSource{ "#version 330 core\n" "out vec4 FragColor;\n" "in vec3 Normal;\n" "in vec3 FragPos;\n" "in vec2 TexCoords;\n" "struct Material\n" "{\n" " sampler2D diffuse_;\n" //ambient color is the same with diffuse color, ususally. " sampler2D specular_;\n" " float shininess_;\n" "};\n" "struct Light\n" "{\n" // why here are camera_xxx? //we are simulating flashlight, so camera is light source. " vec3 camera_position_;\n" " vec3 camera_front_;\n" " float cutoff_;\n" " vec3 ambient_;\n" " vec3 diffuse_;\n" " vec3 specular_;\n" " float constant_;\n" " float linear_;\n" " float quadratic_;\n" "};\n" "uniform Material material;\n" "uniform Light light;\n" "uniform vec3 cameraPos;\n" //camera pos. "void main()\n" "{\n" " vec3 lightDir = normalize(light.camera_position_ - FragPos);\n" // check if lighting is inside the spotlight cone " float thea = dot(lightDir, normalize(-light.camera_front_));\n" "if(thea > light.cutoff_)\n" "{\n" // ambient " vec3 ambientVec = light.ambient_ * texture(material.diffuse_, TexCoords).rgb;\n" // diffuse " vec3 normalVec = normalize(Normal);\n" " vec3 lightDir = normalize(light.camera_position_ - FragPos);\n" " float diffuseValue = max(dot(normalVec, lightDir), 0.0);\n" " vec3 diffuseVec = light.diffuse_ * diffuseValue * texture(material.diffuse_, TexCoords).rgb; \n" // specular " vec3 viewDir = normalize(cameraPos - FragPos);\n" " vec3 reflectDir = reflect(-lightDir, normalVec);\n" " float specularValue = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess_);\n" " vec3 specularVec = light.specular_ * specularValue * texture(material.specular_, TexCoords).rgb;\n" " float distance = length(light.camera_position_ - FragPos);\n" " float attenuationValue = 1.0 / (light.constant_ + light.linear_ * distance + light.quadratic_ * (distance * distance));\n" // here ambient need not attenuationValue. " vec3 finalColor = (diffuseVec + specularVec)*attenuationValue + ambientVec;\n" " FragColor = vec4(finalColor, 1.0);\n" "}else{\n" // else, use ambient light so scene isn't completely dark outside the spotlight. " FragColor = vec4(light.ambient_ * texture(material.diffuse_, TexCoords).rgb, 1.0);\n " "}\n" "}"}; static constexpr const char *lampVertexShaderSource{ "#version 330 core\n" "layout (location = 0) in vec3 aPos;\n" "uniform mat4 model;\n" "uniform mat4 view;\n" "uniform mat4 projection;\n" "void main()\n" "{\n" " gl_Position = projection * view * model * vec4(aPos, 1.0);\n" "}"}; static constexpr const char *lampFragmentShaderSource{ "#version 330 core\n" "out vec4 FragColor;\n" "void main()\n" "{\n" " FragColor = vec4(1.0);\n" // set alle 4 vector values to 1.0 "}"}; // process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly // --------------------------------------------------------------------------------------------------------- static void processInput(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); float camera_speed{speed * delta_time}; if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { cameraPos += (cameraFront * camera_speed); } if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { cameraPos -= camera_speed * cameraFront; } if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { cameraPos -= cameraRight * camera_speed; } if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) cameraPos += cameraRight * camera_speed; } // glfw: whenever the window size changed (by OS or user resize) this callback function executes // --------------------------------------------------------------------------------------------- void framebuffer_size_callback(GLFWwindow *window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); } // glfw: whenever the mouse moves, this callback is called // ------------------------------------------------------- static void mouse_callback(GLFWwindow *window, double xpos, double ypos) { if (firstMouse) { lastX = xpos; lastY = ypos; firstMouse = false; } float xoffset = xpos - lastX; float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top lastX = xpos; lastY = ypos; xoffset *= sensitivity; yoffset *= sensitivity; yaw += xoffset; pitch += yoffset; // make sure that when pitch is out of bounds, screen doesn't get flipped if (pitch > 89.0f) pitch = 89.0f; if (pitch < -89.0f) pitch = -89.0f; updateCameraVectors(); } // glfw: whenever the mouse scroll wheel scrolls, this callback is called // ---------------------------------------------------------------------- static void scroll_callback(GLFWwindow *window, double xoffset, double yoffset) { if (field_of_view >= 1.0f && field_of_view <= 45.0f) { field_of_view -= yoffset; } if (field_of_view <= 1.f) { field_of_view = 1.0f; } if (field_of_view >= 45.0f) { field_of_view = 45.0f; } } int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // glfw window creation // -------------------- GLFWwindow *window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); if (window == nullptr) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // tell GLFW to capture our mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader(reinterpret_cast<GLADloadproc>(glfwGetProcAddress))) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // configure global opengl state // ----------------------------- glEnable(GL_DEPTH_TEST); // notice that: count camera front/up/right vectors. updateCameraVectors(); // cube shaders. GLuint cubeVertexShader{}; GLuint cubeFragmentShader{}; cubeVertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(cubeVertexShader, 1, &cubeVertexShaderSource, nullptr); glCompileShader(cubeVertexShader); GLint success{}; glGetShaderiv(cubeVertexShader, GL_COMPILE_STATUS, &success); if (!success) { GLchar infoLog[1024]{}; glGetShaderInfoLog(cubeVertexShader, 1024, nullptr, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } cubeFragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(cubeFragmentShader, 1, &cubeFragmentShaderSource, nullptr); glCompileShader(cubeFragmentShader); success = 0; glGetShaderiv(cubeFragmentShader, GL_COMPILE_STATUS, &success); if (!success) { GLchar infoLog[1024]{}; glGetShaderInfoLog(cubeFragmentShader, 1024, nullptr, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } GLuint cubeProgramId{glCreateProgram()}; glAttachShader(cubeProgramId, cubeVertexShader); glAttachShader(cubeProgramId, cubeFragmentShader); glLinkProgram(cubeProgramId); success = 0; glGetProgramiv(cubeProgramId, GL_LINK_STATUS, &success); if (!success) { GLchar infoLog[1024]{}; glGetProgramInfoLog(cubeProgramId, 1024, nullptr, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } // lamp shaders. GLuint lampVertexShader{}; GLuint lampFragmentShader{}; lampVertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(lampVertexShader, 1, &lampVertexShaderSource, nullptr); glCompileShader(lampVertexShader); success = 0; glGetShaderiv(lampVertexShader, GL_COMPILE_STATUS, &success); if (!success) { GLchar infoLog[1024]{}; glGetShaderInfoLog(lampVertexShader, 1024, nullptr, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } lampFragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(lampFragmentShader, 1, &lampFragmentShaderSource, nullptr); glCompileShader(lampFragmentShader); success = 0; glGetShaderiv(lampFragmentShader, GL_COMPILE_STATUS, &success); if (!success) { GLchar infoLog[1024]{}; glGetShaderInfoLog(lampFragmentShader, 1024, nullptr, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } GLuint lampProgramId{glCreateProgram()}; glAttachShader(lampProgramId, lampVertexShader); glAttachShader(lampProgramId, lampFragmentShader); glLinkProgram(lampProgramId); success = 0; glGetProgramiv(lampProgramId, GL_LINK_STATUS, &success); if (!success) { GLchar infoLog[1024]{}; glGetProgramInfoLog(lampProgramId, 1024, nullptr, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ const float vertices[]{ // positions // normals // texture coords -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f}; // positions all containers const glm::vec3 cubePositions[]{ glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3(2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3(1.3f, -2.0f, -2.5f), glm::vec3(1.5f, 2.0f, -2.5f), glm::vec3(1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f)}; GLuint VBO{}; GLuint cubeVAO{}; glGenVertexArrays(1, &cubeVAO); glGenBuffers(1, &VBO); glBindVertexArray(cubeVAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); GLint offset{0}; glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), reinterpret_cast<void *>(offset)); glEnableVertexAttribArray(0); offset = 3 * sizeof(float); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), reinterpret_cast<void *>(offset)); glEnableVertexAttribArray(1); offset = 6 * sizeof(float); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), reinterpret_cast<void *>(offset)); glEnableVertexAttribArray(2); GLuint lampVAO{}; glGenVertexArrays(1, &lampVAO); glBindVertexArray(lampVAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); offset = 0; glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), reinterpret_cast<void *>(offset)); glEnableVertexAttribArray(0); GLuint textureID{}; glGenTextures(1, &textureID); int width{}, height{}, nrComponents{}; unsigned char *data{stbi_load("/home/shihua/projects/learn_opengl/lightmapping/image/container2.png", &width, &height, &nrComponents, 0)}; if (data) { GLenum format{}; if (nrComponents == 1) format = GL_RED; else if (nrComponents == 3) format = GL_RGB; else if (nrComponents == 4) format = GL_RGBA; glBindTexture(GL_TEXTURE_2D, textureID); glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); // set texture wrapper. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filter. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(data); } else { std::cerr << "the path of image is wrong." << std::endl; stbi_image_free(data); } data = nullptr; GLuint textureID2{}; glGenTextures(1, &textureID2); width = 0; height = 0; nrComponents = 0; data = stbi_load("/home/shihua/projects/learn_opengl/lightmapping/image/container2_specular.png", &width, &height, &nrComponents, 0); if (data) { GLenum format{}; if (nrComponents == 1) format = GL_RED; else if (nrComponents == 3) format = GL_RGB; else if (nrComponents == 4) format = GL_RGBA; glBindTexture(GL_TEXTURE_2D, textureID2); glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); // set texture wrapper. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filter. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(data); } else { std::cerr << "the path of image is wrong." << std::endl; stbi_image_free(data); } data = nullptr; glUseProgram(cubeProgramId); GLint texture1Id{glGetUniformLocation(cubeProgramId, "material.diffuse_")}; glUniform1i(texture1Id, 0); GLint texture2Id{glGetUniformLocation(cubeProgramId, "material.specular_")}; glUniform1i(texture2Id, 1); while (!glfwWindowShouldClose(window)) { // per-frame time logic float currentFrame = glfwGetTime(); delta_time = currentFrame - last_frame; last_frame = currentFrame; glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // input // ----- processInput(window); glUseProgram(cubeProgramId); // bind textures to specify uniform. glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, textureID); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, textureID2); GLint viewPosLoc{glGetUniformLocation(cubeProgramId, "cameraPos")}; glUniform3fv(viewPosLoc, 1, &cameraPos[0]); glm::vec3 lightAmbientColor{0.2f, 0.2f, 0.2f}; glm::vec3 lightDiffuseColor{0.5f, 0.5f, 0.5f}; glm::vec3 lightSpecularColor{1.0f, 1.0f, 1.0f}; GLint cameraPosLoc{glGetUniformLocation(cubeProgramId, "light.camera_position_")}; glUniform3fv(cameraPosLoc, 1, &cameraPos[0]); GLint cameraDirectionLoc{glGetUniformLocation(cubeProgramId, "light.camera_front_")}; glUniform3fv(cameraDirectionLoc, 1, &cameraFront[0]); GLint cutOffLoc{glGetUniformLocation(cubeProgramId, "light.cutoff_")}; glUniform1f(cutOffLoc, std::cos(glm::radians(12.5f))); GLint lightAmbientLoc{glGetUniformLocation(cubeProgramId, "light.ambient_")}; glUniform3f(lightAmbientLoc, 0.1f, 0.1f, 0.1f); GLint lightDiffuseLoc{glGetUniformLocation(cubeProgramId, "light.diffuse_")}; glUniform3f(lightDiffuseLoc, 0.8f, 0.8f, 0.8f); GLint lightSpecularLoc{glGetUniformLocation(cubeProgramId, "light.specular_")}; glUniform3f(lightSpecularLoc, 1.0, 1.0, 1.0); GLint lightConstantLoc{glGetUniformLocation(cubeProgramId, "light.constant_")}; glUniform1f(lightConstantLoc, 1.0f); GLint lightLinearLoc{glGetUniformLocation(cubeProgramId, "light.linear_")}; glUniform1f(lightLinearLoc, 0.09f); GLint lightQuadraticLoc{glGetUniformLocation(cubeProgramId, "light.quadratic_")}; glUniform1f(lightQuadraticLoc, 0.032f); GLint materialShininessLoc{glGetUniformLocation(cubeProgramId, "material.shininess_")}; glUniform1f(materialShininessLoc, 32.0f); // view/projection transformations glm::mat4 projection{glm::perspective(glm::radians(field_of_view), static_cast<float>(WIDTH) / static_cast<float>(HEIGHT), 0.1f, 100.0f)}; glUniformMatrix4fv(glGetUniformLocation(cubeProgramId, "projection"), 1, GL_FALSE, &projection[0][0]); // camera/view transformation glm::mat4 view{1.0f}; // make sure to initialize matrix to identity matrix first view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp); glUniformMatrix4fv(glGetUniformLocation(cubeProgramId, "view"), 1, GL_FALSE, &view[0][0]); // model glm::mat4 model{1.0f}; glUniformMatrix4fv(glGetUniformLocation(cubeProgramId, "model"), 1, GL_FALSE, &model[0][0]); // render containers glBindVertexArray(cubeVAO); for (unsigned int i = 0; i < 10; i++) { // calculate the model matrix for each object and pass it to shader before drawing glm::mat4 model{1.0f}; model = glm::translate(model, cubePositions[i]); float angle{20.0f * i}; model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); glUniformMatrix4fv(glGetUniformLocation(cubeProgramId, "model"), 1, GL_FALSE, &model[0][0]); glDrawArrays(GL_TRIANGLES, 0, 36); } // // also draw the lamp object // glUseProgram(lampProgramId); // glUniformMatrix4fv(glGetUniformLocation(lampProgramId, "projection"), 1, GL_FALSE, &projection[0][0]); // glUniformMatrix4fv(glGetUniformLocation(lampProgramId, "view"), 1, GL_FALSE, &view[0][0]); // model = glm::mat4(1.0f); // model = glm::translate(model, light_pos); // model = glm::scale(model, glm::vec3(0.3f)); // a smaller lamp cube // glUniformMatrix4fv(glGetUniformLocation(lampProgramId, "model"), 1, GL_FALSE, &model[0][0]); // glBindVertexArray(lampVAO); // glDrawArrays(GL_TRIANGLES, 0, 36); // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ glDeleteVertexArrays(1, &cubeVAO); glDeleteVertexArrays(1, &lampVAO); glDeleteBuffers(1, &VBO); // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return 0; }<file_sep>/illumination/camera.cpp #include "camera.h" const float YAW{-90.0f}; const float PITCH{0.0f}; const float SPEED{2.5f}; const float SENSITIVITY{0.05f}; const float ZOOM{45.0f};<file_sep>/blending/blending/main.cpp #define GLM_FORCE_CXX14 #define GLM_FORCE_INTRINSICS #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glad/glad.h> #include <GLFW/glfw3.h> #include <vector> #include <atomic> #include <iostream> #include "shader.hpp" #include "stb_image/stb_image.h" static const int WIDTH{ 1280 }; static const int HEIGHT{ 720 }; // lighting. static const glm::vec3 light_pos{ 1.2f, 1.0f, 2.0f }; // camera static glm::vec3 camera_pos{ 0.0f, 0.0f, 3.0f }; static glm::vec3 camera_front{}; static glm::vec3 camera_up{ 0.0f, 1.0f, 0.0f }; static glm::vec3 camera_right{}; static glm::vec3 world_up = camera_up; static float delta_time{}; static float last_frame{}; //mouse and scroll static float field_of_view{ 45.0f }; static std::atomic<bool> first_click{ true }; static float lastX{ WIDTH / 2.f }; static float lastY{ HEIGHT / 2.f }; static float pitch{ 0.0f }; static float yaw{ -90.f }; static float speed{ 2.5f }; static float sensitivity{ 0.05f }; static void update_camera_vectors() { // Calculate the new Front vector glm::vec3 front{}; front.x = std::cos(glm::radians(yaw)) * std::cos(glm::radians(pitch)); front.y = std::sin(glm::radians(pitch)); front.z = std::sin(glm::radians(yaw)) * std::cos(glm::radians(pitch)); camera_front = glm::normalize(front); // Also re-calculate the Right and Up vector camera_right = glm::normalize(glm::cross(camera_front, world_up)); // Normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement. camera_up = glm::normalize(glm::cross(camera_right, camera_front)); } // process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly // --------------------------------------------------------------------------------------------------------- static void process_input(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); float camera_speed{ speed * delta_time }; if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { camera_pos += (camera_front * camera_speed); } if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { camera_pos -= camera_speed * camera_front; } if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { camera_pos -= camera_right * camera_speed; } if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) { camera_pos += camera_right * camera_speed; } } // glfw: whenever the window size changed (by OS or user resize) this callback function executes // --------------------------------------------------------------------------------------------- static void framebuffer_size_callback(GLFWwindow *window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); } // glfw: whenever the mouse moves, this callback is called // ------------------------------------------------------- static void mouse_callback(GLFWwindow *window, double xpos, double ypos) { if (first_click.load()) { lastX = xpos; lastY = ypos; first_click.store(false); } float xoffset = xpos - lastX; float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top lastX = xpos; lastY = ypos; xoffset *= sensitivity; yoffset *= sensitivity; yaw += xoffset; pitch += yoffset; // make sure that when pitch is out of bounds, screen doesn't get flipped if (pitch > 89.0f) pitch = 89.0f; if (pitch < -89.0f) pitch = -89.0f; update_camera_vectors(); } // glfw: whenever the mouse scroll wheel scrolls, this callback is called // ---------------------------------------------------------------------- static void scroll_callback(GLFWwindow *window, double xoffset, double yoffset) { if (field_of_view >= 1.0f && field_of_view <= 45.0f) { field_of_view -= yoffset; } if (field_of_view <= 1.f) { field_of_view = 1.0f; } if (field_of_view >= 45.0f) { field_of_view = 45.0f; } } static GLuint load_texture(const char * path) { GLuint texture_id{}; glGenTextures(1, &texture_id); int width{}, height{}, nrComponents{}; unsigned char *data{ stbi_load(path, &width, &height, &nrComponents, 0) }; if (data) { GLenum format{}; if (nrComponents == 1) format = GL_RED; else if (nrComponents == 3) format = GL_RGB; else if (nrComponents == 4) format = GL_RGBA; glBindTexture(GL_TEXTURE_2D, texture_id); glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(data); } else { std::cout << __FUNCTION__ << " " << __LINE__ << " " << "Texture failed to load at path : " << path << std::endl; stbi_image_free(data); } data = nullptr; return texture_id; } int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // glfw window creation // -------------------- GLFWwindow *window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); if (window == nullptr) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // tell GLFW to capture our mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader(reinterpret_cast<GLADloadproc>(glfwGetProcAddress))) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // update camera parameters. update_camera_vectors(); // configure global opengl state glEnable(GL_DEPTH_TEST); GLuint vertex_shader_id{ shader::create("C:\\Users\\shihua\\source\\repos\\opengl_demo\\blending\\blending\\glsl\\vertex_shader.glsl", shader_type::vertex_shader) }; GLuint fragment_shader_id{ shader::create("C:\\Users\\shihua\\source\\repos\\opengl_demo\\blending\\blending\\glsl\\fragment_shader.glsl", shader_type::fragment_shader) }; GLuint program_id{ glCreateProgram() }; glAttachShader(program_id, vertex_shader_id); glAttachShader(program_id, fragment_shader_id); glLinkProgram(program_id); glDeleteShader(vertex_shader_id); glDeleteShader(fragment_shader_id); shader::checkout_shader_state(program_id, shader_type::program); const float floor_vertices[]{ // positions // texture Coords (note we set these higher than 1 (together with GL_REPEAT as texture wrapping mode). this will cause the floor texture to repeat) 5.0f, -0.5f, 5.0f, 2.0f, 0.0f, -5.0f, -0.5f, 5.0f, 0.0f, 0.0f, -5.0f, -0.5f, -5.0f, 0.0f, 2.0f, 5.0f, -0.5f, 5.0f, 2.0f, 0.0f, -5.0f, -0.5f, -5.0f, 0.0f, 2.0f, 5.0f, -0.5f, -5.0f, 2.0f, 2.0f }; float cubes_vertices[]{ // positions // texture Coords -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f }; const float grass_vertices[]{ // positions // texture Coords (swapped y coordinates because texture is flipped upside down) 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.0f, 0.0f, 1.0f, 1.0f, -0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.0f, 1.0f, 0.0f }; GLuint cube_VAO{}; GLuint cube_VBO{}; glGenVertexArrays(1, &cube_VAO); glGenBuffers(1, &cube_VBO); glBindVertexArray(cube_VAO); glBindBuffer(GL_ARRAY_BUFFER, cube_VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(cubes_vertices), cubes_vertices, GL_STATIC_DRAW); std::size_t offset{ 0 }; glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(offset)); offset = 3 * sizeof(float); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(offset)); // notice that. glBindVertexArray(0); GLuint floor_VAO{}; GLuint floor_VBO{}; glGenVertexArrays(1, &floor_VAO); glGenBuffers(1, &floor_VBO); glBindVertexArray(floor_VAO); glBindBuffer(GL_ARRAY_BUFFER, floor_VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(floor_vertices), floor_vertices, GL_STATIC_DRAW); offset = 0; glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(offset)); offset = 3 * sizeof(float); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(offset)); // notice that glBindVertexArray(0); GLuint grass_VAO{}; GLuint grass_VBO{}; glGenVertexArrays(1, &grass_VAO); glGenBuffers(1, &grass_VBO); glBindVertexArray(grass_VAO); glBindBuffer(GL_ARRAY_BUFFER, grass_VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(grass_vertices), grass_vertices, GL_STATIC_DRAW); offset = 0; glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(offset)); offset = 3 * sizeof(float); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(offset)); // notice that: glBindVertexArray(0); GLuint wall_texture_id{ load_texture("C:\\Users\\shihua\\source\\repos\\opengl_demo\\depth_test\\depth_test\\image\\marble.jpg") }; GLuint floor_texture_id{ load_texture("C:\\Users\\shihua\\source\\repos\\opengl_demo\\depth_test\\depth_test\\image\\metal.png") }; GLuint grass_texture_id{ load_texture("C:\\Users\\shihua\\source\\repos\\opengl_demo\\blending\\blending\\image\\grass.png") }; glUseProgram(program_id); shader::set_int(program_id, "texture_1", 0); // grass locations. std::vector<glm::vec3> vegetation_locations { glm::vec3(-1.5f, 0.0f, -0.48f), glm::vec3(1.5f, 0.0f, 0.51f), glm::vec3(0.0f, 0.0f, 0.7f), glm::vec3(-0.3f, 0.0f, -2.3f), glm::vec3(0.5f, 0.0f, -0.6f) }; while (!glfwWindowShouldClose(window)) { double current_time{ glfwGetTime() }; delta_time = current_time - last_frame; last_frame = current_time; process_input(window); glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(program_id); glm::mat4 model{ 1.0f }; glm::mat4 view{ glm::lookAt(camera_pos, camera_pos + camera_front, camera_up) }; glm::mat4 projection{ glm::perspective(glm::radians(field_of_view), WIDTH*1.0f / HEIGHT * 1.0f, 0.1f, 100.0f) }; shader::set_mat4(program_id, "view", view); shader::set_mat4(program_id, "projection", projection); // draw floor glBindVertexArray(floor_VAO); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, floor_texture_id); model = glm::mat4{ 1.0f }; shader::set_mat4(program_id, "model", model); glDrawArrays(GL_TRIANGLES, 0, 6); // draw cubes glBindVertexArray(cube_VAO); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, wall_texture_id); // draw first cube. model = glm::mat4{ 1.0f }; model = glm::translate(model, glm::vec3(-1.0f, 0.0f, -1.0f)); shader::set_mat4(program_id, "model", model); glDrawArrays(GL_TRIANGLES, 0, 36); //draw second cube. model = glm::mat4{ 1.0f }; model = glm::translate(model, glm::vec3{ 2.0f, 0.0f, 0.0f }); shader::set_mat4(program_id, "model", model); glDrawArrays(GL_TRIANGLES, 0, 36); // vegetation glBindVertexArray(grass_VAO); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, grass_texture_id); for (std::size_t index = 0; index < vegetation_locations.size(); ++index) { model = glm::mat4{ 1.0f }; model = glm::translate(model, vegetation_locations[index]); shader::set_mat4(program_id, "model", model); glDrawArrays(GL_TRIANGLES, 0, 6); } // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glDeleteVertexArrays(1, &cube_VAO); glDeleteVertexArrays(1, &floor_VAO); glDeleteVertexArrays(1, &grass_VAO); glDeleteBuffers(1, &cube_VBO); glDeleteBuffers(1, &floor_VBO); glDeleteBuffers(1, &floor_VBO); glfwTerminate(); return 0; }
e930cc7c6c3fa034ec4c53c770b8fec91c26d604
[ "Markdown", "CMake", "C++" ]
22
C++
SHIHUAMarryMe/opengl_demo
7e60c0c71c343191e25c49a381251b693e4b2a79
40828d20a3f0a138ffe5df9e59a5bc639039af36
refs/heads/master
<file_sep>import tkinter as tk import sqlite3 import tkinter.messagebox HEIGHT = 300 WIDTH = 400 database = sqlite3.connect('YourPlan.db') c = database.cursor() c.execute('''create table if not exists list (contain varchar(50) primary key)''') database.commit() #---------------------运行所需函数-------------------------------- def addMission(): top = tk.Toplevel() top.title("添加") textEntry = tk.Entry(top, width=10) textEntry.grid(row=1, column=0, padx=1, pady=1) addButton2 = tk.Button(top, text="添加", command=lambda: addMissionComfire(textEntry.get(), top)) addButton2.grid(row=1, column=1, padx=1, pady=1) def addList(): top = tk.Toplevel() top.title("添加") textEntry = tk.Entry(top, width=10) textEntry.grid(row=1, column=0, padx=1, pady=1) addButton2 = tk.Button(top, text="添加", command=lambda: addListComfire(textEntry.get(), top)) addButton2.grid(row=1, column=1, padx=1, pady=1) def addMissionComfire(text, top): missionBox.insert("end", text) top.destroy() def addListComfire(text, top): contain = listBox.get(0, missionBox.size()) if text in contain: tk.messagebox.showinfo('提示', '存在重复的计划单,请更换名字') else: listBox.insert("end", text) #c.execute('''create table if is not exist ? # (contain varchar(50) primary key);''', (text,)) #c.execute("insert into list(contain) values (?);", (text,)) #database.commit() top.destroy() def exitAndSave(): print("Escape") root.destroy() def click(): print("click") root.destroy() #-------------------------图形化GUI布局-------------------------- root = tk.Tk() root.resizable(0, 0) mainCanvas = tk.Canvas(root, height=HEIGHT, width=WIDTH, bg='gray') mainCanvas.pack() listFrame = tk.Frame(mainCanvas) listFrame.grid(row=0, column=0) missionFrame = tk.Frame(mainCanvas, bg='green') missionFrame.grid(row=0, column=1) listBox = tk.Listbox(listFrame) listBox.grid(row=0, column=0) buttonFrame2 = tk.Frame(listFrame) buttonFrame2.grid(row=1, column=0) addListButton = tk.Button(buttonFrame2, text="add", command=addList) addListButton.grid(row=0, column=0) deleteListButton = tk.Button(buttonFrame2, text="delete", command=lambda x=listBox: x.delete("active")) deleteListButton.grid(row=0, column=1) missionBox = tk.Listbox(missionFrame) missionBox.grid(row=0, column=0) buttonFrame1 = tk.Frame(missionFrame) buttonFrame1.grid(row=1, column=0) addButton = tk.Button(buttonFrame1, text="添加", command=addMission) addButton.grid(row=0, column=0) deleteButton = tk.Button(buttonFrame1, text="删除", command=lambda x=missionBox: x.delete("active")) deleteButton.grid(row=0, column=1) for item in ["996", "ICU"]: missionBox.insert("end", item) listBox.insert("end", item) root.protocol('WM_DELETE_WINDOW', exitAndSave) root.mainloop() <file_sep>import sqlite3 database = sqlite3.connect("YourPlan.db") conn = database.cursor() conn.execute('''drop table list''')
70e7fa4a6ca193aacc5e9606ab0feff3e9eebc31
[ "Python" ]
2
Python
Wb-Alpha/YourPlan
382d2b4d872ac7dc88bd7f307c101c89c9448363
b38c2abac29a7377ec311bb3f7a1e65f6492652f
refs/heads/master
<file_sep>const path = require("path"); const config = { api: { port: 3000 }, timeout: 30 * 1000 }; module.exports = config; <file_sep>const Router = require("express").Router; const ws = require("../libs").ws; const sockets = ws.sockets; const router = Router(); router.post("/create", (req, res) => { const user = req.body; if (sockets.get(user.name)) { res.status(409); res.json("duplicate user name"); return; } res.status(201); res.json({ name: user.name }); return; }); module.exports = router; <file_sep># chatroom-server ## Features - Use node.js - Use docker ## Install ```bash git clone <reop> ``` ## Commands - Before development ``` npm install ``` - Start server ``` node server.js ``` ## Docker - Build docker image ``` sh docker-build-backend.sh ``` - Run image ``` docker-compose up -d ```<file_sep>const WebSocket = require("ws"); const config = require("../config"); const HashMap = require("hashmap"); const sockets = new HashMap(); const cleanTasks = new HashMap(); const createCleanTask = (wss, type, name, message) => { const task = setTimeout(() => { const data = { type, name, message }; wss.broadcast(JSON.stringify(data)); const socket = sockets.get(name); socket.terminate(); sockets.delete(name); }, config.timeout); return task; }; module.exports = { sockets, setup: server => { wss = new WebSocket.Server({ server }); wss.broadcast = data => { wss.clients.forEach(function each(client) { if (client.readyState === WebSocket.OPEN) { client.send(data); } }); }; wss.on("connection", socket => { socket.on("message", message => { const user = JSON.parse(message); if (user.login === true) { const data = { type: "system", name: user.name, message: `${user.name} enter the chat` }; wss.broadcast(JSON.stringify(data)); sockets.set(user.name, socket); cleanTasks.set( user.name, createCleanTask( wss, "system", user.name, `${user.name} was disconnected due to inactivity` ) ); } if (user.logout === true) { sockets.delete(user.name); clearTimeout(cleanTasks.get(user.name)); cleanTasks.delete(user.name); const data = { type: "system", name: user.name, message: `${user.name} left the chat, connection lost` }; wss.broadcast(JSON.stringify(data)); } if (user.message) { clearTimeout(cleanTasks.get(user.name)); cleanTasks.delete(user.name); cleanTasks.set( user.name, createCleanTask( wss, "system", user.name, `${user.name} was disconnected due to inactivity` ) ); wss.broadcast(JSON.stringify(user)); } }); }); } }; <file_sep>const config = require("./config"); const express = require("express"); const app = express(); const server = require("http").createServer(app); const json = require("body-parser").json; const urlencoded = require("body-parser").urlencoded; const routes = require("./routes"); const ws = require("./libs").ws; ws.setup(server); app.use(json()); app.use( urlencoded({ extended: false }) ); routes.setup(app); app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header( "Access-Control-Allow-Headers", "Authorization,Content-Type,Accept" ); res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS"); next(); }); app.use(function(err, req, res, next) { console.error({ err }); next(); }); process.on("uncaughtException", function(err) { console.error(err); // handle the error safely }); // this function is called when you want the server to die gracefully // i.e. wait for existing connections var gracefulShutdown = function() { console.log("Received kill signal, shutting down gracefully."); server.close(function() { console.log("Closed out remaining connections."); process.exit() }); // if after setTimeout(function() { console.error("Could not close connections in time, forcefully shutting down"); process.exit() }, 10*1000); } // listen for TERM signal .e.g. kill process.on ('SIGTERM', gracefulShutdown); // listen for INT signal e.g. Ctrl-C process.on ('SIGINT', gracefulShutdown); server.listen(config.api.port, function() { console.log(`Api server listening on port: ${config.api.port}`); }); <file_sep>const express = require("express"); const chat = require("./chat"); const routes = { setup: app => { // setup routes const api = express.Router(); api.use("/chat", chat); app.use("/api", api); } }; module.exports = routes;
b486cd3a75d6879ebecd7fc80a29a2cf39b4288b
[ "JavaScript", "Markdown" ]
6
JavaScript
VincentLinsanity/chatroom-server
119161727bf6b394058e4a1cc881e8b2a5fb0918
d6bddecd3f34a83a48fbeeff09ac6a2dcca7c1ec
refs/heads/master
<repo_name>forki/Gjallarhorn<file_sep>/samples/WpfSimpleApplicationCSharp/Context.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Gjallarhorn; using Gjallarhorn.Bindable; namespace WpfSimpleApplicationCSharp { internal static class Context { public static BindingSource CreateBindingSource() { var source = BindingModule.createSource(); return source; } } }
e0a33254a85e51d8fa2a8dac454eaa6fc0ab8d2a
[ "C#" ]
1
C#
forki/Gjallarhorn
9bfc49c6af0dfa12c09fc5fb90f066b5f186f2cd
ed1f88e87f226117290970a7392dc83a43687a4e
refs/heads/master
<repo_name>mailbackwards/tt_imgfeed<file_sep>/requirements.txt beautifulsoup4==4.4.1 feedparser==5.2.1 Flask==0.10.1 gunicorn==19.3.0 itsdangerous==0.24 Jinja2==2.8 MarkupSafe==0.23 Werkzeug==0.11.2 wheel==0.24.0 <file_sep>/app.py from flask import Flask, render_template import feedparser import random from bs4 import BeautifulSoup app = Flask(__name__) DEFAULT_FEED = 'main' def get_feed(url): feed = feedparser.parse(url) title = feed.feed.get('title', '') if title and title.startswith('The Texas Tribune'): title = ' '.join(title.split(' ')[3:]) return { 'title': title, 'entries': feed.entries } def make_soup(item): return BeautifulSoup(item.summary, 'html.parser') @app.route('/') def respond(): return hello_world(DEFAULT_FEED) @app.route('/<path:path>') def hello_world(path): url = 'https://www.texastribune.org/feeds/'+path feed = get_feed(url) struct_items = [] for item in feed['entries']: soup = make_soup(item) img = soup.find('img') or {} if not img: continue struct_items.append({ 'headline': item.title, 'img': img.get('src'), 'date': ' '.join(item.published.split(' ')[:4]) }) return render_template('index.html', items=struct_items, title=feed['title']) if __name__ == '__main__': app.run(debug=True)
729cf9e7dfd1d75758842ee9cc840753a8c21521
[ "Python", "Text" ]
2
Text
mailbackwards/tt_imgfeed
ff2ea576b75af9654f4f9ebdb531f7c58306c4b0
4e88c0d6b19aed4e4577014c112b0096c4bcaf86
refs/heads/master
<file_sep>## React hot reload v3 with react-router v3 with redux Does hot reload work? **YES** Does time travel work? **NO** (no router state) Can child component access router state with connect? **NO** (no router state) Note: There is no router state in Redux store. Breaks time travel debugging when the route has been changed. <file_sep>## react-hot-reload v3 Scaffold ## This repo contains scaffolds for `react-hot-reload` v3 and compare pros and cons when combining it with react-router and redux with several methods. ### Result ### | redux | react-router | react-router-redux | redux-router | hot reload | correct time travel | child component can access router state via connect | |-------|--------------|--------------------|---------------|------------|---------------------|-----------------------------------------------------| | no | no | no | no | **YES** | **NO** | **NO** | | yes | no | no | no | **YES** | **YES** | **NO** | | no | v3 | no | no | **YES** | **NO** | **NO** | | yes | v3 | no | no | **YES** | **NO** | **NO** | | yes | v3 | v4 | no | **NO** | **YES** | **NO** | | yes | v2 | no | v2 | **NO** | **YES** | **YES** | | yes | v4 | v5 | no | **YES** | **YES** | **YES** | <file_sep>## React hot reload v3 with redux ## Does hot reload work? **YES** Note: Does not use react-router. <file_sep>## React hot reload v3 with react-router v3 Does hot reload work? **YES** <file_sep>## React hot reload v3 with react-router v2 and redux-router v2 ## Does hot reload work? **NO** Does time travel work? **YES** Can child component access router state with connect? **YES** Note: redux-router v2.1.2 needs react-router v2.x and history v2.x (does not work with react-router v3 with history v2.x/3.x) <file_sep>## React hot reload v3 without react-router and redux Does hot reload work? **YES** <file_sep>import React from 'react' import { IndexRoute, Router, Route, browserHistory } from 'react-router' import Home from './components/Home' import Hello from './components/Hello' import Counter from './components/Counter' import NoMatch from './components/NoMatch' import Layout from './components/Layout' const App = () => ( <Router history={browserHistory}> <Route path="/" component={Layout}> <IndexRoute component={Home} /> <Route path="hello" component={Hello} /> <Route path="counter" component={Counter} /> <Route path="*" component={NoMatch} /> </Route> </Router> ) export default App <file_sep>import React from 'react' import { ConnectedRouter } from 'react-router-redux' import routes from './routes' const App = () => { return ( <ConnectedRouter> { routes } </ConnectedRouter> ) } export default App <file_sep>import React from 'react' import { connect } from 'react-redux' import HelloChild from './HelloChild' const Hello = ({ path }) => ( <div> <div>Hello</div> <HelloChild path={path} /> </div> ) const mapStateToProps = (state, ownProps) => ({ path: ownProps.location.pathname, }) export default connect(mapStateToProps)(Hello) <file_sep>import React from 'react' const HelloChild = ({ path }) => ( <div> Hello-Child at {path} (receive path from parent) </div> ) export default HelloChild <file_sep>import { combineReducers } from 'redux' import { routerStateReducer } from 'redux-router' import counterReducer from './counter' const rootReducer = combineReducers({ count: counterReducer, router: routerStateReducer, }) export default rootReducer <file_sep>import React from 'react' import { ReduxRouter } from 'redux-router' import routes from './routes' const App = () => ( <ReduxRouter> { routes } </ReduxRouter> ) export default App <file_sep>## React hot reload v3 with react-router v4 and react-router-redux v5 ## Does hot reload work? **YES** Does time travel work? **YES** Can child component access router state with connect? **YES** Note: `react-router-redux` is still not available on npm. So, we have to use directly from [timdorr's branch](https://github.com/timdorr/react-router-redux/tree/5.0.x) and build it in our `node_modules` folder. **How to run** 1. `yarn` 2. `npm run prepare` This will install and build `react-router-redux` in `node_modules` 3. `npm run dev`
f185fcd8dc57a9880e2d6fa71d11f69e738302f1
[ "Markdown", "JavaScript" ]
13
Markdown
supasate/react-hot-reload-v3-scaffold
5685c12e5a80215dcc8756e409fdea3d3266b5ff
0d073b422192691a6795bbfe2d16edd151c704b5
refs/heads/master
<repo_name>orestislef/Techblogproject<file_sep>/app/src/main/java/com/orestislef/techblogproject/MainActivity.java package com.orestislef.techblogproject; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.core.view.GravityCompat; import androidx.drawerlayout.widget.DrawerLayout; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.EditText; import com.google.android.material.navigation.NavigationView; import java.util.ArrayList; import java.util.List; import java.util.Objects; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { RecyclerView NewsRecyclerview; RecyclerViewPostAdapter recyclerViewPostAdapter; List<PostItem> mData; boolean isDark = false; ConstraintLayout rootLayout; EditText searchInput; CharSequence search = ""; public int postsPerPage = 30; public int category = 0; private static final String TAG = "MainActivity"; public String imageUrl; private DrawerLayout drawer; private Toolbar toolbar; private ActionBarDrawerToggle toggle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // let's make this activity on full screen requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_main); // hide the action bar // getSupportActionBar().hide(); // ini view // rootLayout = findViewById(R.id.root_layout); drawer = findViewById(R.id.drawer_layout); searchInput = findViewById(R.id.search_input); NewsRecyclerview = findViewById(R.id.news_rv); mData = new ArrayList<>(); // load theme state toolbar = findViewById(R.id.toolbar); toolbar.setVisibility(View.GONE); setSupportActionBar(toolbar); drawer.findViewById(R.id.drawer_layout); NavigationView navigationView = findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); if (savedInstanceState == null) { navigationView.setCheckedItem(R.id.nav_home); } getData(); // adapter ini and setup recyclerViewPostAdapter = new RecyclerViewPostAdapter(this, mData, isDark); NewsRecyclerview.setAdapter(recyclerViewPostAdapter); NewsRecyclerview.setLayoutManager(new LinearLayoutManager(this)); searchInput.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { recyclerViewPostAdapter.getFilter().filter(s); search = s; } @Override public void afterTextChanged(Editable s) { } }); } @Override public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { Log.d(TAG, "onNavigationItemSelected: selected: " + menuItem); switch (menuItem.getItemId()) { case R.id.nav_home: category = 0; break; case R.id.nav_smartphones: category = 8; break; case R.id.nav_gear: category = 24; break; case R.id.nav_reviews: category = 58; break; case R.id.nav_workshop: category = 1033; break; case R.id.nav_internet: category = 49; break; case R.id.nav_cars: category = 9131; break; case R.id.nav_homecinema: category = 57; break; case R.id.nav_software: category = 584; break; case R.id.nav_computers: category = 29; break; case R.id.nav_business: category = 24; break; } mData.clear(); getData(); drawer.closeDrawer(GravityCompat.START); setSupportActionBar(toolbar); toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); return true; } @Override public void onBackPressed() { if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else super.onBackPressed(); } public void getData() { Retrofit retrofit = new Retrofit.Builder().baseUrl(getResources() .getString(R.string.base_url)) .addConverterFactory(GsonConverterFactory.create()) .build(); RetrofitArrayApi service = retrofit.create(RetrofitArrayApi.class); Call<List<WPPost>> call; if (category == 0) { call = service.getPostPerPage(postsPerPage); } else { call = service.getPostByCategory(category); } call.enqueue(new Callback<List<WPPost>>() { @Override public void onResponse(@NonNull Call<List<WPPost>> call, @NonNull Response<List<WPPost>> response) { Log.e(TAG, "onResponse: " + response.body()); for (int i = 0; i < Objects.requireNonNull(response.body()).size(); i++) { int mId = response.body().get(i).getId(); Log.d(TAG, "onResponseID: " + mId); final String mediaUrl = response.body().get(i).getLinks().getWpAttachment().get(0).getHref(); final String mTitle = response.body().get(i).getTitle().getRendered(); String mSubtitle = response.body().get(i).getExcerpt().getRendered(); mSubtitle = mSubtitle.replace("<p>", ""); mSubtitle = mSubtitle.replace("</p>", ""); mSubtitle = mSubtitle.replace("[&hellip;]", ""); final String finalMContent = response.body().get(i).getContent().getRendered(); final String mDate = response.body().get(i).getDate(); Log.d(TAG, "onResponse: " + "\n================================================================================================================================================================================================================================================" + "\nid: \t\t" + mId + "\nTitle: \t\t" + mTitle + "\nSubtitle: \t" + mSubtitle + "\nContent: \t\t" + finalMContent + "\n================================================================================================================================================================================================================================================"); Retrofit retrofit2 = new Retrofit.Builder() .baseUrl(getResources().getString(R.string.base_url)) .addConverterFactory(GsonConverterFactory.create()) .build(); RetrofitArrayApi service2 = retrofit2.create(RetrofitArrayApi.class); Call<List<WPPostID>> call2 = service2.getWpAttachment(mediaUrl); Log.d(TAG, "getRetrofitImageMediaUrl: " + mediaUrl); final String finalMSubtitle = mSubtitle; call2.enqueue(new Callback<List<WPPostID>>() { @Override public void onResponse(@NonNull Call<List<WPPostID>> call, @NonNull Response<List<WPPostID>> response) { Log.e(TAG, "onResponse: " + response.body()); if (response.body() != null) { if (response.body().size() != 0) { imageUrl = response.body().get(0).getMediaDetails().getSizes().getThumbnail().getSourceUrl(); // imageUrl = response.body().get(0).getSourceUrl(); Log.d(TAG, "onResponseImage: " + "\n******************************************************************************************" + "\n\t with media " + imageUrl + "\n******************************************************************************************"); } else { imageUrl = ""; Log.d(TAG, "onResponseImage: " + "\n******************************************************************************************" + "\n\t null media\n" + imageUrl + "\n******************************************************************************************"); } } mData.add(new PostItem(mTitle, finalMSubtitle, finalMContent, mDate, imageUrl)); recyclerViewPostAdapter.notifyItemInserted(mData.size() - 1); } @Override public void onFailure(@NonNull Call<List<WPPostID>> call, Throwable t) { } } ); } } @Override public void onFailure(@NonNull Call<List<WPPost>> call, Throwable t) { } }); } } <file_sep>/README.md # Techblogproject Techblog.gr website Testing retrofit2 implementation to populate threds into recyclerView <file_sep>/app/src/main/java/com/orestislef/techblogproject/RecyclerViewPostAdapter.java package com.orestislef.techblogproject; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Handler; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.RecyclerView; import android.text.format.DateUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.AnimationUtils; import android.widget.Filter; import android.widget.Filterable; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.DataSource; import com.bumptech.glide.load.engine.GlideException; import com.bumptech.glide.request.RequestListener; import com.bumptech.glide.request.target.Target; import org.sufficientlysecure.htmltextview.HtmlHttpImageGetter; import org.sufficientlysecure.htmltextview.HtmlTextView; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class RecyclerViewPostAdapter extends RecyclerView.Adapter<RecyclerViewPostAdapter.NewsViewHolder> implements Filterable { Context mContext; List<PostItem> mData; List<PostItem> mDataFiltered; public RecyclerViewPostAdapter(Context mContext, List<PostItem> mData, boolean isDark) { this.mContext = mContext; this.mData = mData; this.mDataFiltered = mData; } public RecyclerViewPostAdapter(Context mContext, List<PostItem> mData) { this.mContext = mContext; this.mData = mData; this.mDataFiltered = mData; } @NonNull @Override public NewsViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View layout; layout = LayoutInflater.from(mContext).inflate(R.layout.item_news, viewGroup, false); return new NewsViewHolder(layout); } @Override public void onBindViewHolder(@NonNull final NewsViewHolder newsViewHolder, int position) { // bind data here // we apply animation to views here // first lets create an animation for user photo newsViewHolder.img_user.setAnimation(AnimationUtils.loadAnimation(mContext, R.anim.fade_transition_animation)); // lets create the animation for the whole card // first lets create a reference to it // you ca use the previous same animation like the following // but i want to use a different one so lets create it .. newsViewHolder.container.setAnimation(AnimationUtils.loadAnimation(mContext, R.anim.fade_scale_animation)); newsViewHolder.tv_title.setText(mDataFiltered.get(position).getTitle()); newsViewHolder.tv_content.setHtml(mDataFiltered.get(position).Excerpt, new HtmlHttpImageGetter(newsViewHolder.tv_content)); // newsViewHolder.tv_content.setHtml(mDataFiltered.get(position).getContent()); newsViewHolder.tv_date.setText(calculateTimeAgo(mDataFiltered.get(position).getDate())); if (mDataFiltered.get(position).image.equals("")) { newsViewHolder.img_user.setVisibility(View.GONE); } else { int finalPos = position; Glide.with(mContext) .load(mDataFiltered.get(position)).listener(new RequestListener<Drawable>() { @Override public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) { new Handler().post(() -> Glide.with(mContext) .load(mDataFiltered.get(finalPos).image) .into(newsViewHolder.img_user)); return false; } @Override public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) { return false; } }).into(newsViewHolder.img_user); } int finalPos = position; newsViewHolder.container.setOnClickListener(v -> newsViewHolder.tv_content. setHtml(mDataFiltered.get(finalPos).Content, new HtmlHttpImageGetter(newsViewHolder.tv_content))); } @Override public int getItemCount() { return mDataFiltered.size(); } public String calculateTimeAgo(@NonNull String date) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US); try { long time = sdf.parse(date).getTime(); long now = System.currentTimeMillis(); CharSequence ago = DateUtils.getRelativeTimeSpanString(time, now, DateUtils.SECOND_IN_MILLIS); return ago + ""; } catch (ParseException e) { e.printStackTrace(); } return null; } @Override public Filter getFilter() { return new Filter() { @Override protected FilterResults performFiltering(CharSequence constraint) { String Key = constraint.toString(); if (Key.isEmpty()) { mDataFiltered = mData; } else { List<PostItem> lstFiltered = new ArrayList<>(); for (PostItem row : mData) { if (row.getTitle().toLowerCase().contains(Key.toLowerCase())) { lstFiltered.add(row); } } mDataFiltered = lstFiltered; } FilterResults filterResults = new FilterResults(); filterResults.values = mDataFiltered; return filterResults; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { mDataFiltered = (List<PostItem>) results.values; notifyDataSetChanged(); } }; } public static class NewsViewHolder extends RecyclerView.ViewHolder { HtmlTextView tv_content; TextView tv_title, tv_date; ImageView img_user; RelativeLayout container; public NewsViewHolder(@NonNull View itemView) { super(itemView); container = itemView.findViewById(R.id.container); tv_title = itemView.findViewById(R.id.tv_title); tv_content = itemView.findViewById(R.id.tv_description); tv_date = itemView.findViewById(R.id.tv_date); img_user = itemView.findViewById(R.id.img_user); } } }
4e7260692ed031ed7b6111528be7116d429e8a68
[ "Markdown", "Java" ]
3
Java
orestislef/Techblogproject
c9a0eaea0c89eed30c2513b28b338d438069d98a
547d243488307b16856c601278a3582892bcb4a0
refs/heads/master
<file_sep>// https://codeforces.com/contest/520/problem/B // https://codeforces.com/contest/520/submission/17434691 #include <iostream> using namespace std; int main() { int n, m, CNT; cin >> m >> n; for (CNT = 0; n > m; (n&1) ? n++ : n>>= 1, CNT++); cout << CNT + (m - n); return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/742/problem/B // https://codeforces.com/contest/742/submission/22797691 #include <stdio.h> #include <iostream> #include <vector> using namespace std; int main() { vector<int> frecv(200005, 0); int n, k, x; long long cnt = 0; scanf("%d %d", &n, &k); while (n--) { scanf("%d", &x); cnt += frecv[x^k]; frecv[x]++; } cout << cnt; return 0; }<file_sep>// https://codeforces.com/contest/455/problem/A // https://codeforces.com/contest/455/submission/15059708 #include <iostream> using namespace std; long long v[100001]; int main() { int x,n; cin>>n; for (int i=1;i<=n;i++) { cin>>x; v[x]+=x; } v[0] = 0; for (int i = 2; i<= 100000;i++) { v[i] = max(v[i-2]+v[i],v[i-1]); } cout<<v[100000]; return 0; } <file_sep>// https://codeforces.com/contest/155/problem/A // https://codeforces.com/contest/155/submission/13958025 #include <iostream> using namespace std; int main() { int x,n,mins,maxs,nr; cin>>n; cin>>mins; maxs=mins; nr=0; while (n-1>0) { cin>>x; if (x<mins) { nr++; mins=x; } if (x>maxs) { nr++; maxs=x; } n--; } cout<<nr; return 0; } <file_sep>// https://codeforces.com/contest/683/problem/A // https://codeforces.com/contest/683/submission/18524836 fun main(args: Array<String>) { val (a, x, y) = readLine()!!.split(' ').map(String::toInt) if (x < 0) println(2); else if (y < 0) println(2); else{ if (x == 0){ if (y <= a) println(1); else println(2); } else if (y == 0){ if (x <= a) println(1); else println(2); } else{ if (a > x){ if (a == y) println(1); else if (a > y) println(0); else println(2); }else if (a==x){ if (y > a) println(2); else println(1); }else println(2); } } }<file_sep>// https://codeforces.com/contest/620/problem/A // https://codeforces.com/contest/620/submission/18017494 #include <iostream> #include <algorithm> using namespace std; int main() { int xi, yi, xf, yf; cin >> xi >> yi >> xf >> yf; cout << max(abs(xf - xi), abs(yf - yi)); return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/746/problem/D // https://codeforces.com/contest/746/submission/23107000 #include <iostream> #include <string> #include <algorithm> using namespace std; void doString(string& s, int nmb, char c) { string kappa = ""; for (int i = 0; i < nmb; ++i) { kappa += c; } s += kappa; } int main() { int n, k, a, b; cin >> n >> k >> a >> b; bool ok = true; string sol = ""; int mx; while (a > 0 && b > 0) { if (a > b) { if (sol != "" && sol[sol.size() - 1] == 'G') { b--; sol += 'B'; } mx = min(a, k); doString(sol, mx, 'G'); a -= mx; } else { if (sol != "" && sol[sol.size() - 1] == 'B') { a--; sol += 'G'; } mx = min(b, k); doString(sol, mx, 'B'); b -= mx; } } if (a > k || (a > 0 && sol[sol.size() - 1] == 'G')) ok = false; else doString(sol, a, 'G'); if (b > k || (b > 0 && sol[sol.size() - 1] == 'B')) ok = false; else doString(sol, b, 'B'); sol += '\n'; if (!ok) puts("NO"); else cout << sol; return 0; }<file_sep>// https://codeforces.com/contest/678/problem/A // https://codeforces.com/contest/678/submission/18418106 #include <iostream> using namespace std; int main() { int n, k, nr = 1; cin >> n >> k; nr += n / k; cout << k * nr; return 0; }<file_sep>// https://codeforces.com/contest/798/problem/A // https://codeforces.com/contest/798/submission/46797924 #include <iostream> #include <string> using namespace std; int Sol(const std::string& s) { int nr = 0; for (size_t i = 0, j = s.size() - 1; i < j; ++i, --j) { if (s[i] != s[j]) nr++; } if (nr == 0 && s.size() % 2 != 0) return 1; return nr; } int main() { string s; cin >> s; Sol(s) == 1 ? cout << "YES" : cout << "NO"; return 0; }<file_sep>// https://codeforces.com/contest/534/problem/A // https://codeforces.com/contest/534/submission/18029863 #include <iostream> using namespace std; int main() { int n, prim, ultim; cin >> n; if (n == 1 || n == 2) cout << "1\n1"; else if (n == 3) cout << "2\n1 3"; else if (n == 4) cout << "4\n3 1 4 2"; else { cout << n << "\n"; for (prim = 1, ultim = (n + 1) / 2 + 1; prim <= (n + 1) / 2; prim++, ultim++) { cout << prim << " "; if (ultim <= n) cout << ultim << " "; } } return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/230/problem/B // https://codeforces.com/contest/230/submission/17466110 #include <stdlib.h> #include <stdio.h> #include <math.h> bool prime(long long x) { if (x == 1) return false; for (long long i = 2; i <= long long(sqrt(double(x))); i++) { if (x % i == 0) return false; } return true; } int main() { long long n, t, i; scanf("%I64d", &n); for (; n > 0; n--) { scanf("%I64d", &t); i = long long(sqrt(double(t))); if (i * i != t) puts("NO"); else { if (prime(i)) puts("YES"); else puts("NO"); } } return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/456/problem/A // https://codeforces.com/contest/456/submission/16613518 #include <iostream> #include <malloc.h> #include <algorithm> using namespace std; typedef struct { int quality, price; }MyVector; bool compare(MyVector a, MyVector b) { return a.price < b.price; } char* solve(MyVector*, int); int main(int argc, char*argv[]) { int n; MyVector *v; cin >> n; v = (MyVector*)malloc(n*sizeof(MyVector)); for (int i = 0; i < n; i++) cin >> v[i].price >> v[i].quality; sort(v, v + n, compare); cout << solve(v, n); free(v); return EXIT_SUCCESS; } char* solve(MyVector* v, int size) { for (int i = 0; i < size - 1; i++) if (v[i].quality > v[i + 1].quality) return "Happy Alex"; return "Poor Alex"; }<file_sep># https://codeforces.com/contest/441/problem/A # https://codeforces.com/contest/441/submission/14872818 n, v = map(int,input().split()) vanz = [] i = 1 while (i<=n): l = list(map(int,input().split())) if v > min(l[1:]): vanz.append(i) i += 1 print(len(vanz)) for el in vanz: print(el, end = ' ' ) <file_sep>// https://www.spoj.com/problems/ACODE/ #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <map> #include <unordered_map> #include <set> #include <vector> #include <cstdio> #include <string> using namespace std; #define ll long long #define ull unsigned long long /*------------------------------------------------------------------*/ int main() { ios_base::sync_with_stdio(false) , cin.tie(nullptr) , cout.tie(nullptr); string s; cin >> s; ull best[5005]; int m; while (s != "0") { m = s.length(); best[m - 1] = best[m] = 1; s += '4'; for (int i = m - 2; i >= 0; --i) { best[i] = best[i + 1]; if (s[i] != '1' && s[i] != '2' && s[i+1] == '0') { best[0] = 0; break; } if (s[i] != '0' && s[i + 1] == '0') continue; if (s[i + 2] == '0') continue; if (s[i] == '1' || (s[i] == '2' && s[i + 1] <= '7')) best[i] += best[i + 2]; } jmp: cout << best[0] << '\n'; cin >> s; } return 0; } <file_sep>// https://codeforces.com/contest/276/problem/A // https://codeforces.com/contest/276/submission/17523475 #include <iostream> using namespace std; #define MAX 0x3B9ACA01 int main() { int n, k, max = -MAX, joy, t; cin >> n >> k; for (; n > 0; n--) { cin >> joy >> t; if (k >= t) { if (max < joy)max = joy; } else if (max < joy - (t - k)) max = joy - (t - k); } cout << max; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/262/problem/A // https://codeforces.com/contest/262/submission/17331632 #include <iostream> using std::cin; using std::cout; int main() { int n, k, x, nr = 0, aux; cin >> n >> k; for (; n > 0; n--) { cin >> x; aux = 0; for (; x != 0;x /= 10) if (x % 10 == 4 || x % 10 == 7) aux++; if (aux <= k) nr++; } cout << nr; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/551/problem/A // https://codeforces.com/contest/551/submission/14410809 #include <iostream> using namespace std; int r[2001],e[2001],v[2001]; int main() { int n; cin>>n; for (int i=1;i<=n;i++) { cin>>e[i]; v[e[i]]++; } r[2000]=0; for (int i=1999;i>=1;i--) { r[i] = v[i+1]+r[i+1]; } for (int i=1;i<=n;i++) { cout<<r[e[i]]+1<<" "; } return 0; } <file_sep>// https://codeforces.com/contest/583/problem/B // https://codeforces.com/contest/583/submission/17567732 #include <iostream> using namespace std; int main() { int v[1001], n, nr = -1, cnt = 0, i, j; char ok = '0'; cin >> n; for (int i = 0; i < n; i++)cin >> v[i]; while (cnt < n) { nr++; if (ok == '0') j = 1, i = 0, ok = '1'; else j = -1, i = n - 1, ok = '0'; for (; i < n && i >= 0; i += j) { if (v[i] <= cnt) cnt++, v[i] = 1001; } } cout << nr; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/664/problem/A // https://codeforces.com/contest/664/submission/17350147 #include <string> #include <iostream> using namespace std; int main() { string a, b; cin >> a >> b; if (a != b)cout << "1"; else cout << a; return EXIT_SUCCESS; }<file_sep># https://codeforces.com/contest/461/problem/A # https://codeforces.com/contest/461/submission/14447388 n = int(input()) m = sorted(list(map(int,input().split()))) s = sum(m) if n!=1: for i in range(n-1): s += m[i]*(i+1) s+=m[n-1]*(n-1) print(s) <file_sep># https://codeforces.com/contest/490/problem/A # https://codeforces.com/contest/490/submission/14398111 n = int(input()) l = list(map(int,input().split())) d = {1:[],2:[],3:[]} for i in range (n): d[l[i]].append(i+1) t = min(len(d[1]),len(d[2]),len(d[3])) print(t) while t>0: print(d[1].pop(),d[2].pop(),d[3].pop()) t-=1 <file_sep>// https://codeforces.com/contest/683/problem/B // https://codeforces.com/contest/683/submission/18525721 fun main(args: Array<String>) { val (a) = readLine()!!.split('\n').map(String::toInt) var i = 1; var arr = IntArray(a + 2); var num = arrayOfNulls<String>(a + 2); while (i <= a){ val (nm , h) = readLine()!!.split(' '); arr[i] = h.toInt(); num[i] = nm; i++; } i = 1; while (i <= a){ var j = i + 1; while (j <= a){ if (arr[i] > arr[j]){ var aux1 = arr[i]; var aux2 = num[i]; arr[i] = arr[j]; arr[j] = aux1; num[i] = num[j]; num[j] = aux2; } j++; } i++; } i = 1; while (i <= a){ println(num[i]); i++; } }<file_sep>// https://codeforces.com/contest/320/problem/A // https://codeforces.com/contest/320/submission/17146992 #include <iostream> #include <string> using namespace std; #define YES true #define NO !true int main() { int i; string s; bool ok; i = 0; ok = YES; cin >> s; while (i < s.length()) { if (s[i] == '1') { if ( (i + 1) < s.length() && s[i + 1] == '4') { if ( (i + 2) < s.length() && s[i + 2] == '4') i++; i++; } i++; } else { ok = NO; i++; } } if (ok) cout << "YES"; else cout << "NO"; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/787/problem/B // https://codeforces.com/contest/787/submission/25740045 #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <map> #include <unordered_map> #include <set> #include <vector> #include <cstdio> #include <string> using namespace std; #define ll long long #define ull unsigned long long /*------------------------------------------------------------------*/ int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); int n, m, mx, x; unordered_map<int, int> mp; bool ok = true; cin >> n >> m; for(int i = 1;i <=m && ok; ++i) { mp.clear(); ok = false; cin >> mx; for(int j = 1; j<=mx;++j) { cin >> x; mp[x] = 1; if (mp.find(-x) != mp.end()) ok = true; } } (!ok) ? puts("YES") : puts("NO"); return 0; }<file_sep>// https://www.spoj.com/problems/PRIME1/ #include <vector> #include <iostream> #include <algorithm> #include <math.h> using namespace std; void BuildSieve(vector<int>& Sieve) { const int limit = static_cast<int>(5e5) + 1; vector<bool> isPrime(limit, true); for (int i = 2; i < limit; ++i) { if (!isPrime[i]) continue; Sieve.push_back(i); for (int j = i + i; j < limit; j += i) { isPrime[j] = false; } } } bool IsPrime(vector<int>& Sieve, long long X) { long long limit = static_cast<long long>(sqrt(static_cast<double>(X))) + 1; bool isPrime = X != 1; for (const auto& p : Sieve) { if (p >= limit || !isPrime) break; if (X % p == 0) isPrime = false; } if (isPrime) return true; for (long long p = Sieve.back(); p < limit && !isPrime; ++p) { if (X % p == 0) isPrime = false; } return isPrime; } void SolvePrimes(vector<int>& Sieve, long long m, long long n) { for (long long i = m; i <= n; ++i) { if (IsPrime(Sieve, i)) cout << i << "\n"; } } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int t; vector<int> sieve; long long n, m; cin >> t; BuildSieve(sieve); while (t--) { cin >> m >> n; SolvePrimes(sieve, m, n); cout << "\n"; } return 0; }<file_sep>// https://codeforces.com/contest/435/problem/A // https://codeforces.com/contest/435/submission/17434848 #include <iostream> using namespace std; int main() { int n, m, cnt, s,x; cin >> n >> m; for (cnt = 1, s = 0; n > 0; n--) { cin >> x; if (s + x > m) s = x, cnt++; else s += x; } cout << cnt; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/752/problem/C // https://codeforces.com/contest/752/submission/23310300 #include <iostream> #include <string> using namespace std; int main() { int n; int cnt = 0, xAxis = 0, yAxis = 0; string s; cin >> n >> s; for (int i = 0; i < n; ++i) { if (s[i] == 'U') { if (yAxis == 2) cnt++, xAxis = 0; yAxis = 1; } else if (s[i] == 'D') { if (yAxis == 1) cnt++, xAxis = 0; yAxis = 2; } else if (s[i] == 'R') { if (xAxis == 2) cnt++, yAxis = 0; xAxis = 1; } else if (s[i] == 'L') { if (xAxis == 1) cnt++, yAxis = 0; xAxis = 2; } } cout << cnt + 1; return 0; }<file_sep># https://codeforces.com/contest/71/problem/A # https://codeforces.com/contest/71/submission/13404842 n=input() n=int(n) for i in range(n): s=input() if (len(s)>10): print(s[0],len(s)-2,s[len(s)-1], sep='') else: print(s) <file_sep>// https://codeforces.com/contest/584/problem/A // https://codeforces.com/contest/584/submission/14045532 #include <stdio.h> #include <stdlib.h> int main() { int i,n,k; scanf("%d %d",&n,&k); if (k==10 && n==1){printf("-1");} else{ if (k==10){printf("1");} else{printf("%d",k);} for (i=1;i<=n-1;i++) { printf("0"); } } return 0; } <file_sep>// https://codeforces.com/contest/479/problem/C // https://codeforces.com/contest/479/submission/17480481 #include <iostream> #include <algorithm> using namespace std; typedef struct _ELEM { int o1, o2; }ELEM; int main() { ELEM v[5001]; int n, maxs; cin >> n; for (int i = 0; i < n; i++)cin >> v[i].o1 >> v[i].o2; sort(v, v + n, [](ELEM st, ELEM dr) {return (st.o1 < dr.o1 || st.o1 == dr.o1 && st.o2 < dr.o2); }); maxs = min(v[0].o1, v[0].o2); for (int i = 1; i < n; i++) (min(v[i].o1, v[i].o2) >= maxs) ? maxs = min(v[i].o1, v[i].o2) : maxs = max(v[i].o1, v[i].o2); cout << maxs; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/725/problem/B // https://codeforces.com/contest/725/submission/21679692 #include <string> #include <iostream> using namespace std; int val(char dgt) { if (dgt == 'f') return 1; if (dgt == 'e') return 2; if (dgt == 'd') return 3; if (dgt == 'a') return 4; if (dgt == 'b') return 5; if (dgt == 'c') return 6; } int main() { string s; char c; int r; unsigned long long num, cmp = 0; cin >> s; c = s[s.size() - 1]; num = stoull(s.substr(0, s.size() - 1)); r = num % 4; if (r == 0) num--; cmp = 16 * (num / 4); if (r == 1 || r == 3) { cmp += val(c); } else if (r == 2 || r == 0) { cmp += 7 + val(c); } cout << cmp; return 0; }<file_sep>// https://codeforces.com/contest/729/problem/A // https://codeforces.com/contest/729/submission/22715444 #include <iostream> #include <string> using namespace std; int main() { string sol = ""; int n; string s; cin >> n >> s; size_t i = 0; size_t j; while (i < s.size()) { if (i + 2 < s.size()) { if (s[i] == 'o' && s[i + 1] == 'g' && s[i + 2] == 'o') { j = i + 3; bool ok = true; while (j < s.size() && ok) { if (j + 1 < s.size()) { if (s[j] == 'g' && s[j + 1] == 'o') j += 2; else ok = false; } else (ok = false); } sol += "***"; i = j; } else { sol += s[i]; i++; } } else { sol += s[i]; i++; } } cout << sol; return 0; }<file_sep>// https://codeforces.com/contest/496/problem/A // https://codeforces.com/contest/496/submission/47180521 #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; vector<int> v(n, 0); int best1 = 0; int best2 = 0; for (int i = 0; i < n; ++i) { cin >> v[i]; } best1 = max(v[1] - v[0], v[2] - v[1]); best2 = v[2] - v[0]; for (int i = 3; i < n; ++i) { best1 = max(best1, v[i] - v[i - 1]); best2 = min(best2, v[i] - v[i - 2]); } cout << max(best1, best2); return 0; }<file_sep># https://codeforces.com/contest/583/problem/A # https://codeforces.com/contest/583/submission/14410627 n = int(input()) v = [0]*(n+1) h = [0]*(n+1) i = 1 while (i<=n*n): a,b=map(int,input().split()) if v[a]==0 and h[b]==0: v[a]=h[b]=1 print(i,sep=' ',end=' ') i+=1 <file_sep>// https://codeforces.com/gym/101191/problem/F // https://codeforces.com/gym/101191/submission/47884686 #include <iostream> #include <string> using namespace std; inline unsigned int DoSum(long long Number) { unsigned int sum = 0; for (; Number != 0; Number /= 10) { sum += (Number % 10); } return sum; } long long Solve(std::string& original) { std::string str = ""; long long target = std::stoll(original); unsigned int sum = DoSum(target); unsigned int no9 = sum / 9; unsigned int rem = sum % 9; str.push_back(rem + '0'); for (unsigned int i = 1; i <= no9; ++i) str.push_back('9'); if (std::stoll(str) != target && std::stoll(str) <= 1e9) { return std::stoll(str); } while (str.size() < 3) str.push_back('0'); swap(str[0], str[1]); if (std::stoll(str) != target && std::stoll(str) <= 1e9) { return std::stoll(str); } swap(str[0], str[1]); str.insert(str.begin() + 1, '0'); if (std::stoll(str) != target && std::stoll(str) <= 1e9) { return std::stoll(str); } str.erase(str.begin() + 1); str.insert(str.begin() + 2, '0'); if (std::stoll(str) != target && std::stoll(str) <= 1e9) { return std::stoll(str); } return -1; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); string init; cin >> init; cout << Solve(init); return 0; }<file_sep># https://codeforces.com/contest/479/problem/A # https://codeforces.com/contest/479/submission/13613997 a = int(input()) b = int(input()) c = int(input()) if a==1: b=b+1 if b==1: if a<c: a=a+1 else: c=c+1 if c==1: b=b+1 print(a*b*c) <file_sep>// https://codeforces.com/contest/727/problem/A // https://codeforces.com/contest/727/submission/21693330 #include <iostream> using namespace std; bool sols = false; long long sol[100]; long long a, b; void printSol(int k) { cout << "YES\n" << k + 1 << "\n"; cout << a << " "; for (int i = 0; i < k; ++i) cout << sol[i] << " "; } void rec(long long a, long long b, int k) { if (a < b) { for (int i = 0; i < 2; i++) { if (i == 0) sol[k] = 2 * a; else sol[k] = 10 * a + 1; if (!sols) rec(sol[k], b, k + 1); } sol[k] = 0; } else if (a == b) { sols = true; printSol(k); } } int main() { cin >> a >> b; rec(a, b, 0); if (!sols) puts("NO\n"); return 0; }<file_sep>// https://codeforces.com/contest/546/problem/B // https://codeforces.com/contest/546/submission/17523253 #include <iostream> #include <algorithm> using namespace std; int main() { int n, s = 0, v[3002], x; memset(v, 0, 3002 * sizeof(int)); cin >> n; for (int i = 0; i < n; i++) { cin >> x; v[x]++; } for (int i = 1; i <= n; i++) { if (v[i] > 1) s += v[i] - 1, v[i + 1] += v[i] - 1; } s += v[n+1] * (v[n+1] - 1) / 2; cout << s; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/460/problem/A // https://codeforces.com/contest/460/submission/13875673 #include <stdio.h> #include <stdlib.h> int main() { int n,m,nr; scanf("%d",&n); scanf("%d",&m); nr = 0; while (n>0) { nr++; if (nr % m != 0){n--;} } printf("%d",nr); return 0; } <file_sep>// https://codeforces.com/contest/766/problem/D // https://codeforces.com/contest/766/submission/47708811 #include <iostream> #include <algorithm> #include <string> #include <vector> #include <map> using namespace std; int find(int x, vector<int>& parent) { if (x == parent[x]) return x; return parent[x] = find(parent[x], parent); } void uni(int x, int y, vector<int>& parent) { parent[min(x, y)] = max(x, y); } bool make_sin(int x, int y, vector<int>& sinonime, vector<int>& antonime) { auto sinX = find(x, sinonime); auto antX = find(antonime[sinX], sinonime); auto sinY = find(y, sinonime); auto antY = find(antonime[sinY], sinonime); if (sinX == antY || sinY == antX) return false; uni(sinX, sinY, sinonime); if (antX != 0 && antY != 0) uni(antX, antY, sinonime); antonime[max(sinX, sinY)] = max(antX, antY); return true; } bool make_ant(int x, int y, vector<int>& sinonime, vector<int>& antonime) { auto sinX = find(x, sinonime); auto antX = find(antonime[sinX], sinonime); auto sinY = find(y, sinonime); auto antY = find(antonime[sinY], sinonime); if (sinX == sinY || (antX == antY && antX != 0)) return false; if (antY != 0) sinonime[antY] = sinX; if (antX != 0) sinonime[antX] = sinY; antonime[sinX] = sinY; antonime[sinY] = sinX; return true; } bool make_rel(int r, int x, int y, vector<int>& sinonime, vector<int>& antonime) { return (r == 1) ? make_sin(x, y, sinonime, antonime) : make_ant(x, y, sinonime, antonime); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, m, q, r; string x, y; cin >> n >> m >> q; map<string, int> hash; vector<int> sinonime(n + 1, 0); vector<int> antonime(n + 1, 0); for (int i = 1; i <= n; ++i) { sinonime[i] = i; cin >> x; hash[x] = i; } for (int i = 1; i <= m; ++i) { cin >> r >> x >> y; (make_rel(r, hash[x], hash[y], sinonime, antonime)) ? cout << "YES\n" : cout << "NO\n"; } for (int i = 1; i <= q; ++i) { cin >> x >> y; auto px = hash[x]; auto py = hash[y]; auto ay = antonime[find(py, sinonime)]; if (find(px, sinonime) == find(py, sinonime)) cout << "1\n"; else if (find(px, sinonime) == find(ay, sinonime)) cout << "2\n"; else cout << "3\n"; } return 0; } #include <iostream> #include <algorithm> #include <string> #include <vector> #include <map> using namespace std; int find(int x, vector<int>& parent) { if (x == parent[x]) return x; return parent[x] = find(parent[x], parent); } bool make_sin(int x, int y, vector<int>& sinonime, vector<int>& antonime) { auto sinX = find(x, sinonime); auto antX = find(antonime[sinX], sinonime); auto sinY = find(y, sinonime); auto antY = find(antonime[sinY], sinonime); if (sinX == antY || sinY == antX) return false; sinonime[sinY] = sinX; antonime[sinX] = max(antX, antY); if (antX != 0 && antY != 0) sinonime[min(antX, antY)] = max(antX, antY); return true; } bool make_ant(int x, int y, vector<int>& sinonime, vector<int>& antonime) { auto sinX = find(x, sinonime); auto antX = find(antonime[sinX], sinonime); auto sinY = find(y, sinonime); auto antY = find(antonime[sinY], sinonime); if (sinX == sinY || (antX == antY && antX != 0)) return false; if (antY != 0) sinonime[antY] = sinX; if (antX != 0) sinonime[antX] = sinY; antonime[sinX] = sinY; antonime[sinY] = sinX; return true; } bool make_rel(int r, int x, int y, vector<int>& sinonime, vector<int>& antonime) { return (r == 1) ? make_sin(x, y, sinonime, antonime) : make_ant(x, y, sinonime, antonime); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, m, q, r; string x, y; cin >> n >> m >> q; map<string, int> hash; vector<int> sinonime(n + 1, 0); vector<int> antonime(n + 1, 0); for (int i = 1; i <= n; ++i) { sinonime[i] = i; cin >> x; hash[x] = i; } for (int i = 1; i <= m; ++i) { cin >> r >> x >> y; (make_rel(r, hash[x], hash[y], sinonime, antonime)) ? cout << "YES\n" : cout << "NO\n"; } for (int i = 1; i <= q; ++i) { cin >> x >> y; auto px = hash[x]; auto py = hash[y]; auto ay = antonime[find(py, sinonime)]; if (find(px, sinonime) == find(py, sinonime)) cout << "1\n"; else if (find(px, sinonime) == find(ay, sinonime)) cout << "2\n"; else cout << "3\n"; } return 0; }<file_sep>// https://codeforces.com/contest/447/problem/B // https://codeforces.com/contest/447/submission/18017766 #include <iostream> #include <string> using namespace std; int main() { string s; long long k, max = 0, sum = 0, v[26]; cin >> s >> k; for (size_t i = 0; i < 26; i++) { cin >> v[i]; if (v[i] > max) max = v[i]; } for (size_t i = 0; i < s.size(); i++) { sum += (v[s[i] - 'a']) * (i + 1); } for (size_t i = s.size() + 1; i <= s.size() + k; i++) { sum += max*i; } cout << sum; return EXIT_SUCCESS; }<file_sep># https://codeforces.com/contest/439/problem/A # https://codeforces.com/contest/439/submission/14449216 n, d = map(int,input().split()) l = list(map(int,input().split())) s = sum(l) if s+(n-1)*10 > d: print(-1) else: d = d-s print(d//5) <file_sep>// https://codeforces.com/contest/1037/problem/D // https://codeforces.com/contest/1037/submission/48033461 #include <iostream> #include <vector> #include <map> #include <set> #include <queue> #include <algorithm> using namespace std; bool CheckBfs(map<int, set<int>>& graph, vector<int>& bfs) { queue<int> q; size_t idx = 1; vector<bool> visited(graph.size() + 1, false); q.push(1); visited[1] = true; if (bfs[0] != 1) return false; while (idx < bfs.size()) { auto in = q.front(); q.pop(); set<int> toVisit; for (auto neighbour : graph[in]) { if (!visited[neighbour]) toVisit.insert(neighbour); } for (size_t i = 0; i < toVisit.size(); ++i) { if (idx == bfs.size()) return false; if (toVisit.find(bfs[idx]) == toVisit.end()) return false; if (visited[bfs[idx]]) return false; q.push(bfs[idx]); visited[bfs[idx]] = true; idx++; } } for (size_t i = 1; i < visited.size(); ++i) { if (!visited[i]) return false; } return true; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, x, y; vector<int> bfs; map<int, set<int>> graph; cin >> n; for (int i = 1; i < n; ++i) { cin >> x >> y; graph[x].insert(y); graph[y].insert(x); } for (int i = 1; i <= n; ++i) { cin >> x; bfs.push_back(x); } CheckBfs(graph, bfs) ? cout << "Yes\n" : cout << "No\n"; return 0; }<file_sep>// https://codeforces.com/contest/777/problem/B // https://codeforces.com/contest/777/submission/24969556 #include <iostream> #include <string> #include <algorithm> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr), cout.tie(nullptr); int n; string a, b; cin >> n >> a >> b; int fS[10] = { 0 }; int fM[10] = { 0 }; int fMax[10] = { 0 }; for (auto c : a) fS[c - '0']++, fM[c-'0']++; for (auto c : b) fM[c - '0']--, fMax[c - '0']++; auto res = 0; auto flicks = 0; for(auto i = 9; i >= 0; --i) { if (fM[i] < 0) res += (-1 * fM[i]); else { if (res >= fM[i]) res -= fM[i]; else { fM[i] -= res; res = 0; flicks += fM[i]; } } } cout << flicks << "\n"; res = fMax[9]; flicks = 0; for(auto i = 8; i>= 0; --i) { if (res >= fS[i]) { flicks += fS[i]; res -= fS[i]; } else { flicks += res; res = 0; } res += fMax[i]; } cout << flicks; return 0; }<file_sep># https://codeforces.com/contest/110/problem/A # https://codeforces.com/contest/110/submission/13477477 def is_lucky(a): """ Check if a given number (a) is lucky. @input: an integer a (1<=a<=10^18) @output: True - if a is lucky False - if a is not lucky """ if a==0: ok=False else: ok=True # We assume that a is lucky while (a>0 and ok==True): if (int(a%10) == 4 or int(a%10) == 7): a=a//10 else: ok=False return ok def nearly_lucky(n): """ Check if a given number (n) is nearly lucky. @input: an integer n (1<=n<=10^18) @output: True - if n is nearly lucky False - if n is not nearly lucky """ ok=False nr=0 while n>0: if is_lucky(n%10)==True: nr+=1 n=n//10 if is_lucky(nr)==True: ok=True return(ok) def citire(): """ Read an integer. @output: an integer n (1<=n<=10^18) """ return int(input()) n=citire() #read n if (nearly_lucky(n)==True): print("YES") else: print("NO") <file_sep>// https://codeforces.com/contest/651/problem/A // https://codeforces.com/contest/651/submission/17366362 #include <iostream> int main() { int cont, a, b; std::cin >> a >> b; if (a == b && b == 1) a = 0; for (cont = 0; a != 0 && b != 0; cont++) { if (a > b) a -= 2, b++; else a++, b -= 2; } std::cout << cont; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/463/problem/B // https://codeforces.com/contest/463/submission/17433406 #include <iostream> using namespace std; int main() { int n, x, sum = 0, h = 0, e = 0; cin >> n; for (; n > 0; n--) { cin >> x; e += h - x; if (e < 0) { sum += -e, e = 0; } h = x; } cout << sum; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/552/problem/B // https://codeforces.com/contest/552/submission/16639895 #include <iostream> using namespace std; int main() { unsigned long long v[12], pow10[12], n, nein = 9, i ; cin >> n; v[0] = 0; pow10[0] = 1; for (i = 1; i <= 11; i++) { v[i] = i * nein + v[i - 1]; nein *= 10; pow10[i] = 10 * pow10[i - 1]; } for (i = 1; pow10[i] <= n; i++); cout << v[i - 1] + (n - pow10[i-1] + 1) * i; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/problemset/problem/987/A // https://codeforces.com/contest/987/submission/68116433 #include <vector> #include <string> #include <map> #include <iostream> using namespace std; int main() { int n; string s; map<string, string> needed = { {"purple", "Power"}, {"green", "Time"}, {"blue", "Space"}, {"orange", "Soul"}, {"red", "Reality"}, {"yellow", "Mind"} }; cin >> n; for (int i = 0; i < n; ++i) { cin >> s; needed.erase(s); } cout << needed.size() << std::endl; for (const auto& keyValuePair : needed) { cout << keyValuePair.second << std::endl; } return 0; }<file_sep># https://codeforces.com/contest/785/problem/C # https://codeforces.com/contest/785/submission/25529811 n,m = map(int,input().split()) def binSearch(n,m): lo = 1 hi = n p = -1 S = 0 while(lo <= hi): k = (lo + hi) // 2 S = ((k-1)* (k+2)) // 2 S += m + 1 if (n - S > 0): lo = k + 1 else: p = k hi = k - 1 return p if (m>=n): print(n) else: print(m + binSearch(n,m))<file_sep>// https://codeforces.com/contest/465/problem/B // https://codeforces.com/contest/465/submission/18017411 #include <iostream> using namespace std; int main() { int n, x = 0, t = 0, i = 0; bool ok1 = false, ok2 = false; cin >> n; while (i < n && x == 0) cin >> x, i++; if (x == 1) t++; while (i < n) { cin >> x; i++; if (x == 1) { t++; if (ok1 == true) t++; ok1 = false; ok2 = false; } else if (x == 0 && ok1 == false) ok1 = true; else if (x == 0 && ok1 == true && ok2 == false) ok2 = true; } cout << t; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/466/problem/C // https://codeforces.com/contest/466/submission/47156701 #include <iostream> #include <vector> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(NULL); int n = 0; long long s = 0, s_23 = 0, s_13 = 0; unsigned long long n1 = 0, n2 = 0, nr = 0; cin >> n; vector<long long> v(n + 1, 0); for (int i = 1; i <= n; ++i) { cin >> v[i]; v[i] += v[i - 1]; } s = v[n]; s_13 = v[n] / 3; s_23 = 2 * s_13; if (s % 3 != 0) { cout << 0; return 0; } for (int i = 1; i < n; ++i) { if (v[i] == s_23) { n2++; nr = nr + n1; } if (v[i] == s_13) { n1++; } } cout << nr; return 0; }<file_sep># https://codeforces.com/contest/236/problem/A # https://codeforces.com/contest/236/submission/13420128 dict={'a':0, 'b':0, 'c':0, 'd':0, 'e':0, 'f':0, 'g':0, 'h':0, 'i':0, 'j':0, 'k':0, 'l':0, 'm':0, 'n':0, 'o':0, 'p':0, 'q':0, 'r':0, 's':0, 't':0, 'u':0, 'v':0 , 'w':0, 'x':0, 'y':0, 'z':0} s=input() nr=0 for i in range(len(s)): dict[s[i]]+=1 if dict[s[i]]==1: nr+=1 if (int(nr%2)==0): print("CHAT WITH HER!") else: print("IGNORE HIM!") <file_sep>// https://codeforces.com/contest/988/problem/A // https://codeforces.com/contest/988/submission/46797091 #include <iostream> #include <map> using namespace std; int main() { int n, k, x; map<int, int> mp; cin >> n >> k; for (int i = 1; i <= n; ++i) { cin >> x; mp[x] = i; } if (mp.size() < k) cout << "NO"; else { cout << "YES\n"; for (const auto& p : mp) { cout << p.second << " "; if (--k == 0) break; } } return 0; }<file_sep>// https://codeforces.com/contest/606/problem/A // https://codeforces.com/contest/606/submission/17916507 #include <iostream> using namespace std; int main() { int a[3], v[3], n = 0, s = 0; cin >> a[0] >> a[1] >> a[2] >> v[0] >> v[1] >> v[2]; for (int i = 0; i < 3; i++) { if (a[i] > v[i]) s += (a[i] - v[i]) / 2; else n += v[i] - a[i]; } (s >= n) ? puts("Yes") : puts("No"); return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/38/problem/A // https://codeforces.com/contest/38/submission/17147878 #include <iostream> using namespace std; int main(){ int v[101], x, n; cin >> n; v[1] = 0; for (int i = 2; i <= n; i++) { cin >> x; v[i] = v[i - 1] + x; } cin >> x >> n; cout << v[n] - v[x]; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/678/problem/B // https://codeforces.com/contest/678/submission/21700809 #include <iostream> using namespace std; bool is_leap(int x) { return (x % 400 == 0 || (x % 4 == 0 && x % 100 != 0)); } int main() { int x; bool leap; bool sol = false; bool leapY; cin >> x; leap = is_leap(x); int day = 0; while (!sol) { x++; leapY = is_leap(x); (leapY) ? day += 2 : day += 1; day %= 7; if (day == 0) { if (leapY == leap) sol = true; } } cout << x; return 0; }<file_sep>// https://codeforces.com/contest/723/problem/B // https://codeforces.com/contest/723/submission/21321513 #include <stdio.h> #include <stdlib.h> int main() { int n; char str[255]; scanf("%d", &n); scanf("%s", &str); int out = 1; int i = -1; int wordLen = 0, wordIn = 0, maxLenOut = 0; while (++i < n) { if (str[i] == '(') { if (wordLen > maxLenOut) { maxLenOut = wordLen; } out = 0; wordLen = 0; } else if (str[i] == ')') { if (wordLen > 0) { wordIn++; } out = 1; wordLen = 0; } else if (str[i] == '_') { if (out == 1) { if (wordLen > maxLenOut) { maxLenOut = wordLen; } } else if (wordLen > 0) { wordIn++; } wordLen = 0; } else { wordLen++; } } if (wordLen > maxLenOut) { maxLenOut = wordLen; } printf("%d %d", maxLenOut, wordIn); return 0; }<file_sep># https://codeforces.com/contest/148/problem/A # https://codeforces.com/contest/148/submission/13473365 a=[] for i in range(4): x=int(input()) a.append(x) n=int(input()) v=[] for i in range(n+1): v.append(0) for i in range(4): aux=a[i] while a[i]<n+1: v[a[i]]=1 a[i]+=aux nr=0 for i in range(1,n+1): if v[i]==1: nr+=1 print(nr) <file_sep>// https://codeforces.com/contest/381/problem/A // https://codeforces.com/contest/381/submission/17434256 #include <iostream> using namespace std; int main() { int v[1001], n, Sereja = 0, Dima = 0; cin >> n; for (int i = 0; i < n; i++) cin >> v[i]; for (int c = 0, j = n - 1, i = 0; i <= j;) { if (c == 0) { if (v[i] > v[j]) Sereja += v[i], i++; else Sereja += v[j], j--; c = 1; } else { if (v[i] > v[j]) Dima += v[i], i++; else Dima += v[j], j--; c = 0; } } cout << Sereja << " " << Dima << endl; return EXIT_SUCCESS; } <file_sep>// https://codeforces.com/contest/678/problem/C // https://codeforces.com/contest/678/submission/18421949 #include <iostream> #include <algorithm> using namespace std; long long gcd(const long long& a, const long long& b) { if (b == 0) return a; return gcd(b, a%b); } int main() { long long n, a, b, p, q, lcm, nra, nrb, nrc; cin >> n>> a >> b >> p >> q; lcm = (a*b) / gcd(a, b); nrc = n / lcm; nra = n / a - nrc; nrb = n / b - nrc; cout << nrc * max(p, q) + nra * p + nrb * q; return 0; }<file_sep># https://codeforces.com/contest/214/problem/A # https://codeforces.com/contest/214/submission/14926990 n,m = map(int,input().split()) nr = 0 for i in range(1001): for j in range(1001): if i*i + j == n and i + j*j == m: nr += 1 print(nr) <file_sep>// https://codeforces.com/contest/746/problem/C // https://codeforces.com/contest/746/submission/23095903 #include <iostream> #include <algorithm> using namespace std; int main() { int Sursa, igorPos, igorDest, vitezaIgor, vitezaTren, trenPos, directieTren, directieIgor; cin >> Sursa >> igorPos >> igorDest >> vitezaTren >> vitezaIgor >> trenPos >> directieTren; if (igorPos > igorDest) directieIgor = -1; else directieIgor = 1; int igorTime = abs(igorPos - igorDest) * vitezaIgor; int trainTime = 0; if (directieTren == 1 && directieIgor == -1) { trainTime += abs(trenPos - Sursa) * vitezaTren; trainTime += abs(Sursa - igorDest) * vitezaTren; } else if (directieTren == -1 && directieIgor == 1) { trainTime += trenPos * vitezaTren; trainTime += igorDest * vitezaTren; } else if (directieTren == 1 && directieIgor == 1 && igorPos < trenPos) { trainTime += abs(trenPos - Sursa) * vitezaTren; trainTime += Sursa * vitezaTren; trainTime += igorDest * vitezaTren; } else if (directieTren == -1 && directieIgor == -1 && igorPos > trenPos) { trainTime += trenPos * vitezaTren; trainTime += Sursa * vitezaTren; trainTime += abs(Sursa - igorDest) * vitezaTren; } else { trainTime += abs(trenPos - igorDest) * vitezaTren; } cout << min(trainTime, igorTime); return 0; }<file_sep>// https://codeforces.com/contest/676/problem/A // https://codeforces.com/contest/676/submission/18780987 #ifndef _CRT_NONSTDC_NO_WARNINGS #define _CRT_NONSTDC_NO_WARNINGS #include <cstdio> #include <cstdlib> #include <iostream> #include <string> #include <cmath> #include <algorithm> #include <vector> using namespace std; int main() { int n, poz1, pozn, i, x; for (scanf("%d", &n), i = 1; i <= n; ++i) { scanf("%d", &x); if (x == 1) poz1 = i; else if (x == n) pozn = i; } printf("%d", max(max(abs(1 - poz1), abs(n - poz1)), max(abs(1 - pozn), abs(n - pozn)))); return EXIT_SUCCESS; } #endif //_CRT_NONSTDC_NO_WARNINGS<file_sep>// https://codeforces.com/contest/735/problem/B // https://codeforces.com/contest/735/submission/22540632 #include <iostream> #include <algorithm> #include <vector> #include <cstdio> using namespace std; bool cmp(int a, int b) { return b < a; } int main() { int n, m, k; double s1a, s1b, s2a, s2b; scanf("%d %d %d", &n, &m, &k); vector<int> v(n, 0); for (int i = 0; i < n; ++i) { scanf("%d", &v[i]); } s1a = s1b = s2a = s2b = 0; sort(v.begin(), v.end(), cmp); for (int i = 0; i < m; ++i) s1a += v[i]; for (int i = m, q = k; q > 0; q--, i++) s1b += v[i]; for (int i = 0; i < k; ++i) s2a += v[i]; for (int i = k, q = m; q > 0; q--, i++) s2b += v[i]; double s1 = s1a / m + s1b / k; double s2 = s2a / k + s2b / m; printf("%.7lf",max(s1, s2)); return 0; }<file_sep>// https://codeforces.com/contest/1281/problem/A // https://codeforces.com/contest/1281/submission/67973469 #include <iostream> #include <string> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cerr.tie(nullptr); int queries = 0; string s; cin >> queries; while (queries--) { cin >> s; switch (s.back()) { case 'o': cout << "FILIPINO\n"; break; case 'a': cout << "KOREAN\n"; break; default: cout << "JAPANESE\n"; break; } } return 0; }<file_sep>// https://codeforces.com/contest/743/problem/C // https://codeforces.com/contest/743/submission/22980441 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <math.h> #include <algorithm> #include <iostream> using namespace std; int main() { int n; scanf("%d", &n); if (n == 1) puts("-1"); else printf("%d %d %d", n, n + 1, n*(n + 1)); return 0; } <file_sep># https://codeforces.com/contest/466/problem/A # https://codeforces.com/contest/466/submission/14009138 n,m,a,b=map(int,input().split()) if m>n: m=n if m%n==0: rez=0 else: rez=1 var1=a*n impr=int(n/m) var2=((impr+rez)*b) pcs=(n-(impr*m)) var3=(impr*b+(pcs*a)) print(min(var1,var2,var3)) <file_sep>// https://codeforces.com/contest/681/problem/C // https://codeforces.com/contest/681/submission/18480382 #include <iostream> #include <stdio.h> #include <string> #include <functional> #include <queue> using namespace std; int main() { string s; vector<pair<string, int>> rez; priority_queue<int, vector<int>, greater<int>> head; int n, value; for (cin >> n; n > 0; n--) { cin >> s; if (s == "removeMin") { if (head.empty()) { rez.push_back({ "insert ", 1 }); rez.push_back({ "removeMin ", 0 }); } else { head.pop(); rez.push_back({ "removeMin ", 0 }); } } else if (s == "insert") { cin >> value; head.push(value); rez.push_back({ "insert ", value }); } else { cin >> value; if (head.empty()) { rez.push_back({ "insert ", value }); head.push(value); rez.push_back({ "getMin ", value }); } else { while ( !head.empty() && head.top() < value) { rez.push_back({ "removeMin ", 0 }); head.pop(); } if (head.empty() || head.top() > value) { rez.push_back({ "insert ", value }); head.push(value); } rez.push_back({ "getMin ", value }); } } } cout << rez.size() << "\n"; for (const auto& el : rez) { cout << el.first; if (el.first != "removeMin ") cout << el.second; cout << '\n'; } return EXIT_SUCCESS; }<file_sep>// https://www.spoj.com/problems/FCTRL/ #include <iostream> #include <fstream> #include <chrono> #include <iomanip> #include <algorithm> #include <string> #include <vector> #include <map> #include <set> #include <queue> #include <numeric> #include <bitset> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cerr.tie(nullptr); int T = 0; unsigned long long N = 0; unsigned long long Result = 0; cin >> T; while (T--) { cin >> N; Result = 0; for (unsigned long long S = 5; S <= N; S *= 5) { Result += (N / S); } cout << Result << "\n"; } return 0; }<file_sep># https://codeforces.com/contest/112/problem/A # https://codeforces.com/contest/112/submission/13407948 s1=input() s2=input() if s1.lower()==s2.lower(): print("0") elif s1.lower()<s2.lower(): print("-1") else: print("1") <file_sep># https://codeforces.com/contest/546/problem/A # https://codeforces.com/contest/546/submission/13588873 n,m,k=map(int,input().split()) if ((((n+(n*k))*k)//2)-m > 0): print((((n+(n*k))*k)//2)-m) else: print(0) <file_sep>// https://codeforces.com/contest/545/problem/A // https://codeforces.com/contest/545/submission/17418609 #include <iostream> using namespace std; int main() { int n, v[101], k = 0, x; bool ok; cin >> n; for (int i = 1; i <= n; i++) { ok = true; for (int j = 1; j <= n; j++) { cin >> x; if (x == 1 || x==3) ok = false; } if (ok) {k++; v[k] = i;} } cout << k << endl; for (int i = 1; i <= k; i++)cout << v[i] << " "; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/520/problem/A // https://codeforces.com/contest/520/submission/13876957 #include <stdio.h> #include <stdlib.h> int main() { int v[30],n,i,cord; char c; scanf("%d\n",&n); for (i=1;i<=n;i++) { scanf("%c",&c); cord = c; if (cord<97) { v[cord-65]=1; } else { v[cord-97]=1; } } cord = 1; for (i=0;i<=25;i++) { if (v[i]!=1) { cord = -1; } } if (cord == -1 ){printf("NO");} else {printf("YES");} return 0; } <file_sep>// https://codeforces.com/contest/746/problem/A // https://codeforces.com/contest/746/submission/23082946 #include <iostream> #include <stdio.h> #include <algorithm> using namespace std; int main() { int a, b, c, ans; scanf("%d %d %d", &a, &b, &c); b = b / 2; c = c / 4; ans = min(a, min(b, c)); printf("%d", ans + ans*2 + ans*4); return 0; }<file_sep># https://codeforces.com/contest/228/problem/A # https://codeforces.com/contest/228/submission/13960789 l = list(map(int,input().split())) a = set(l) print(4-len(a)) <file_sep>// https://codeforces.com/contest/791/problem/A // https://codeforces.com/contest/791/submission/25610192 #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <map> #include <unordered_map> #include <set> #include <vector> #include <cstdio> #include <string> using namespace std; #define ll long long #define ull unsigned long long /*------------------------------------------------------------------*/ int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); int a, b; ll k = 1, ans = 0, pw2 = 1, pw3 = 1; cin >> a >> b; while (!ans) { pw2 *= 2; pw3 *= 3; if (a * pw3 <= b * pw2) k++; else ans = k; } cout << ans; return 0; }<file_sep>// https://codeforces.com/contest/706/problem/B // https://codeforces.com/contest/706/submission/46624969 #include <iostream> #include <vector> #include <algorithm> using namespace std; int Find(const vector<int>& V, int X) { int lo = 0; int hi = V.size() - 1; int m = 0; int found = -1; while (lo <= hi) { m = (lo + hi) / 2; if (V[m] > X) hi = m - 1; else found = m, lo = m + 1; } return found; } int main() { int n, d, x; cin >> n; vector<int> v(n, 0); for (int i = 0; i < n; ++i) cin >> v[i]; sort(v.begin(), v.end()); cin >> d; while (d--) { cin >> x; cout << Find(v, x) + 1 << "\n"; } return 0; }<file_sep># https://codeforces.com/contest/467/problem/B # https://codeforces.com/contest/467/submission/14468665 n,m,k = map(int,input().split()) l = [] while (m+1>0): x = int(input()) l.append(x) m-=1 nr = 0 for i in range (len(l)-1): c = l[i]^l[len(l)-1] if bin(c).count("1")<=k: nr+=1 print(nr) <file_sep>#include <iostream> #include <string> #include <vector> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); string on; bool ok = false; vector<string> hand(5); cin >> on; for (size_t i = 0; i < hand.size(); ++i) cin >> hand[i]; for (const auto& h : hand) { ok = ok || h[0] == on[0] || h[1] == on[1]; } (ok) ? cout << "YES\n" : cout << "NO\n"; return 0; } <file_sep># https://codeforces.com/contest/588/problem/A # https://codeforces.com/contest/588/submission/14543201 n = int(input()) a, kilo =map(int,input().split()) s = kilo*a while n-1>0: a,b = map(int,input().split()) if b<kilo: kilo = b s += kilo*a n -= 1 print(s) <file_sep>// https://codeforces.com/contest/747/problem/A // https://codeforces.com/contest/747/submission/23259014 #include <iostream> #include <algorithm> using namespace std; int main() { int n; int mxa, mxb, mx; cin >> n; mxa = 1; mxb = n; mx = n - 1; for (int i = 2; i < n; ++i) { if (n % i == 0) { if (abs(n / i - i) < mx) { mx = abs(n / i - i); mxa = min(n / i, i); mxb = max(n / i, i); } } } cout << mxa << " " << mxb; return 0; }<file_sep>// https://codeforces.com/contest/1030/problem/A // https://codeforces.com/contest/1030/submission/46625301 #include <iostream> using namespace std; int main() { int n; bool res = false, b = false; cin >> n; for(int i = 0; i < n; i++) { cin >> b; res = res || b; } res ? cout << "hard" : cout << "easy"; return 0; }<file_sep>// https://codeforces.com/contest/789/problem/C // https://codeforces.com/contest/789/submission/25930865 #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <map> #include <unordered_map> #include <set> #include <vector> #include <cstdio> #include <string> using namespace std; #define ll long long #define ull unsigned long long /*------------------------------------------------------------------*/ int n; long long v[100004]; vector<long long> pare, impare; long long sum(vector<long long>& vc) { long long sumMax = 0; long long sumCur = 0; long long c = 0; for(size_t i = 0; i < vc.size(); ++i) { sumCur += vc[i]; sumMax = max(sumMax, sumCur); sumCur = max(c, sumCur); } return sumMax; } int main() { ios_base::sync_with_stdio(false) , cin.tie(nullptr) , cout.tie(nullptr); cin >> n; for (int i = 1; i <= n; ++i) cin >> v[i]; for(int i = 1; i<=n-1; ++i) { if (i & 1) impare.push_back(abs(v[i] - v[i + 1])); else impare.push_back(-abs(v[i] - v[i + 1])); } for(int i = 2; i<=n-1; ++i) { if (i & 1) pare.push_back(-abs(v[i] - v[i + 1])); else pare.push_back(abs(v[i] - v[i + 1])); } cout << max(sum(pare), sum(impare)); return 0; } <file_sep>// https://codeforces.com/contest/339/problem/D // https://codeforces.com/contest/339/submission/25572718 #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <stdio.h> #include <algorithm> #include <vector> #include <map> #include <string> using namespace std; #define ll long long #define ull unsigned long long /*--------------------------------------------------------------------------------------*/ typedef struct node { ll value; bool xorField; node() { value = 0; xorField = true; } }node; const int MAXN = 1 << 18; node arb[4 * MAXN + 66]; int n, m; void update(int node, int start, int end, int& pos, ll& val) { if (start == end) { arb[node].value = val; arb[node].xorField = true; return; } int mid = (start + end) / 2; if (pos <= mid) update(node * 2, start, mid, pos, val); else update(node * 2 + 1, mid + 1, end, pos, val); arb[node].xorField = !arb[node * 2].xorField; if (arb[node].xorField) arb[node].value = arb[node * 2].value ^ arb[node * 2 + 1].value; else arb[node].value = arb[node * 2].value | arb[node * 2 + 1].value; } int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); scanf("%d", &n); scanf("%d", &m); ll x; n = 1 << n; for (int i = 1; i <= n; ++i) { scanf("%I64d", &x); update(1, 1, n, i, x); } int pos; for (int i = 1; i <= m; ++i) { scanf("%d %I64d", &pos, &x); update(1, 1, n, pos, x); printf("%I64d\n", arb[1].value); } return 0; } <file_sep>// https://codeforces.com/contest/766/problem/A // https://codeforces.com/contest/766/submission/28727945 #include <iostream> #include <string> using namespace std; int main() { string a, b; cin>>a>>b; if( a == b) cout<<"-1"; else cout<<max(a.size(), b.size()); return 0; } <file_sep>// https://codeforces.com/contest/777/problem/D // https://codeforces.com/contest/777/submission/24971940 #include <iostream> #include <string> #include <vector> using namespace std; int main() { ios::sync_with_stdio(false); int n, j, sz1, sz2; string curr,s,prec; vector<string> v; vector<string> sol; cin >> n; for(auto i = 0; i < n; ++i) { cin >> s; v.push_back(s); } sol.push_back(v[n - 1]); for(auto i = n - 2; i>= 0; --i) { prec = sol.back(); curr = v[i]; sz1 = prec.size(); sz2 = curr.size(); for (j = 0; j < sz1 && j < sz2 && prec[j] == curr[j]; j++); if (j < sz1 && j < sz2 && prec[j] > curr[j]) j = sz2; sol.push_back(curr.substr(0, j)); } for (auto i = n - 1; i >= 0; --i)cout << sol[i] << "\n"; return 0; }<file_sep>// https://codeforces.com/problemset/problem/919/B // https://codeforces.com/contest/919/submission/49355568 #include <iostream> #include <fstream> #include <chrono> #include <iomanip> #include <algorithm> #include <string> #include <vector> #include <map> #include <set> #include <queue> #include <numeric> #include <bitset> using namespace std; vector<long long> Compute() { long long current = 19; vector<long long> result; while (result.size() < 10000) { int sum = 0; for (auto c = current; c > 0; c = c / 10) sum += (c % 10); if (sum == 10) result.push_back(current); current++; } return result; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cerr.tie(nullptr); auto all = Compute(); int k; cin >> k; cout << all[k - 1]; return 0; }<file_sep>// https://codeforces.com/contest/592/problem/A // https://codeforces.com/contest/592/submission/13993887 #include <iostream> using namespace std; char s[10][10]; int minb=9,minw=9,p; int calc_min(int el, int i, int j) { int m=9; if (el=='B') { for(int k=i+1;k<=8;k++) { if (s[k][j]!='.'){return m;} } return 8-i; } else { for(int k=i-1;k>=1;k--) { if (s[k][j]!='.'){return m;} } return i-1; } } int main() { for (int i=1;i<=8;i++) { for (int j=1;j<=8;j++) { cin>>s[i][j]; } } for (int i=1;i<=8;i++) { for (int j=1;j<=8;j++) { if (s[i][j]!='.'){p=calc_min(s[i][j],i,j);} if ((s[i][j]=='B')&&(p<minb)) { minb=p; } if ((s[i][j]=='W')&&(p<minw)) { minw=p; } } } if (minb<minw){cout<<'B';} else{cout<<'A';} return 0; } <file_sep># https://codeforces.com/contest/451/problem/A # https://codeforces.com/contest/451/submission/13960967 n,m=map(int,input().split()) if (n==1) or (m==1): rez=1; else: if (n>m): diff=m else: diff=n if diff%2==0: rez=0 else: rez=1 if rez==0: print("Malvika") else: print("Akshat") <file_sep>// https://codeforces.com/contest/604/problem/A // https://codeforces.com/contest/604/submission/17336525 #include <iostream> #include <algorithm> using namespace std; int main() { int m1, m2, m3, m4, m5, w1, w2, w3, w4, w5, s, u; double sm = 0; cin >> m1 >> m2 >> m3 >> m4 >> m5 >> w1 >> w2 >> w3 >> w4 >> w5 >> s >> u; sm += max(0.3 * 500, (1 - m1 / 250.0) * 500 - 50.0 * w1) + max(0.3 * 1000, (1 - m2 / 250.0) * 1000 - 50.0 * w2) + max(0.3 * 1500, (1 - m3 / 250.0) * 1500 - 50.0 * w3) + max(0.3 * 2000, (1 - m4 / 250.0) * 2000 - 50.0 * w4) + max(0.3 * 2500, (1 - m5 / 250.0) * 2500 - 50.0 * w5) + s * 100 - u * 50; cout << int(sm); } <file_sep># https://codeforces.com/contest/469/problem/A # https://codeforces.com/contest/469/submission/13960730 n=int(input()) l=list(map(int,input().split())) l1=list(map(int,input().split())) lc=[] for _ in range(0,n+1): lc.append(0) for i in range(1,len(l)): lc[l[i]]=1 for i in range (1,len(l1)): lc[l1[i]]=1 ok = 0 for i in range(1,n+1): if lc[i]!=1: print('Oh, my keyboard!') ok = 1; break if ok == 0: print('I become the guy.') <file_sep># https://codeforces.com/contest/459/problem/A # https://codeforces.com/contest/459/submission/14411162 x1,y1,x2,y2 = map(int,input().split()) if x1 == x2: l = abs(y2-y1) if x1+l>1000: l=-l x3 = x4 = x1+l print(x3,y1,x4,y2) elif y1==y2: l = abs(x2-x1) if y1+l>1000: l = -l y3 = y4 = y1+l print(x1,y3,x2,y4) else: if abs(y2-y1)!=abs(x2-x1): print(-1) else: print(x1,y2,x2,y1) <file_sep>// https://codeforces.com/contest/732/problem/A // https://codeforces.com/contest/732/submission/21642425 #include <stdio.h> #include <stdlib.h> int main() { int k, r, rz; scanf("%d %d", &k, &r); for (int i = 1; i <= 10; ++i) { rz = i * k; if (rz % 10 == 0 || (rz - r) % 10 == 0) { printf("%d", i); break; } } return EXIT_SUCCESS; }<file_sep>// https://www.spoj.com/problems/BGSHOOT/ #include <vector> #include <iostream> #include <map> #include <set> #include <algorithm> using namespace std; class SegmentedTree { public: SegmentedTree(const vector<int>& Array) : arraySize{Array.size()}, tree(Array.size() * 4 + 4, 0) { Build(Array, 1, 0, arraySize - 1); } int Query(size_t Low, size_t High) { return Query(1, 0, arraySize - 1, Low, High); } ~SegmentedTree() = default; private: void Build(const vector<int>& Array, size_t Node, size_t Start, size_t End) { if (Start == End) { tree[Node] = Array[Start]; return; } int mid = (Start + End) / 2; Build(Array, Node * 2, Start, mid); Build(Array, Node * 2 + 1, mid + 1, End); tree[Node] = max(tree[Node * 2], tree[Node * 2 + 1]); } int Query(size_t Node, size_t Start, size_t End, size_t Low, size_t High) { if (Low > End || High < Start) { return numeric_limits<int>::min(); } if (Start >= Low && End <= High) { return tree[Node]; } size_t mid = (Start + End) / 2; auto left = Query(Node * 2, Start, mid, Low, High); auto right = Query(Node * 2 + 1, mid + 1, End, Low, High); return max(left, right); } vector<int> tree; size_t arraySize; }; vector<pair<int, int>> ReadPairs() { int noPairs; cin >> noPairs; vector<pair<int, int>> pairs(noPairs); for (int i = 0; i < noPairs; ++i) { cin >> pairs[i].first >> pairs[i].second; } return pairs; } map<int, int> CoordinateCompression(const vector<pair<int, int>>& Data, const vector<pair<int, int>>& Queries) { set<int> uniques; map<int, int> compression; for (const auto& d : Data) { uniques.insert(d.first); uniques.insert(d.second); } for (const auto& q : Queries) { uniques.insert(q.first); uniques.insert(q.second); } int noElements = 0; for (const auto& u : uniques) { compression[u] = noElements++; } return compression; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); auto data = ReadPairs(); auto queries = ReadPairs(); auto compressed = CoordinateCompression(data, queries); vector<int> arr(compressed.size() + 1, 0); for (const auto& d : data) { arr[compressed[d.first]]++; arr[compressed[d.second] + 1]--; } for (size_t i = 1; i < arr.size(); ++i) { arr[i] += arr[i - 1]; } SegmentedTree tree(arr); for (const auto& q : queries) { auto x = compressed[q.first]; auto y = compressed[q.second]; cout << tree.Query(x, y) << "\n"; } return 0; }<file_sep># https://codeforces.com/contest/527/problem/A # https://codeforces.com/contest/527/submission/14458555 a,b = map(int,input().split()) s = 0 while a%b!=0: s+= a//b a,b = max(a%b,b),min(a%b,b) s+=a//b print(s) <file_sep>// https://codeforces.com/contest/84/problem/A // https://codeforces.com/contest/84/submission/18009090 #include <iostream> using namespace std; int main() { int n; cin >> n; cout << 3 * (n / 2); return EXIT_SUCCESS; }<file_sep># https://codeforces.com/contest/118/problem/A # https://codeforces.com/contest/118/submission/13405524 s=input() i=0 s2="" vowellist=['a','e','i','o','u','y'] while (i<len(s)): if s[i].lower() not in vowellist: s2=s2+"."+s[i] i+=1 print(s2.lower()) <file_sep>// https://codeforces.com/problemset/problem/1005/A // https://codeforces.com/contest/1005/submission/48101104 #include <vector> #include <iostream> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); vector<int> res; int n, x, curr = 1; cin >> n >> x; for (int i = 2; i <= n; ++i) { cin >> x; if (x == 1) { res.push_back(curr); curr = 0; } ++curr; } res.push_back(curr); cout << res.size() << "\n"; for (auto& c : res) cout << c << " "; return 0; }<file_sep>// https://codeforces.com/contest/706/problem/A // https://codeforces.com/contest/706/submission/22852236 #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <algorithm> #include <stdio.h> #include <limits> #include <cmath> using namespace std; inline double distance(int ax, int ay, int bx, int by) { return sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by)); } int main() { int vx, vy, n, bx, by, vb; double mx = numeric_limits<double>::max(); double time; scanf("%d %d %d", &vx, &vy, &n); while (n--) { scanf("%d %d %d", &bx, &by, &vb); time = (distance(vx, vy, bx, by)) / vb; if (mx > time) mx = time; } printf("%.10lf\n", mx); return 0; }<file_sep>// https://codeforces.com/contest/356/problem/A // https://codeforces.com/contest/356/submission/25574265 #include <iostream> using namespace std; const int MAXN = 300009; int tata[MAXN]; int beatenBy[MAXN]; int n, m; int find(int x) { if (x == tata[x]) return x; return tata[x] = find(tata[x]); } int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); cin >> n >> m; for(int i = 1; i<=n; ++i) { beatenBy[i] = 0; tata[i] = i; } tata[n + 1] = n + 1; int l, r, winner,sef; for(int i = 1; i<=m; ++i) { cin >> l >> r >> winner; sef = find(l); while(sef <= r) { if (sef == winner) { sef++; } else { beatenBy[sef] = winner; tata[sef] = sef + 1; } sef = find(sef); } } for (int i = 1; i <= n; ++i) cout << beatenBy[i] << " "; return 0; }<file_sep>// https://codeforces.com/contest/683/problem/F // https://codeforces.com/contest/683/submission/18529476 fun main(args: Array<String>) { val (q) = readLine()!!.split('\n'); var a = q.trim(); a += ' '; var len = a.length; var i = 0; var word = ""; var cap = 1; var st = ""; while (i < len){ while (i < len && a[i] == ' '){ i++; } while ( i < len && ((a[i] >= 'a' && a[i] <= 'z' ) || (a[i] >= 'A' && a[i] <= 'Z'))){ word += a[i]; i++; } word = word.toLowerCase(); if (cap == 1) word = word.capitalize(); if (word != "") st+= word; var char = ' ' if (i < len) char = a[i]; while (i < len && a[i] == ' '){ i++; if (i < len) char = a[i]; } cap = 0; word = ""; if (char == ','){ st+=", "; i++;}; else if (char == '.'){ st+=". "; cap = 1; i++; }else if (i < len && ((a[i] >= 'a' && a[i] <= 'z' ) || (a[i] >= 'A' && a[i] <= 'Z'))){ st+=' '; } } word = word.toLowerCase(); if (cap == 1) word = word.capitalize(); st+=word; println(st.trim()); } <file_sep>// https://codeforces.com/contest/660/problem/A // https://codeforces.com/contest/660/submission/18716745 #ifndef _CRT_NONSTDC_NO_WARNINGS #define _CRT_NONSTDC_NO_WARNINGS #include <cstdio> #include <cstdlib> #include <iostream> #include <string> #include <cmath> #include <vector> using namespace std; int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a%b); } int main() { int n, v[1002], i = 0, sz; vector<int> fin; for (scanf("%d", &n); i < n; scanf("%d", &v[i++])); for (i = 0; i < n - 1; i++) { fin.push_back(v[i]); if (gcd(v[i], v[i + 1]) != 1) fin.push_back(1); } fin.push_back(v[n - 1]); sz = (int)fin.size(); for (printf("%d\n", sz - n), i = 0; i < sz ; printf("%d ", fin[i++])); return EXIT_SUCCESS; } #endif //_CRT_NONSTDC_NO_WARNINGS<file_sep>// https://codeforces.com/contest/686/problem/B // https://codeforces.com/contest/686/submission/18716425 #ifndef _CRT_NONSTDC_NO_WARNINGS #define _CRT_NONSTDC_NO_WARNINGS #include <cstdio> #include <cstdlib> #include <iostream> #include <string> #include <cmath> #include <vector> using namespace std; void swap(int& a, int&b) { auto aux = a; a = b; b = aux; } int main() { int n, v[105], i = 0; char ok = 0; for (scanf("%d", &n); i < n; scanf("%d", &v[i++])); while (ok == 0) { ok = 1; for (int i = 1; i < n; i++) { if (v[i] < v[i - 1]) swap(v[i], v[i - 1]), ok = 0, printf("%d %d\n", i, i+1); } } return EXIT_SUCCESS; } #endif //_CRT_NONSTDC_NO_WARNINGS<file_sep>// https://codeforces.com/contest/721/problem/B // https://codeforces.com/contest/721/submission/21808148 #include <iostream> #include <vector> #include <string> using namespace std; int main() { ios::sync_with_stdio(false); vector<int> v(105, 0); string s; int n, k; cin >> n >> k; for (;n--;) { cin >> s; v[s.size()]++; } int sum = 0; int pp = 0; cin >> s; for (size_t i = 0; i < s.size(); ++i) { sum += v[i]; } pp = (sum / k) * 5; cout << sum + pp + 1 << " "; sum += v[s.size()] - 1; pp = (sum / k) * 5; cout << sum + pp + 1; return EXIT_SUCCESS; } <file_sep># https://codeforces.com/contest/141/problem/A # https://codeforces.com/contest/141/submission/14008308 s=input() l=[] for _ in range(0,27): l.append(0) for i in range (len(s)): l[ord(s[i])-64]+=1 del(s) s=input() for i in range (len(s)): l[ord(s[i])-64]+=1 del(s) s=input() for i in range (len(s)): l[ord(s[i])-64]-=1 ok='YES' for i in range (27): if l[i]!=0: ok='NO' print(ok) <file_sep>// https://www.spoj.com/problems/FREQUENT/ #include <iostream> #include <vector> #include <algorithm> using namespace std; struct Node { Node() = default; ~Node() = default; Node(int Value) { LeftValue = Value; RightValue = Value; LeftMaxCounter = 1; RightMaxCounter = 1; CombinedMaxCounter = 1; } int LeftValue = 0; int RightValue = 0; int LeftMaxCounter = 0; int RightMaxCounter = 0; int CombinedMaxCounter = 0; }; class SegmentTree { public: SegmentTree(const vector<int>& Array) : Array{ Array }, Tree( Array.size() * 4 + 4, Node()) { Build(1, 0, Array.size() - 1); } int Query(size_t Low, size_t High) { vector<size_t> path; Query(1, 0, Array.size() - 1, Low, High, path); Node node = Tree[path[0]]; for (size_t i = 1; i < path.size(); ++i) { Node n = Tree[path[i]]; node = Combine(node, n); } return max(node.CombinedMaxCounter, max(node.LeftMaxCounter, node.RightMaxCounter)); } private: void Build(size_t Node, size_t Start, size_t End) { if (Start == End) { Tree[Node] = ::Node(Array[Start]); return; } size_t mid = (Start + End) / 2; Build(Node * 2, Start, mid); Build(Node * 2 + 1, mid + 1, End); Tree[Node] = Combine(Tree[Node * 2], Tree[Node * 2 + 1]); } void Query(size_t Node, size_t Start, size_t End, size_t Low, size_t High, vector<size_t>& Path) { if (Start > High || End < Low) { return; } if (Low <= Start && End <= High) { Path.push_back(Node); return; } size_t mid = (Start + End) / 2; Query(Node * 2, Start, mid, Low, High, Path); Query(Node * 2 + 1, mid + 1, End, Low, High, Path); } Node Combine(const Node& Left, const Node& Right) { Node node; node.LeftValue = Left.LeftValue; node.RightValue = Right.RightValue; node.LeftMaxCounter = Left.LeftMaxCounter; node.RightMaxCounter = Right.RightMaxCounter; node.CombinedMaxCounter = max(Left.CombinedMaxCounter, Right.CombinedMaxCounter); if (Right.LeftValue == Left.LeftValue) { node.LeftMaxCounter += Right.LeftMaxCounter; } if (Left.RightValue == Right.RightValue) { node.RightMaxCounter += Left.RightMaxCounter; } if (Right.LeftValue == Left.RightValue) { node.CombinedMaxCounter = max(node.CombinedMaxCounter, Left.RightMaxCounter + Right.LeftMaxCounter); } return node; } vector<int> Array; vector<Node> Tree; }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int n, q, r, l; cin >> n; while (n != 0) { cin >> q; vector<int> v(n, 0); for (int i = 0; i < n; ++i) cin >> v[i]; SegmentTree tree(v); for (int i = 1; i <= q; ++i) { cin >> r >> l; cout << tree.Query(r - 1, l - 1) << '\n'; } cin >> n; } return 0; }<file_sep>// https://codeforces.com/contest/1/problem/B // https://codeforces.com/contest/1/submission/18717562 #ifndef _CRT_NONSTDC_NO_WARNINGS #define _CRT_NONSTDC_NO_WARNINGS #include <cstdio> #include <cstdlib> #include <iostream> #include <string> #include <cmath> #include <vector> using namespace std; void excelConvert(const string&column, const string& row); void reverseConvert(const string&row, const string&rowNumber, const string&column, const string& columnNumber); int main() { int n, i, size; string s, r, nr1, c, nr2; scanf("%d", &n); while (n--) { cin >> s; size = (int)s.size(); r = nr1 = c = nr2 = ""; i = 0; while (i < size && (s[i] >= 'A' && s[i] <= 'Z')) r += s[i++]; while (i < size && (s[i] >= '0' && s[i] <= '9')) nr1 += s[i++]; while (i < size && (s[i] >= 'A' && s[i] <= 'Z')) c += s[i++]; while (i < size && (s[i] >= '0' && s[i] <= '9')) nr2 += s[i++]; (c == "") ? excelConvert(r, nr1) : reverseConvert(r, nr1, c, nr2); } return EXIT_SUCCESS; } void excelConvert(const string&column, const string& row) { string rez = "R" + row + "C"; int col = 0, size = (int)column.size(); for (int i = 0; i < size; i++) col = col * 26 + column[i] - 'A' + 1; rez += to_string(col); cout << rez << "\n"; } void reverseConvert(const string&row, const string&rowNumber, const string&column, const string& columnNumber){ string rez = ""; int col = stoi(columnNumber), md; while (col > 0) { md = (col - 1) % 26; rez = (char)('A' + md) + rez; col = (col - md) / 26; } rez += rowNumber; cout << rez << "\n"; } #endif //_CRT_NONSTDC_NO_WARNINGS<file_sep>// https://codeforces.com/contest/1118/problem/A // https://codeforces.com/contest/1118/submission/67975573 #include <iostream> #include <algorithm> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cerr.tie(nullptr); unsigned long long queries, n, a, b; cin >> queries; while (queries--) { unsigned long long cost = 0; cin >> n >> a >> b; b = min(a + a, b); cost = (n % 2) * a + (n / 2) * b; cout << cost << "\n"; } return 0; }<file_sep>// https://codeforces.com/contest/513/problem/A // https://codeforces.com/contest/513/submission/14045349 #include <stdio.h> #include <stdlib.h> int main() { int n1,n2,k1,k2; scanf("%d %d %d %d",&n1,&n2,&k1,&k2); if (n1<=n2){printf("Second");} else{printf("First");} return 0; } <file_sep># https://codeforces.com/contest/133/problem/A # https://codeforces.com/contest/133/submission/13408036 s=input() if "H" in s or "Q" in s or "9" in s: print("YES") else: print("NO") <file_sep>// https://codeforces.com/contest/702/problem/A // https://codeforces.com/contest/702/submission/46818106 #include <iostream> using namespace std; int main() { int n, prev, cur, mx = 1, pc = 1; cin >> n >> prev; for (int i = 1; i < n; ++i) { cin >> cur; cur > prev ? ++pc : pc = 1; if (mx < pc) mx = pc; prev = cur; } cout << mx; return 0; }<file_sep>// https://codeforces.com/contest/681/problem/B // https://codeforces.com/contest/681/submission/18471034 #include <iostream> using namespace std; const int house = 1234567; const int car = 123456; const int comp = 1234; int main() { int n, rez; bool ok = false; cin >> n; for (int i = 0; ok == false && house*i <= n; i++) { for (int j = 0; ok == false && i*house + j * car <= n; j++) { rez = i * house + j * car; if ((n - rez) % comp == 0) ok = true; } } (ok) ? puts("YES") : puts("NO"); return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/509/problem/A // https://codeforces.com/contest/509/submission/14045227 #include <stdio.h> #include <stdlib.h> int main() { int a[10][10],maxs,i,j,n; scanf("%d",&n); maxs=1; for (i=0;i<n;i++) { for (j=0;j<n;j++) { if (j==0 || i==0) { a[i][j]=1; } else { a[i][j]=a[i-1][j]+a[i][j-1]; } if (a[i][j]>maxs) { maxs=a[i][j]; } } } printf("%d",maxs); return 0; } <file_sep>// https://codeforces.com/contest/659/problem/A // https://codeforces.com/contest/659/submission/17562007 #include <stdio.h> #include <stdlib.h> int main() { int n, a, b, c; scanf("%d %d %d", &n, &a, &b); a = (a + b) % n; if (a < 0) a = n + a; else if (a == 0) a = n; printf("%d",a); }<file_sep>// https://codeforces.com/contest/725/problem/A // https://codeforces.com/contest/725/submission/21672549 #include <iostream> #include <string> using namespace std; int main() { int n; int cnt = 0; int all = 0; string s; cin >> n >> s; size_t sz = s.size(); bool ok; ok = (s[0] == '<'); (ok) ? all++ : cnt++; for (auto i = 1; i < sz; ++i) { if (s[i] == '<') { cnt = 0; if (ok) all++; } else { cnt++; ok = false; } } all += cnt; cout << all; return 0; }<file_sep>// https://codeforces.com/contest/313/problem/B // https://codeforces.com/contest/313/submission/17171423 #include <iostream> using namespace std; int main(){ int v[100001], n, m, l, r; char x, y = 'e'; x = getchar(); y = getchar(); v[1] = 0; n = 1; while (y != '\n') { n++; if (x == y) v[n] = v[n - 1] + 1; else { v[n] = v[n-1]; x = y; } y = getchar(); } cin >> m; for (; m > 0; m--) { cin >> l >> r; cout << v[r] - v[l] << endl; } return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/630/problem/A // https://codeforces.com/contest/630/submission/17205264 #include <stdio.h> #include <stdlib.h> int main() { putchar('2'); putchar('5'); return EXIT_SUCCESS; } #include <iostream> using namespace std; int main() { unsigned long long n; cout << 25; return EXIT_SUCCESS; } <file_sep>// https://www.spoj.com/problems/IWGBS/ #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <map> #include <unordered_map> #include <set> #include <vector> #include <cstdio> #include <string> using namespace std; #define ll long long #define ull unsigned long long /*---------------------------*/ inline int digit(char c) { return c - '0'; } inline char chr(int d) { return d + '0'; } void add(string& a, string& b, string& res) { int n = a.size(); int m = b.size(); int i = n - 1; int j = m - 1; int cap = 0; int ps; res = ""; for (; i >= 0 && j >= 0; --i , --j) { ps = digit(a[i]) + digit(b[j]) + cap; res += chr(ps % 10); cap = ps / 10; } for (; i >= 0; --i) { ps = digit(a[i]) + cap; res += chr(ps % 10); cap = ps / 10; } for(; j >= 0; --j) { ps = digit(b[j]) + cap; res += chr(ps % 10); cap = ps / 10; } if (cap > 0) res += chr(cap); reverse(res.begin(), res.end()); } int main() { ios_base::sync_with_stdio(false) , cin.tie(nullptr) , cout.tie(nullptr); int n; cin >> n; string prevZeros = "1", prevOnes = "1", currentZeros = "1", currentOnes = "1"; for (int i = n - 1; i > 0; --i) { currentZeros = prevOnes; add(prevZeros, prevOnes, currentOnes); prevOnes = currentOnes; prevZeros = currentZeros; } add(currentOnes, currentZeros, prevZeros); cout << prevZeros; return 0; } <file_sep>// https://codeforces.com/contest/427/problem/A // https://codeforces.com/contest/427/submission/14061277 #include <iostream> using namespace std; int main() { int n,x,nrp=0,nrn=0; cin>>n; while (n>0) { cin>>x; if (x==-1 && nrp==0) { nrn++; } else if(x==-1 && nrp>0) { nrp--; } else if (x>=0) { nrp+=x; } n--; } cout<<nrn; return 0; } <file_sep>// https://codeforces.com/contest/499/problem/A // https://codeforces.com/contest/499/submission/17592521 #include <iostream> using namespace std; int main() { int n, x, t = 0, ra = 1, l, r; cin >> n >> x; for (; n > 0; n--) { cin >> l >> r; t += (r - l) + 1; for (; ra + x <= l; ra += x); if (ra < l) t += (l - ra); ra = r + 1; } cout << t; return EXIT_SUCCESS; }<file_sep># https://codeforces.com/contest/158/problem/B # https://codeforces.com/contest/158/submission/13419053 n=int(input()) x=list(map(int,input().split())) v=[0,0,0,0,0] for i in range(n): v[x[i]]+=1 nr=v[4] while (v[1]>0 and v[3]>0): nr+=1 v[3]-=1 v[1]-=1 while (v[3]>0): nr+=1 v[3]-=1 while(v[1]>=2): v[2]+=1 v[1]-=2 while (v[2]>=2): nr+=1 v[2]-=2 if (v[2]>0 or v[1]>0): nr+=1 print(nr) <file_sep>// https://codeforces.com/contest/581/problem/A // https://codeforces.com/contest/581/submission/14061199 #include <iostream> #include <algorithm> #include <math.h> using namespace std; int main() { int a, b; int time = 0; cin >> a; cin >> b; time = min(a, b); int maxnum = max(a, b) - time; cout << time << " "; cout << maxnum / 2 << endl; return 0; } #include <iostream> using namespace std; int main() { int a,b; cin>>a>>b; cout<<min(a,b)<<" "<<(max(a,b)-min(a,b))/2; return 0; } <file_sep>// https://codeforces.com/contest/630/problem/Q // https://codeforces.com/contest/630/submission/17316827 #include <stdlib.h> #include <stdio.h> #include <iostream> #include <math.h> int main() { int lT, lP, lH; double V; std::cin >> lT >> lP >> lH; V = (lT*lT*lT) /( 6.0*sqrt(2.0)) + (lP*lP*lP*sqrt(2.0)) / 6.0 + (5.0 + sqrt(5.0))*lH*lH*lH / 24.0; printf("%.10lf", V); return EXIT_SUCCESS; } <file_sep># https://codeforces.com/contest/96/problem/A # https://codeforces.com/contest/96/submission/13407917 s=input() i=0 ok='true' while i<=len(s)-7 and ok=='true': if s[i:i+7]=="0000000" or s[i:i+7]=="1111111": ok='false' else: i+=1 if ok=='false': print("YES") else: print("NO") <file_sep>// https://codeforces.com/contest/1257/problem/A // https://codeforces.com/contest/1257/submission/67974889 #include <iostream> #include <algorithm> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cerr.tie(nullptr); int n, x, a, b, t; cin >> t; while (t--) { cin >> n >> x >> a >> b; if (b < a) swap(a, b); if (b < n) { auto prevB = b; b = min(b + x, n); x -= (b - prevB); } if (a > 1) { a = max(1, a - x); } cout << b - a << "\n"; } return 0; }<file_sep>// https://codeforces.com/contest/711/problem/A // https://codeforces.com/contest/711/submission/20556856 #include <stdio.h> #include <stdlib.h> int main() { char rows[1001][6]; int n; bool ok = false; scanf("%d",&n); int i; for(i = 0; i < n; i++) { scanf("%s",&rows[i]); if (!ok) { if (rows[i][0] == 'O' && rows[i][1] == 'O') { ok = true; rows[i][0] = '+'; rows[i][1] = '+'; } else if (rows[i][3] == 'O' && rows[i][4] == 'O') { ok = true; rows[i][3] = '+'; rows[i][4] = '+'; } } } if (!ok) { printf("NO"); } else { printf("YES\n"); for (i = 0; i < n; i++) { printf("%s\n", rows[i]); } } return 0; } <file_sep>// https://codeforces.com/contest/439/problem/B // https://codeforces.com/contest/439/submission/18275375 #include <cstdio> #include <cstdlib> #include <algorithm> int main() { unsigned long long n, x, s = 0, v[100001]; scanf("%llu %llu", &n, &x); for (unsigned long long i = 0; i < n; i++)scanf("%llu", &v[i]); std::sort(v, v + n); for (unsigned long long i = 0; i < n; i++) { s += x*v[i]; x--; if (x < 1) x = 1; } printf("%llu\n", s); return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/problemset/problem/1077/A // https://codeforces.com/contest/1077/submission/48048633 #include <iostream> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int t; long long a, b, k; cin >> t; while (t--) { cin >> a >> b >> k; cout << ((k / 2) + (k % 2)) * a - (k / 2) * b << "\n"; } return 0; }<file_sep>// https://codeforces.com/contest/339/problem/B // https://codeforces.com/contest/339/submission/14410462 #include <iostream> using namespace std; int main() { long long x,pozcur=1,n,m,grande=0; cin>>n>>m; while (m>0) { cin>>x; if (x>pozcur) { grande += x - pozcur ; } else if (x<pozcur) { grande += n - pozcur + x; } pozcur = x; m--; } cout<<grande; return 0; } <file_sep>// https://codeforces.com/contest/471/problem/A // https://codeforces.com/contest/471/submission/14395079 #include <iostream> using namespace std; int a[10]; int find_picioare() { int aux = -1; for (int i = 1;i <= 9;i++) { if (a[i]>=4) { aux = i; } } return aux; } int cauta_elefant() { int aux = -1; for (int i=1;i<=9;i++) { if (a[i]>=2) { aux = i; } } return aux; } int main() { int x; for (int i = 1;i <= 6;i++) { cin >> x; a[x]++; } int p = find_picioare(); if (p==-1) { cout<<"Alien"; } else { a[p]-=4; p = cauta_elefant(); if (p==-1) { cout<<"Bear"; } else { cout<<"Elephant"; } } return 0; } <file_sep># https://codeforces.com/contest/697/problem/A # https://codeforces.com/contest/697/submission/25661932 t,s,x = map(int,input().split()) if (x % s == t % s and t <= x or x % s == (t + 1) % s and t+1 < x): print('YES') else: print('NO') <file_sep>// https://codeforces.com/contest/656/problem/F // https://codeforces.com/contest/656/submission/18043270 #include <iostream> using namespace std; int main() { int s = 1; char c; getchar(); for (int i = 1; i <= 6; i++) { c = getchar(); if (c == '1') s += 10; else s += c - 48; } cout << s; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/722/problem/B // https://codeforces.com/contest/722/submission/21723154 #include <iostream> #include <string.h> using namespace std; bool is_vowel(char c) { return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'y'); } int main() { int nr, n, v[102]; char s[105]; cin >> n; bool ok = true; for (int i = 0; i < n; ++i) cin >> v[i]; fgets(s, 105, stdin); for (int i = 0; i < n; ++i) { nr = 0; fgets(s, 105, stdin); size_t sz = strlen(s); for (size_t k = 0; k < sz; ++k) { if (is_vowel(s[k])) nr++; } if (nr != v[i]) ok = false; } (ok) ? puts("YES") : puts("NO"); return 0; }<file_sep># https://codeforces.com/contest/158/problem/A # https://codeforces.com/contest/158/submission/13406190 n,k = map(int, input().split()) x=list(map(int,input().split())) nr=0 meta_number=x[k-1] for i in range(n): if ((i<k and x[i]>0) or (i>=k and x[i]>0 and meta_number==x[i])): nr+=1 print(nr) <file_sep># https://codeforces.com/contest/515/problem/A # https://codeforces.com/contest/515/submission/14397592 n,m,s=map(int,input().split()) s = s - (abs(n)+abs(m)) if s<0: s=1 if s%2==0: print('Yes') else: print('No') <file_sep>// https://codeforces.com/contest/556/problem/A // https://codeforces.com/contest/556/submission/14410932 #include <iostream> using namespace std; int main() { char c; int n,nr0=0,nr1=0; cin>>n; for (int i=1;i<=n;i++) { cin>>c; if (c=='0') { nr0++; } else { nr1++; } if (nr1>0 && nr0>0) { if (nr1>nr0) { nr1-=nr0; nr0=0; } else { nr0-=nr1; nr1=0; } } } cout<<max(nr0,nr1); } <file_sep>// https://codeforces.com/contest/25/problem/A // https://codeforces.com/contest/25/submission/14048259 #include <stdio.h> #include <stdlib.h> int main() { int x,i=1,nrpar=0,nrimpar=0,n,indexpar=0,indeximpar=0; scanf("%d",&n); while (n>0) { scanf("%d",&x); if (x%2==0) { nrpar++; indexpar=i; } else { nrimpar++; indeximpar=i; } i++; n--; } if (nrimpar>nrpar) { printf("%d",indexpar); } else { printf("%d",indeximpar); } return 0; } <file_sep># https://codeforces.com/contest/268/problem/A # https://codeforces.com/contest/268/submission/13613840 n = int(input()) a = [] b = [] for _ in range(n): x,y=list(map(int,input().split())) a.append(x) b.append(y) nr = 0 for i in range(n): for j in range(n): if b[i]==a[j]: nr+=1 print(nr) <file_sep>// https://codeforces.com/contest/656/problem/A // https://codeforces.com/contest/656/submission/17154162 #include <iostream> using namespace std; int main() { unsigned long long n, t = 1;; cin >> n; t <<= n; if (n >= 13) t -= (1 << (n - 13)) * 100; cout << t; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/750/problem/B // https://codeforces.com/contest/750/submission/23458730 #include <iostream> #include <string> using namespace std; int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); int n, km, scc = 0, d = 'N'; bool ok = true; string s; cin >> n; while(n-- && ok) { if (scc == 0) d = 'N'; else if (scc == 20000) d = 'S'; else if (scc < 0 || scc > 20000) ok = false; else d = 'U'; cin >> km >> s; if (d == 'N' && s != "South") ok = false; else if (d == 'S' && s != "North") ok = false; else if (s == "South") scc += km; else if (s == "North") scc -= km; } d = (scc == 0) ? 'N' : 'U'; (ok && d == 'N') ? puts("YES") : puts("NO"); return 0; }<file_sep># https://codeforces.com/contest/507/problem/A # https://codeforces.com/contest/507/submission/14530591 def recursie(s,i): if i<n and s+p[i][1]<=k : recursie(s+p[i][1],i+1) print(p[i][0]+1,sep = ' ', end=' ') else: print(i) n, k = map(int,input().split()) l = list(map(int,input().split())) p = [] for i in range(n): p.append([i,l[i]]) p = sorted(p,key=lambda x: x[1]) s = 0 i = 0 recursie(s,i) <file_sep># https://codeforces.com/contest/4/problem/C # https://codeforces.com/contest/4/submission/15134542 n = int(input()) dictio = {} while n > 0: s = input() try: dictio[s] += 1 print(s,dictio[s],sep='') except: dictio[s] = 0 print('OK') n -= 1 <file_sep># https://codeforces.com/contest/116/problem/A # https://codeforces.com/contest/116/submission/13407618 n=int(input()) nr_max=0 nr_curent=0 for i in range(n): pas_out,pas_in=map(int, input().split()) nr_curent=nr_curent-pas_out+pas_in if nr_curent>nr_max: nr_max=nr_curent print(nr_max) <file_sep># https://codeforces.com/contest/599/problem/A # https://codeforces.com/contest/599/submission/14384482 d1,d2,d3 = map(int, input().split()) l = min(d1,d2) total = l h = max(d1,d2) p = min(l+h,d3) total += p p = min(h,d3+l) total += p print(total) <file_sep>// https://codeforces.com/contest/734/problem/B // https://codeforces.com/contest/734/submission/22307571 #include <iostream> #include <algorithm> using namespace std; int main() { int k2, k3, k5, k6, m; cin >> k2 >> k3 >> k5 >> k6; m = min(k2, min(k5, k6)); cout << m * 256 + min(k2 - m, k3) * 32; return 0; }<file_sep>// https://codeforces.com/contest/740/problem/A // https://codeforces.com/contest/740/submission/22715054 #include <iostream> using namespace std; int main() { long long s, n, a, b, c, min; cin >> n >> a >> b >> c; min = LLONG_MAX; for (int i = 0; i <= 4; i++) { for (int j = 0; j <= 4; j++) { for (int p = 0; p <= 4; p++) { if ((n + i + 2*j + 3*p) % 4 == 0) { s = i*a + j * b + p * c; if (s < min) min = s; } } } } cout << min; return 0; }<file_sep>// https://codeforces.com/contest/749/problem/A // https://codeforces.com/contest/749/submission/23144602 #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <stdio.h> using namespace std; int main() { int n; int nr; bool o3 = false; scanf("%d", &n); if (n & 1) o3 = true, n -= 3; nr = n / 2; if (o3) printf("%d\n3 ", nr + 1); else printf("%d\n",nr); while (nr--) printf("2 "); return 0; }<file_sep>// https://codeforces.com/contest/743/problem/B // https://codeforces.com/contest/743/submission/22979867 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <math.h> #include <algorithm> #include <iostream> using namespace std; int main() { unsigned long long k, poz, el, adv; int n; cin >> n >> k; el = 1; poz = 1; while (poz <= k) { el++; poz <<= 1; } el--; poz >>= 1; adv = (unsigned long long) 1 << el; for (;;) { if (poz == k) break; else { if ((k - poz) % adv == 0) break; el--; poz >>= 1; adv >>= 1; } } cout << el; return 0; } <file_sep>// https://codeforces.com/contest/977/problem/A // https://codeforces.com/contest/977/submission/46371984 #include <iostream> using namespace std; int main() { unsigned long long n = 0; int k = 0; cin >> n >> k; while (k > 0) { if (n % 10 != 0) { if (k > n % 10) { k -= (n % 10); n -= (n % 10); } else { n -= k; k = 0; } } else { n = n / 10; --k; } } cout << n; return 0; }<file_sep># https://codeforces.com/contest/616/problem/A # https://codeforces.com/contest/616/submission/15329901 a = input().lstrip("0") b = input().lstrip("0") if len(a) > len (b) or len(a) == len(b) and a > b: print('>') elif len(a) < len(b) or len(a) == len(b) and a < b: print('<') elif a == b: print('=') <file_sep># https://codeforces.com/contest/476/problem/A # https://codeforces.com/contest/476/submission/14268179 n,m = map(int,input().split()) if n%2==0: high = n//2 else: high = n//2 + 1 if high%m==0: div = high//m else: div = high//m +1 if m*div<=n: print(m*div) else: print(-1) <file_sep>// https://codeforces.com/contest/549/problem/A // https://codeforces.com/contest/549/submission/17147407 #include <iostream> using namespace std; void check(char x, int tab[27]) { if (x == 'f' || x == 'a' || x == 'c' || x == 'e') tab[x - 'a']++; } bool face(int x, int y, char mat[52][52]) { int tab[27]; memset(tab, 0, 27 * sizeof(int)); check(mat[x][y],tab); check(mat[x + 1][y],tab); check(mat[x][y + 1],tab); check(mat[x + 1][y + 1],tab); return ((tab['a' - 'a'] == 1) && (tab['e' - 'a'] == 1) && (tab['c' - 'a'] == 1) && (tab['f' - 'a'] == 1)); } int main() { char mat[52][52]; int n, m, cont = 0; cin >> n >> m; for (int i = 1; i <= n + 1; i++) { for (int j = 1; j <= m + 1; j++) { if ( i == n + 1 || j == m + 1) mat[i][j] = 'X'; else cin >> mat[i][j]; } } for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (face(i,j,mat)) cont++; cout << cont; return EXIT_SUCCESS; } <file_sep>// https://codeforces.com/contest/313/problem/A // https://codeforces.com/contest/313/submission/14057579 #include <iostream> #include <stdlib.h> using namespace std; int main() { long long n,aux; cin>>n; aux=n; int lc,sc; lc=abs(n%10); aux=aux/10; sc=abs(aux%10); aux=aux/10; if (n>=0) { cout<<n; } else { if (lc>=sc) { cout<<n/10; } else { n=n/100; n=n*10;; n-=lc; cout<<n; } } return 0; } <file_sep>// https://codeforces.com/contest/447/problem/A // https://codeforces.com/contest/447/submission/18041709 #include <iostream> using namespace std; int main() { int x, n, p, v[301]; memset(v, 0, 301 * sizeof(int)); cin >> p >> n; for (int i = 1; i <= n; i++) { cin >> x; if (v[x % p] != 0) { cout << i; goto out; } else v[x%p] = 1; } cout << "-1"; out: return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/707/problem/A // https://codeforces.com/contest/707/submission/21341900 #include <stdio.h> #include <stdlib.h> int main() { int n, m, elms; char c; int ok = 0, i = 0; scanf("%d %d", &n, &m); elms = n * m; while (ok == 0 && i++ < elms) { c = getchar(); c = getchar(); ok = (c != 'B' && c != 'W' && c!= 'G'); } (ok == 0) ? puts("#Black&White") : puts("#Color"); return EXIT_SUCCESS; }<file_sep>// https://www.spoj.com/problems/MARTIAN/ #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <map> #include <unordered_map> #include <set> #include <vector> #include <cstdio> #include <string> using namespace std; #define ll long long #define ull unsigned long long /*------------------------------------------------------------------*/ int n, m; int yeyenium[505][505], bloggium[505][505], ans[505][505]; int main() { ios_base::sync_with_stdio(false) , cin.tie(nullptr) , cout.tie(nullptr); cin >> n >> m; while (n != 0 && m != 0) { for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { cin >> yeyenium[i][j]; yeyenium[i][j] += yeyenium[i][j - 1]; } } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { cin >> bloggium[i][j]; bloggium[i][j] += bloggium[i - 1][j]; } } for(int i = 1; i<=n; ++i) { for(int j = 1; j<=m; ++j) { ans[i][j] = max(ans[i - 1][j] + yeyenium[i][j], ans[i][j - 1] + bloggium[i][j]); } } cout << ans[n][m] << "\n"; cin >> n >> m; } return 0; } <file_sep>// https://codeforces.com/contest/745/problem/A // https://codeforces.com/contest/745/submission/23052557 #include <stdio.h> #include <iostream> #include <set> #include <string> using namespace std; void shift(string& s) { string p; p = s.substr(1, s.size() - 1); p += s[0]; s = p; } int main() { string s; set<string> multime; cin >> s; multime.insert(s); for (int i = 1; i <= (int)s.size() + 1; ++i) { shift(s); multime.insert(s); } cout << multime.size(); return 0; }<file_sep>// https://www.spoj.com/problems/EDIST/ #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <map> #include <unordered_map> #include <set> #include <vector> #include <cstdio> #include <string> using namespace std; #define ll long long #define ull unsigned long long /*------------------------------------------------------------------*/ int mat[2005][2005]; int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); string s, p; int t, n, m, cost; cin >> t; while(t--) { cin >> s >> p; n = s.length(); m = p.length(); for (int i = 0; i <= m + 1; ++i) mat[0][i] = i; for (int i = 0; i <= n + 1; ++i) mat[i][0] = i; for(int i = 1; i<=n;++i) { for(int j = 1; j<=m;++j) { cost = 1; if (s[i - 1] == p[j - 1]) cost = 0; mat[i][j] = min(mat[i - 1][j - 1] + cost, min(mat[i - 1][j] + 1, mat[i][j - 1] + 1)); } } cout << mat[n][m] << '\n'; } return 0; }<file_sep>// https://codeforces.com/contest/617/problem/A // https://codeforces.com/contest/617/submission/16293561 #include <stdio.h> #include <stdlib.h> int main() { int n,contor,p; scanf("%d",&n); p = 5; contor = 0; while (p > 0 && n != 0) { contor += n/p; n -= p* (n/p); p--; } printf("%d",contor); return 0; } <file_sep>// https://codeforces.com/contest/489/problem/C // https://codeforces.com/contest/489/submission/22857330 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <math.h> #include <algorithm> #include <iostream> #include <vector> #include <string> using namespace std; int main() { vector<int> min(10, 0), max(10,0); int m, s, n, p; scanf("%d %d", &m, &s); n = m; p = s; while (m--) { if (s >= 9) max[9]++, min[9]++, s -= 9; else max[s]++, min[s]++, s -= s; } if (s > 0 || (n > 1 && p == 0)) puts("-1 -1"); else { string solMin = ""; string solMax = ""; if (min[0] == 1 && n == 1) solMin = "0"; else { if (min[1] != 0) solMin += '1', min[1]--; else if (min[0] > 0 && n > 1) { min[0]--; for (int i = 2; i <= 9; ++i) { if (min[i] != 0) { min[i]--; solMin += '1'; min[i - 1]++; break; } } } for (int i = 0; i <= 9; ++i) { for (int k = 1; k <= min[i]; k++)solMin += (char)(i + '0'); } } if (max[0] == 1 && n == 1) solMax = "0"; else { for (int i = 9; i >= 0; --i) { for (int k = 1; k <= max[i]; k++)solMax += (char)(i + '0'); } } cout << solMin << " " << solMax; } return 0; } <file_sep># https://codeforces.com/contest/572/problem/A # https://codeforces.com/contest/572/submission/14898609 a, b = map(int,input().split()) k, m = map(int,input().split()) l1 = list(map(int,input().split())) l2 = list(map(int,input().split())) if l1[k - 1] < l2[b - m]: print('YES') else: print('NO') <file_sep>// https://codeforces.com/contest/258/problem/A // https://codeforces.com/contest/258/submission/17172639 #include <iostream> #include <string> using namespace std; int main() { string line; getline(cin, line); bool ok = (line[0] == '1'); int i = 0, len = line.length(); while (ok == true && i < len - 1) { putchar('1'); i++; ok = line[i] == '1'; } if (ok == true || i == len - 1) return 0; i++; for (; i < len;i++) putchar(line[i]); return EXIT_SUCCESS; } <file_sep>// https://codeforces.com/contest/735/problem/D // https://codeforces.com/contest/735/submission/22544920 #include <iostream> #include <algorithm> #include <cmath> using namespace std; bool is_prime(long long n) { double x = sqrt(n); long long k = (long long)x + 1; for (long long i = 2; i < k; ++i) { if (n % i == 0) return false; } return true; } int main() { long long n; cin >> n; if (is_prime(n)) puts("1"); else if (n & 1) { if (is_prime(n - 2)) puts("2"); else puts("3"); } else puts("2"); return 0; }<file_sep>// https://codeforces.com/contest/777/problem/A // https://codeforces.com/contest/777/submission/24967162 #include <iostream> #include <vector> using namespace std; int main() { ios::sync_with_stdio(false); int moves[6][3] = { {0, 1, 2}, {1, 0, 2}, {1, 2, 0}, {2, 1, 0}, {2, 0, 1}, {0, 2, 1} }; long long n, pos; cin >> n >> pos; cout<<moves[n % 6][pos]; return 0; }<file_sep>// https://codeforces.com/problemset/problem/1015/A // https://codeforces.com/contest/1015/submission/48889387 #include <iostream> #include <fstream> #include <chrono> #include <iomanip> #include <algorithm> #include <string> #include <vector> #include <map> #include <set> #include <queue> #include <numeric> #include <bitset> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cerr.tie(nullptr); int n, m, l, r; cin >> n >> m; set<int> s; for (int i = 1; i <= m; ++i) { s.insert(i); } for (int i = 1; i <= n; ++i) { cin >> l >> r; for (int k = l; k <= r; ++k) s.erase(k); } cout << s.size() << "\n"; for (const auto& p : s) cout << p << " "; return 0; }<file_sep>// https://codeforces.com/contest/255/problem/A // https://codeforces.com/contest/255/submission/16294406 #include <stdio.h> #include <stdlib.h> struct muscles { char* name; int value; }; int main() { struct muscles muscle[3]; int i,n,x,j; muscle[0].name = "chest"; muscle[0].value = 0; muscle[1].name = "biceps"; muscle[1].value = 0; muscle[2].name = "back"; muscle[2].value = 0; scanf("%d",&n); for (i = 1; i <=n; i++) { scanf("%d",&x); if (i % 3 == 0) muscle[2].value += x; else if (i % 3 == 2) muscle[1].value += x; else muscle[0].value += x; } for (i = 0; i < 3; i++) { for (j = i + 1; j < 3; j++) { if (muscle[i].value < muscle[j].value) { struct muscles aux; aux = muscle[i]; muscle[i] = muscle[j]; muscle[j] = aux; } } } printf("%s",muscle[0].name); return 0; } <file_sep>// https://codeforces.com/contest/686/problem/A // https://codeforces.com/contest/686/submission/18716299 #ifndef _CRT_NONSTDC_NO_WARNINGS #define _CRT_NONSTDC_NO_WARNINGS #include <cstdio> #include <cstdlib> #include <iostream> #include <string> #include <cmath> #include <vector> using namespace std; int main() { long long n, x, d, ct = 0; char sign; scanf("%lld %lld", &n, &x); while (n--) { scanf("%c %c %lld", &sign, &sign, &d); (sign == '+') ? x += d : ((x >= d) ? x -= d : ct++); } printf("%lld %lld \n", x, ct); return EXIT_SUCCESS; } #endif //_CRT_NONSTDC_NO_WARNINGS<file_sep>// https://codeforces.com/contest/580/problem/A // https://codeforces.com/contest/580/submission/13753520 #include <stdio.h> #include <stdlib.h> int main() { int i,n,former,x,len,max_len; scanf("%d",&n); scanf("%d",&former); len = 1; max_len = 1; for (i=2;i<=n;i+=1) { scanf("%d",&x); if (x>=former) { len+=1; } else { if (len>max_len){max_len=len;} len = 1; } former = x; } if (len>max_len){max_len=len;} printf("%d",max_len); return 0; } <file_sep>// https://codeforces.com/contest/688/problem/A // https://codeforces.com/contest/688/submission/22867613 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <math.h> #include <algorithm> #include <string> #include <iostream> #include <vector> using namespace std; int main() { string s; int n, d; scanf("%d %d", &n, &d); int current = 0; int mx = 0; int cr = 0; for (int i = 0; i < d; ++i) { cin >> s; current = 0; for (int k = 0; k < n; ++k) { if (s[k] == '1') current++; } if (current == n) cr = 0; else cr++; if (cr > mx) mx = cr; } cout << mx; return 0; } <file_sep>// https://codeforces.com/contest/622/problem/A // https://codeforces.com/contest/622/submission/17340093 #include <iostream> using namespace std; int main() { long long n, i; cin >> n; for (i = 1; ((1 + i) * i )/ 2 < n; i++); cout << n - ((i - 1) * i) / 2; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/703/problem/A // https://codeforces.com/contest/703/submission/21342039 #include <stdio.h> #include <stdlib.h> int main() { int n, M = 0, C = 0, m, c; scanf("%d", &n); while (n--) { scanf("%d %d", &m, &c); if (m != c) { (m > c) ? M++ : C++; } } (M == C) ? puts("Friendship is magic!^^") : (M > C) ? puts("Mishka") : puts("Chris"); return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/334/problem/A // https://codeforces.com/contest/334/submission/18030157 #include <iostream> using namespace std; int main() { int n; cin >> n; for (int i = 1, t = 2; i <= n*n / 2; i++, t += 2) { cout << i << " " << n*n - i + 1 << " "; if (t % n == 0) cout << "\n"; } return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/1206/problem/B // https://codeforces.com/contest/1206/submission/67974231 #include <iostream> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cerr.tie(nullptr); long long negative = 0, positive = 0, zero = 0; long long n = 0, x = 0, cost = 0; cin >> n; while (n--) { cin >> x; if (x == 0) zero++; else if (x > 0) { cost += (x - 1); positive++; } else { cost += (-x - 1); negative++; } } if (negative % 2 == 1) { if (zero > 0) { zero--; cost++; } else { negative--; positive++; cost += 2; } } cost += zero; cout << cost; return 0; }<file_sep>// https://codeforces.com/contest/489/problem/B // https://codeforces.com/contest/489/submission/17433045 #include <iostream> #include <algorithm> using namespace std; int main() { int n, m, a[100], b[100]; cin >> n; for (int i = 0; i < n; i++) cin >> a[i]; cin >> m; for (int i = 0; i < m; i++) cin >> b[i]; sort(a, a + n, [](int left, int right) {return left > right; }); sort(b, b + m, [](int left, int right) {return left > right; }); int i = 0, j = 0, count = 0; while (i < n && j < m) { if (a[i] > b[j] + 1) i++; else if (b[j] > a[i] + 1) j++; else i++, j++, count++; } cout << count; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/732/problem/E // https://codeforces.com/contest/732/submission/21668163 #include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <vector> #include <map> #include <queue> using namespace std; typedef struct _STRUCT { int pow; int idx; }STRUCT; bool compStructs(STRUCT left, STRUCT right) { return (left.pow < right.pow); } STRUCT sockets[200005]; vector<int> adaptoare(200005, 0); vector<int> connected(200005, 0); map<int, queue<int>> comps; int n, m; int main() { int pw, u = 0, c = 0, k = 0, r = 0; scanf("%d %d", &n, &m); for (int i = 1; i <= n; ++i) { scanf("%d", &pw); comps[pw].push(i); } for (int i = 1; i <= m; ++i) scanf("%d", &sockets[i]), sockets[i].idx = i; sort(sockets + 1, sockets + m + 1, compStructs); for (int i = 1; i <= m; ++i) { k = 0; pw = sockets[i].pow; auto it = comps.find(pw); while (it == comps.end() && k < 33) { (pw % 2 == 0) ? r = 0 : r = 1; pw = pw / 2 + r; it = comps.find(pw); k++; } if (k > 32) { continue; } int first = (it->second).front(); (it->second).pop(); if (it->second.empty()) comps.erase(it); c++; u += k; adaptoare[sockets[i].idx] = k; connected[first] = sockets[i].idx; } printf("%d %d\n", c, u); for (int i = 1; i <= m; ++i) printf("%d ", adaptoare[i]); printf("\n"); for (int i = 1; i <= n; ++i) printf("%d ", connected[i]); return 0; }<file_sep># https://codeforces.com/contest/454/problem/A # https://codeforces.com/contest/454/submission/14543739 n = int(input()) k = 1 for i in range(1,n+1): for j in range(1,(n-k)//2+1): print('*',end='') for l in range(k): print('D',end='') for j in range(1,(n-k)//2+1): print('*',end='') if i<(n//2)+1: k+=2 else: k-=2 print() <file_sep>// https://codeforces.com/contest/327/problem/A // https://codeforces.com/contest/327/submission/15059968 #include <iostream> using namespace std; int v[101]; int main() { int n,no1=0,max,fin; cin>>n; for (int i = 1; i<=n;i++) { cin>>v[i]; if (v[i] == 1) no1++; } fin = 0; for (int i = 1; i<=n; i++) { max = no1; for (int j = i; j<=n;j++ ) { if (v[j] == 1) max--; else max++; if (max>fin) fin = max; } } cout<<fin; return 0; } <file_sep>// https://codeforces.com/contest/591/problem/A // https://codeforces.com/contest/591/submission/18018381 #include <iostream> #include <iomanip> using namespace std; int main() { int l, p, q; cin >> l >> p >> q; cout << setprecision(10) << (double)(l * p) / (p + q * 1.0); return EXIT_SUCCESS; }<file_sep>// https://www.spoj.com/problems/ABCPATH/ #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <map> #include <unordered_map> #include <set> #include <vector> #include <cstdio> #include <cstring> #include <queue> #include <string> using namespace std; #define ll long long #define ull unsigned long long /*------------------------------------------------------------------*/ char mat[55][55]; int vis[55][55]; int vec[30]; int h, w; int best = 0; int arrx[] = { -1,0,1,1,1,0,-1,-1 }; int arry[] = { -1,-1,-1,0,1,1,1,0 }; queue<pair<int, int>> boje; void citire() { string s; for (int i = 1; i <= h; ++i) { cin >> s; for (int j = 1; j <= w; ++j) { vis[i][j] = 0; mat[i][j] = s[j - 1]; if (mat[i][j] == 'A') boje.push(make_pair(i, j)); } } } void solve(int x, int y, char c, int current) { if (current > best) best = current; vis[x][y] = 1; int tx, ty; for (int i = 0; i < 8; ++i) { tx = arrx[i] + x; ty = arry[i] + y; if ((mat[tx][ty] == c + 1) && vis[tx][ty] == 0) solve(tx, ty, mat[tx][ty], current + 1); } } int main() { //ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); cin >> h >> w; pair<int, int> psd; int ct = 1; while (h != 0 && w != 0) { best = 0; citire(); while (!boje.empty()) { psd = boje.front(); boje.pop(); solve(psd.first, psd.second, mat[psd.first][psd.second], 1); } printf("Case %d: %d\n", ct, best); ct++; cin >> h >> w; } return 0; }<file_sep>// https://codeforces.com/contest/683/problem/C // https://codeforces.com/contest/683/submission/18526804 fun main(args: Array<String>) { var arr1 = IntArray(3000); var arr2 = IntArray(3000); var arr3 = IntArray(3000); val (line) = readLine()!!.split('\n') var y = line.split(Regex("\\s+")) var n1 = y[0].toInt(); var i = 1; while (i <= n1){ arr1[i] = y[i].toInt(); i++; } val (line2) = readLine()!!.split('\n') var y2 = line2.split(Regex("\\s+")) var n2 = y2[0].toInt(); i = 1; while (i <= n2){ arr2[i] = y2[i].toInt(); i++; } var k = 0; i = 1; while (i <= n1){ var j = 1; var p = 0; while (j <= n2){ if (arr1[i] == arr2[j]) p = 1; j++; } if (p == 0){ k++; arr3[k] = arr1[i]; } i++; } i = 1; while (i <= n2){ var j = 1; var p = 0; while (j <= n1){ if (arr2[i] == arr1[j]) p = 1; j++; } if (p == 0){ k++; arr3[k] = arr2[i]; } i++; } print(k); print(' '); i = 1; while (i <= k){ print(arr3[i]); print(' '); i++; } } <file_sep>// https://codeforces.com/problemset/problem/996/A // https://codeforces.com/contest/996/submission/49053280 #include <iostream> #include <fstream> #include <chrono> #include <iomanip> #include <algorithm> #include <string> #include <vector> #include <map> #include <set> #include <queue> #include <numeric> #include <bitset> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cerr.tie(nullptr); int n, r = 0; vector<int> v = { 100, 20, 10, 5,1 }; cin >> n; for (size_t i = 0; i < v.size(); ++i) { r += (n / v[i]); n = n % v[i]; } cout << r; return 0; }<file_sep>// https://codeforces.com/problemset/problem/1256/A // https://codeforces.com/contest/1256/submission/67693035 #include <iostream> #include <algorithm> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int queries; cin >> queries; while (queries--) { int a, b, n, s; cin >> a >> b >> n >> s; auto cat = (s / n); b = (b - s % n); cat -= min(cat, a); if (cat > 0) { b -= (cat * n); } (b < 0) ? cout << "NO\n" : cout << "YES\n"; } return 0; }<file_sep>// https://codeforces.com/contest/233/problem/A // https://codeforces.com/contest/233/submission/17701678 #include <iostream> using namespace std; int main() { int c; cin >> c; if (c & 1) puts("-1"); else for (int i = 1; i <= c; i += 2) cout << i + 1 << " " << i << " "; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/279/problem/B // https://codeforces.com/contest/279/submission/46925339 #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { std::ios::sync_with_stdio(false); cin.tie(NULL); int n, t; cin >> n >> t; vector<int> v(n, 0); for (int i = 0; i < n; ++i) cin >> v[i]; int p1 = 0, p2 = 0, s = 0, _max = 0; while (p1 < n && p2 < n) { if (p1 > p2) s += v[p2++]; else if (s > t) s -= v[p1++]; else { s += v[p2++]; if (s <= t) _max = max(_max, p2 - p1); } } cout << _max; return 0; }<file_sep>// https://codeforces.com/contest/835/problem/A // https://codeforces.com/contest/835/submission/29155915 // Example program #include <stdio.h> #include <string> #include <iostream> using namespace std; int mat[12][102][102]; int main() { int s, v1, v2, t1, t2, r1, r2 ; scanf("%d %d %d %d %d", &s, &v1, &v2, &t1, &t2); r1 = v1 * s + 2 * t1; r2 = v2 * s + 2 * t2; if (r1 < r2) cout << "First"; else if (r2 < r1 ) cout << "Second"; else cout << "Friendship"; return 0; } <file_sep># https://codeforces.com/contest/344/problem/A # https://codeforces.com/contest/344/submission/13589209 n = int(input()) nr = 0 prev = '-1' for _ in range(n): x = input() if x != prev: nr+=1 prev = x print(nr) <file_sep>// https://codeforces.com/contest/618/problem/A // https://codeforces.com/contest/618/submission/18010612 #include <iostream> using namespace std; int main() { int n, t, s; cin >> n; while (n > 0) { t = 0; s = 1; for (; s <= n; s <<= 1) t++; s >>= 1; n -= s; cout << t << " "; } return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/742/problem/A // https://codeforces.com/contest/742/submission/22766765 #include <iostream> using namespace std; int main() { int n, r; cin >> n; r = n % 4; if (n == 0) puts("1"); else if (r == 1) puts("8"); else if (r == 2) puts("4"); else if (r == 3) puts("2"); else if (r == 0) puts("6"); return 0; }<file_sep>// https://codeforces.com/contest/1091/problem/A // https://codeforces.com/contest/1091/submission/48048474 #include <iostream> #include <algorithm> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int y, b, r; cin >> y >> b >> r; b = min(r - 1, b); y = min(b - 1, y); cout << 3 * y + 3; return 0; }<file_sep>// https://codeforces.com/contest/507/problem/B // https://codeforces.com/contest/507/submission/18029581 #include <cstdio> #include <cstdlib> #include <cmath> int main() { long r, x1, y1, x2, y2; double dist, ct = 0; scanf("%ld %ld %ld %ld %ld", &r, &x1, &y1, &x2, &y2); dist = (sqrt(double(x1 - x2) * double(x1 - x2) + double(y1 - y2) * double(y1 - y2))); if (x1 == x2 && y1 == y2) goto out; ct = ceil(dist / r / 2.0); out: printf("%.0lf", ct); return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/628/problem/B // https://codeforces.com/contest/628/submission/47967159 #include <string> #include <iostream> using namespace std; inline uint8_t ToDigit(char c) { return c - '0'; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); string s; unsigned long long count = 0; cin >> s; if (ToDigit(s[0]) % 4 == 0) count = 1; for (size_t i = 1; i < s.size(); ++i) { if (ToDigit(s[i]) % 4 == 0) ++count; uint8_t nmb = ToDigit(s[i - 1]) * 10 + ToDigit(s[i]); if (nmb % 4 == 0) count += i; } cout << count; return 0; }<file_sep>// https://codeforces.com/contest/518/problem/A // https://codeforces.com/contest/518/submission/18055216 #include <string> #include <iostream> using namespace std; int main() { string s, t; size_t i; cin >> s >> t; for (i = s.size() - 1; i >= 0; i--) { if (s[i] != 'z') break; } s[i] = s[i] + 1; i++; for (; i < s.size(); i++) s[i] = 'a'; (s < t) ? cout << s : cout << "No such string\n"; return EXIT_SUCCESS; }<file_sep># https://codeforces.com/contest/450/problem/A # https://codeforces.com/contest/450/submission/15261021 n,m = map(int,input().split()) lis = list(map(int,input().split())) copii = [x for x in range(1, n+1 )] while lis != []: x = lis.pop(0) y = copii.pop(0) if (x-m) > 0 : lis.append(x-m) copii.append(y) print(y) <file_sep>// https://codeforces.com/contest/545/problem/B // https://codeforces.com/contest/545/submission/18454030 #include <iostream> #include <string> using namespace std; int main() { string a, b, rez = ""; int diffa = 0, diffb = 0, len; cin >> a >> b; len = a.size(); for (int i = 0; i < len; i++) { if (a[i] == b[i]) rez += a[i]; else { if (diffa > diffb) { diffb++; rez += b[i]; } else diffa++, rez += a[i]; } } if (diffa != diffb) rez = "impossible"; cout << rez; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/550/problem/C // https://codeforces.com/contest/550/submission/46638716 #include <iostream> #include <string> #include <map> #include <set> #include <vector> using namespace std; set<int> multiplii2; set<int> multiplii3; map<int, vector<int>> occurences; void BuildSet() { int i = 16; for (; i < 100; i = i + 8) multiplii2.insert(i); for (; i < 1000; i = i + 8) multiplii3.insert(i); } void BuildOcc(const std::string& str) { for (size_t i = 0; i < str.size(); ++i) { occurences[str[i] - '0'].push_back(i); } } bool Check1(int& res) { if (occurences[0].size() > 0) { res = 0; return true; } if (occurences[8].size() > 0) { res = 8; return true; } return false; } bool Check2(int& res) { for (const auto& m2 : multiplii2) { int d1 = m2 / 10; int d2 = m2 % 10; if (occurences[d1].size() > 0 && occurences[d2].size() > 0 && occurences[d1][0] < occurences[d2].back()) { res = m2; return true; } } return false; } bool Check3(int& res) { for (const auto& m3 : multiplii3) { int d1 = m3 / 100; int d2 = (m3 / 10) % 10; int d3 = m3 % 10; if (occurences[d1].size() > 0 && occurences[d2].size() > 0 && occurences[d3].size() > 0) { for (const auto& pos : occurences[d2]) { if (pos > occurences[d1][0] && pos < occurences[d3].back()) { res = m3; return true; } } } } return false; } int main() { string str; int res; cin >> str; BuildSet(); BuildOcc(str); if (Check1(res)) cout << "YES\n" << res; else if (Check2(res)) cout << "YES\n" << res; else if (Check3(res)) cout << "YES\n" << res; else cout << "NO\n"; return 0; } <file_sep>// https://codeforces.com/contest/683/problem/D // https://codeforces.com/contest/683/submission/18527258 fun main(args: Array<String>) { val (q) = readLine()!!.split('\n').map(String::toInt) var i = 1; while (i <= q){ val (n, m, p) = readLine()!!.split(' ').map(String::toInt) var j = 1; var o = 0; while (j <= n){ var k = 1; while (k <= m){ if (j * k == p) o = 1; k++; } j++; } if (o == 1) println("Yes") else println("No"); i++; } } <file_sep>// https://codeforces.com/contest/535/problem/B // https://codeforces.com/contest/535/submission/17147803 #include <iostream> using namespace std; int main() { int n = 0; char str[11]; cin >> str; for (int i = 0; i < strlen(str); i++) { n <<= 1; if (str[i] == '4') n++; else n += 2; } cout << n; return EXIT_SUCCESS; } <file_sep>// https://codeforces.com/contest/785/problem/B // https://codeforces.com/contest/785/submission/25527550 #include <iostream> #include <algorithm> #include <vector> using namespace std; typedef struct point{ int x; int y; }point; bool compare(const point& a, const point&b) { return a.x < b.x || (a.x == b.x && a.y < b.y); } bool compareb(const point& a, const point&b) { return a.y < b.y || (a.y == b.y && a.x < b.x); } int dist(const point& a, const point& b) { if (a.x <= b.x && b.x <= a.y) return 0; if (a.x <= b.y && b.y <= a.y) return 0; if (b.x <= a.x && a.x <= b.y) return 0; if (b.x <= a.y && a.y <= b.y) return 0; if (a.y < b.x) return b.x - a.y; return a.x - b.y; } int n, m; int mx = 0; vector<point> a, b; void bsearch(const point& x) { int mid, lo = 0, hi = m - 1, p =0; point k; while(lo <= hi) { mid = (lo + hi) / 2; k = b[mid]; p = dist(x, k); mx = max(p, mx); lo = mid + 1; } lo = 0, hi = m - 1; while (lo <= hi) { mid = (lo + hi) / 2; k = b[mid]; p = dist(x, k); mx = max(p, mx); hi = mid - 1; } } int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); point k; cin >> n; for(int i = 0; i< n; ++i) { cin >> k.x >> k.y; a.push_back(k); } cin >> m; for(int i = 0; i < m; ++i) { cin >> k.x >> k.y; b.push_back(k); } sort(a.begin(), a.end(), compare); sort(b.begin(), b.end(), compareb); for (int i = 0; i < n; ++i) bsearch(a[i]); sort(a.begin(), a.end(), compareb); sort(b.begin(), b.end(), compare); for (int i = 0; i < n; ++i) bsearch(a[i]); cout << mx; return 0; }<file_sep>// https://codeforces.com/contest/749/problem/C // https://codeforces.com/contest/749/submission/23153097 #include<string> #include<iostream> using namespace std; int main() { int n; string s; cin >> n >> s; string p; int D = 0; int R = 0; string q; while (s.size() != 1) { n = s.size(); p = ""; for (int i = 0; i < n; ++i) { if (s[i] == 'D') { if (D == 0) R--, p += 'D'; else D++; } else { if (R == 0) D--, p += 'R'; else R++; } } if (s == p) break; s = p; } cout << s[0]; return 0; }<file_sep>// https://codeforces.com/gym/100810/problem/H // https://codeforces.com/gym/100810/submission/18206141 #include <iostream> #include <vector> #include <string> #include <string.h> #include <cmath> #include <algorithm> using namespace std; typedef struct _TEAM { string name; int gD = 0, gP = 0, index, w = 0, d = 0, l = 0; _TEAM(const string& nume, const int& index) :name{ nume }, index{ index } { gD = 0, gP = 0, w = 0, d = 0, l = 0; }; }TEAM; vector<TEAM> tournament; string results[100][100]; int cautaEchipa(const string& teamName) { for (size_t i = 0; i < tournament.size(); ++i) { if (tournament[i].name == teamName) return i; } return -1; } void initEchipe(int nrEchipe) { for (int i = 0; i <= nrEchipe; i++) { for (int j = 0; j <= nrEchipe; j++) { results[i][j] = ""; } } } int getLen(int numar) { int nr = 0; if (numar == 0) return 1; for (; numar > 0; numar /= 10, nr++); return nr; } int main() { int nrEchipe = -1, meciuri, pozA, pozB; string echipa, teamA, teamB, score, del; int maxTeamName, maxime[10]; for (cin >> nrEchipe; nrEchipe != 0; cin >> nrEchipe) { maxTeamName = -1; tournament.clear(); del = "+"; initEchipe(nrEchipe); memset(maxime, 0, 10 * sizeof(int)); for (int i = 1; i <= nrEchipe; i++) { cin >> echipa; if ((int)echipa.size() > maxTeamName) maxTeamName = (int)echipa.size(); tournament.push_back(TEAM{ echipa,i }); } echipa = "|"; for (int i = 1; i <= maxTeamName; ++i) del += "-", echipa+=" "; del += "+"; for (int i = 1; i <= nrEchipe; ++i) del += "---+"; results[0][0] = echipa; for (int i = 0; i < nrEchipe; ++i) { echipa = "|"; teamA = "|"; if (tournament[i].name.size() == 1) echipa = echipa + tournament[i].name + " "; else if (tournament[i].name.size() == 2) echipa = echipa + tournament[i].name + " "; else echipa = echipa + tournament[i].name.substr(0, 3); if (i + 1 == nrEchipe) echipa += "|"; teamA += tournament[i].name; for (int k = (int)tournament[i].name.size(); k < maxTeamName; k++) teamA += " "; teamA += "|"; results[0][i+1] = echipa; results[i + 1][0] = teamA; } cin >> meciuri; for (int i = 1; i <= meciuri; ++i) { cin >> teamA >> teamB >> teamB >> score; pozA = cautaEchipa(teamA); pozB = cautaEchipa(teamB); results[pozA + 1][pozB + 1] = score; tournament[pozA].gD += score[0] - 48; tournament[pozA].gP += score[2] - 48; tournament[pozB].gD += score[2] - 48; tournament[pozB].gP += score[0] - 48; if (score[0] > score[2]) { tournament[pozA].w++; tournament[pozB].l++; } else if (score[0] < score[2]) { tournament[pozA].l++; tournament[pozB].w++; } else { tournament[pozA].d++; tournament[pozB].d++; } } cout << "RESULTS:\n" << del << "\n"; for (int i = 0; i <= nrEchipe; i++) { for (int j = 0; j <= nrEchipe; j++) { if (i != 0 && j != 0) { if (i == j) cout << " X |"; else if (results[i][j] == "") cout << " |"; else cout << results[i][j]<<"|"; } else { cout << results[i][j]; } } cout << "\n"<<del << "\n";; } cout <<"\nSTANDINGS:\n----------\n"; sort(tournament.begin(), tournament.end(), [&](const TEAM& teamA, const TEAM& teamB) { if (teamA.w * 3 + teamA.d != teamB.w * 3 + teamB.d) return (teamA.w * 3 + teamA.d > teamB.w * 3 + teamB.d); if (teamA.gD - teamA.gP != teamB.gD - teamB.gP) return (teamA.gD - teamA.gP > teamB.gD - teamB.gP); if (teamA.gD != teamB.gD) return (teamA.gD > teamB.gD); if (teamA.w != teamB.w) return (teamA.w > teamB.w); return (teamA.index > teamB.index); }); for (int i = 0; i < nrEchipe; i++) { maxime[0] = max(maxime[0], getLen(tournament[i].w + tournament[i].d + tournament[i].l)); maxime[1] = max(maxime[1], getLen(tournament[i].w)); maxime[2] = max(maxime[2], getLen(tournament[i].d)); maxime[3] = max(maxime[3], getLen(tournament[i].l)); maxime[4] = max(maxime[4], getLen(tournament[i].gD) + getLen(tournament[i].gP) + 1); maxime[5] = max(maxime[5], getLen(tournament[i].w * 3 + tournament[i].d)); } for (int i = 0; i < nrEchipe; i++) { if (nrEchipe >= 10 && i < 9) cout << " "; cout << i + 1 << ". "; echipa = tournament[i].name; for (int k = tournament[i].name.size(); k < maxTeamName; k++)echipa += " "; cout << echipa<<" "; teamA = ""; echipa = to_string(tournament[i].w + tournament[i].d + tournament[i].l); for (int k = echipa.size(); k < maxime[0]; k++) teamA += " "; teamA += echipa; cout << teamA << " "; teamA = ""; echipa = to_string(tournament[i].w); for (int k = echipa.size(); k < maxime[1]; k++) teamA += " "; teamA += echipa; cout << teamA << " "; teamA = ""; echipa = to_string(tournament[i].d); for (int k = echipa.size(); k < maxime[2]; k++) teamA += " "; teamA += echipa; cout << teamA << " "; teamA = ""; echipa = to_string(tournament[i].l); for (int k = echipa.size(); k < maxime[3]; k++) teamA += " "; teamA += echipa; cout << teamA << " "; teamA = ""; echipa = to_string(tournament[i].gD) + ":" + to_string(tournament[i].gP); for (int k = echipa.size(); k < maxime[4]; k++) teamA += " "; teamA += echipa; cout << teamA << " "; teamA = ""; echipa = to_string(tournament[i].w * 3 + tournament[i].d); for (int k = echipa.size(); k < maxime[5]; k++) teamA += " "; teamA += echipa; cout << teamA << "\n"; } cout << "\n"; } return EXIT_SUCCESS; }<file_sep># https://codeforces.com/contest/1/problem/A # https://codeforces.com/contest/1/submission/13419183 n,m,a=map(int,input().split()) nr1=int(n/a) if (int(n%a)>0): nr1+=1 nr2=int(m/a) if (int(m%a)>0): nr2+=1 print(nr1*nr2) <file_sep>// https://codeforces.com/contest/745/problem/B // https://codeforces.com/contest/745/submission/23059000 #include <iostream> #include <string> using namespace std; int main() { string s, cmp; int n, m; cin >> n >> m >> s; bool ok = true; bool x = false; while (--n) { cin >> cmp; if (s == cmp) goto peste; if (s.find('X') == string::npos && cmp.find('X') != string::npos) goto peste; if (s.find('X') != string::npos && cmp.find('X') == string::npos) goto peste; ok = false; peste: s = cmp; } (ok) ? puts("YES") : puts("NO"); return 0; }<file_sep>// https://codeforces.com/contest/580/problem/C // https://codeforces.com/contest/580/submission/46924788 #include <map> #include <vector> #include <iostream> using namespace std; int dfs(map<int, vector<int>>& graph, int maxCats, int currentNode, int currentCats, vector<bool>& cats, vector<bool>& visited) { (cats[currentNode]) ? currentCats++ : currentCats = 0; visited[currentNode] = true; if (currentCats > maxCats) return 0; int res = 0; bool leaf = true; for (auto& neighbour : graph[currentNode]) { if (visited[neighbour]) continue; leaf = false; res += dfs(graph, maxCats, neighbour, currentCats, cats, visited); visited[neighbour] = false; } if (leaf) return 1; return res; } int main() { ios::sync_with_stdio(false); cin.tie(NULL); int n, m, x, y; cin >> n >> m; map<int, vector<int>> graph; vector<bool> cats(n + 1, false); vector<bool> visited(n + 1, false); for (int i = 1; i <= n; ++i) { cin >> x; cats[i] = (x == 1); } for (int i = 0; i < n - 1; ++i) { cin >> x >> y; graph[x].push_back(y); graph[y].push_back(x); } cout << dfs(graph, m, 1, 0, cats, visited); return 0; }<file_sep>// https://codeforces.com/contest/573/problem/A // https://codeforces.com/contest/573/submission/17470800 #include <iostream> using namespace std; int main() { int a, n, rez; cin >> n >> a; for (; a % 2 == 0; a /= 2); for (; a % 3 == 0; a /= 3); rez = a; for (; n-1 > 0; n--) { cin >> a; for (; a % 2 == 0; a /= 2); for (; a % 3 == 0; a /= 3); if (a != rez) { puts("NO"); return 0; } } puts("YES"); return EXIT_SUCCESS; }<file_sep># https://codeforces.com/contest/577/problem/A # https://codeforces.com/contest/577/submission/14450756 n,k = map(int,input().split()) contor = 0 for i in range(1,n+1): if (k%i==0)and(k//i<=n): contor+=1 print(contor) <file_sep># https://codeforces.com/contest/281/problem/A # https://codeforces.com/contest/281/submission/13419952 s=input() print(s[0].capitalize(),s[1:len(s)],sep='') <file_sep>// https://codeforces.com/contest/746/problem/B // https://codeforces.com/contest/746/submission/23086002 #include <string> #include <iostream> using namespace std; int main() { int sz; string s; int ct = 0; cin >> sz >> s; string p; while (sz--) { if (sz & 1) p = s[0] + p; else p = p + s[0]; s = s.substr(1, s.size() - 1); } cout << p; return 0; }<file_sep>// https://codeforces.com/contest/835/problem/B // https://codeforces.com/contest/835/submission/29156583 // Example program #include <stdio.h> #include <string> #include <iostream> #include <algorithm> using namespace std; int v[10]; int main() { int k, s = 0, res = 0, pk = 0; cin >> k; getchar(); for(char c = getchar(); c!='\n'; c = getchar()) { v[c-'0']++; s += (c-'0'); } res = max(0, k - s); for (int i = 0; i < 10 && res ;++i) { if(!v[i])continue; k = (9 - i) * v[i]; if (k - res >= 0) { pk += (res / (9-i) + (res %(9-i) !=0)); res = 0; } else { res -= k; pk += v[i]; } } cout<<pk; return 0; } <file_sep>// https://codeforces.com/contest/752/problem/A // https://codeforces.com/contest/752/submission/23309643 #include <iostream> #include <stdio.h> using namespace std; int main() { int n, m, k, lanes, desks; char c; scanf("%d %d %d", &n, &m, &k); c = (k & 1) ? 'L' : 'R'; lanes = k / (2 * m ) + 1; if (k % (2 * m) == 0) lanes--; k = k - (lanes - 1) * (2 * m); desks = (k - 1) / 2 + 1; printf("%d %d %c\n", lanes, desks, c); return 0; }<file_sep># https://codeforces.com/contest/41/problem/A # https://codeforces.com/contest/41/submission/13583435 def is_correct(s,t): if len(s) != len(t): return 'NO' for i in range(len(s)): if s[i] != t[len(t)-1-i]: return 'NO' return 'YES' s=input() t=input() print(is_correct(s,t)) <file_sep># https://codeforces.com/contest/200/problem/B # https://codeforces.com/contest/200/submission/14572603 n = int(input()) s = sum(list(map(int,input().split()))) print("%.12f" %float(s/n)) <file_sep>// https://codeforces.com/contest/670/problem/A // https://codeforces.com/contest/670/submission/30912901 #include <iostream> #include <algorithm> using namespace std; inline int GetMin(const int& n) { switch (n % 7) { case 6: return (n / 7) * 2 + 1; default: return (n / 7) * 2; } } inline int GetMax(const int& n) { switch (n % 7) { case 0: return (n / 7) * 2; case 1: return (n / 7) * 2 + 1; default: return (n / 7) * 2 + 2; } } int main() { int n = 0; cin >> n; cout << GetMin(n) << " " << GetMax(n); return 0; }<file_sep>// https://codeforces.com/contest/538/problem/B // https://codeforces.com/contest/538/submission/17462106 #include <iostream> using namespace std; int main() { int n, v[10], max = 0; bool ok; memset(v, 0, 10 * sizeof(int)); cin >> n; for (int i = 1; n != 0; n /= 10, ++i) { v[i] = n % 10; if (v[i] > max) max = v[i]; } cout << max << endl; for (int i = 1; i <= max; i++) { ok = false; for (int j = 9; j > 0; j--) { if (v[j] != 0) ok = true, putchar('1'), v[j]--; else if (v[j] == 0 && ok) putchar('0'); } putchar(' '); } return EXIT_SUCCESS; }<file_sep># https://codeforces.com/contest/58/problem/A # https://codeforces.com/contest/58/submission/13420486 s=input() h=s.find('h') e=s.find('e',h) l1=s.find('l',e) l2=s.find('l',l1+1) o=s.find('o',l2) if (h<e and e<l1 and l1<l2 and l2<o): print("YES") else: print("NO") <file_sep>// https://codeforces.com/problemset/problem/1207/A // https://codeforces.com/contest/1207/submission/67692150 #include <iostream> #include <algorithm> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int query; cin >> query; while (query--) { int buns, beefs, chickens, priceBeef, priceChicken; cin >> buns >> beefs >> chickens >> priceBeef >> priceChicken; int profit = 0; if (priceBeef < priceChicken) { swap(priceBeef, priceChicken); swap(beefs, chickens); } auto hamburgers = min(buns / 2, beefs); profit += (hamburgers * priceBeef); buns -= (hamburgers * 2); hamburgers = min(buns / 2, chickens); profit += (hamburgers * priceChicken); cout << profit << endl; } return 0; }<file_sep>// https://codeforces.com/contest/501/problem/A // https://codeforces.com/contest/501/submission/16639055 #include <iostream> #include <algorithm> using namespace std; int main() { int a, b, c, d, m1, m2; cin >> a >> b >> c >> d; m1 = max(3 * a / 10, a - a / 250 * c); m2 = max(3 * b / 10, b - b / 250 * d); if (m1 > m2) cout << "Misha"; else if (m1 == m2) cout << "Tie"; else cout << "Vasya"; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/525/problem/A // https://codeforces.com/contest/525/submission/17557255 #include <iostream> #include <string> using namespace std; int main() { string s; int n, ABC[27], nr, i; memset(ABC, 0, 27 * sizeof(int)); cin >> n >> s; for (i = 0, nr = 0; i < s.size(); i++){ if (i & 1) { if (ABC[s[i] - 'A']) ABC[s[i] - 'A'] -- ; else nr++; } else ABC[s[i] - 'a'] ++; } cout << nr; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/516/problem/A // https://codeforces.com/contest/516/submission/17291786 #include <iostream> #include <string> #include <algorithm> void ptchar(std::string& s) { char x = getchar(); if (x == '2' || x == '3' || x == '5' || x == '7') s+=x; else if (x == '4') s += "322"; else if (x == '6') s += "53"; else if (x == '8') s += "2227"; else if (x == '9') s += "3327"; } int main() { int n; std::string s; std::cin >> n; getchar(); for (; n > 0; n--) ptchar(s); std::sort(s.begin(), s.end(), [](const char l, const char r) {return (r < l); }); std::cout << s; return EXIT_SUCCESS; } <file_sep>// https://codeforces.com/contest/567/problem/B // https://codeforces.com/contest/567/submission/17567475 #include <iostream> using namespace std; int main() { int n, max = 0, curr = 0, numb; char x, v[1000001]; memset(v, '0', 1000001 * sizeof(char)); cin >> n; for (; n > 0; n--) { getchar(); x = getchar(); cin >> numb; if (x == '+') { curr++; v[numb] = '1'; } else { if (v[numb] == '0') max++; else curr--, v[numb] = '0'; } if (curr > max) max = curr; } cout << max; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/problemset/problem/1220/A // https://codeforces.com/contest/1220/submission/67693181 #include <iostream> #include <algorithm> #include <string> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); string s; int z, n; cin >> z >> s; z = 0; n = 0; for (const auto& c : s) { if (c == 'z') z++; else if (c == 'n') n++; } while (n--) cout << "1 "; while (z--) cout << "0 "; return 0; }<file_sep>// https://codeforces.com/contest/735/problem/C // https://codeforces.com/contest/735/submission/22543505 #include<iostream> using namespace std; int main() { unsigned long long F0, F1; unsigned long long n; cin >> n; F0 = 1; F1 = 2; unsigned long long aux, nr=0; while (n >= F1) { aux = F1; F1 = F1+F0; F0 = aux; nr++; } cout << nr; }<file_sep># https://codeforces.com/contest/271/problem/A # https://codeforces.com/contest/271/submission/13478547 def read(): """ Read an integer n. @restrictions: 1000<=n<=9000 @output: n - the year number """ return(int(input())) def distinct_digits(n): """ Check if a number (n) has only distincts digits. @input: n - an integer @output: True - if n has only distincts digits False - otherwise """ v=[] # A list of digits frequency #initialize list with 0 for i in range(10): v.append(0) ok=True # we assume that n has only distincts digits while (n>0 and ok==True): v[n%10]+=1 if v[n%10]>1: ok=False else: n=n//10 return ok def find(n): """ Find the smallest value that is strictly larger than n and all it's digits are distincts @input: n - a given integer @output: the value that we search for @restrictions: it is guaranteed that the answer exists """ n+=1 while distinct_digits(n)!=True: n+=1 return n n=read() print(find(n)) <file_sep># https://codeforces.com/contest/119/problem/A # https://codeforces.com/contest/119/submission/13478295 def read(): """ Read three integers: a,b,n. @restrictions: 1<=a,b,n<=100 @output: a - number that Simon receives b - number that Antisimon receives n - the number of stones in heap at start. """ a,b,n=map(int, input().split()) return a,b,n def gcd(x,y): """ Calculate the greatest common divisor of x and y using Euclid's algorithm. @input: x,y @output: greatest common divisor of x and y. """ while y!=0: r=y y=x%y x=r return x def play(a,b,n): """ The steps of playing the game. @input: a - number that Simon receives b - number that Antisimon receives n - the number of stones in heap at start. @output: 0 - if Simon wins 1 - if Antisimon wins """ #tour variable can have 2 values: 1 if it's Simon turns or -1 if it's Antisimon's tour=1 while n>0: if tour == 1: k=a else: k=b n=n-gcd(k,n) tour=-tour if tour==1: return 1 else: return 0 a,b,n=read() print(play(a,b,n)) <file_sep>// https://codeforces.com/contest/474/problem/B // https://codeforces.com/contest/474/submission/15134437 #include <iostream> using namespace std; struct entity { int first_in_pile,last_in_pile; }; entity piles[100001]; int search_bin(int lo, int hi, int x) { int mid = (lo+hi) / 2; while (lo <= hi) { if (piles[mid].first_in_pile > x) hi = mid - 1; else if (piles[mid].last_in_pile < x) lo = mid + 1; else return mid; mid = (lo + hi) / 2; } } int main() { int m,x,n,worms = 0; cin >> n; for (int i = 1; i <= n; i++) { cin >> x; piles[i].first_in_pile = worms + 1; piles[i].last_in_pile = worms + x; worms += x; } cin >> m; for (int i = 1; i <= m; i++) { cin >> x; cout << search_bin(1,n,x)<<"\n"; } return 0; } <file_sep># https://codeforces.com/contest/4/problem/A # https://codeforces.com/contest/4/submission/13404456 w=input() if (int(w)%2==1 or int(w)==2): print("NO") else: print("YES") <file_sep>// https://codeforces.com/contest/20/problem/C // https://codeforces.com/contest/20/submission/48035394 #include <map> #include <queue> #include <vector> #include <iostream> #include <algorithm> #include <cstdio> using namespace std; void BellmanFord(int Edges, map<int, vector<pair<int, int>>> & Graph, int Source, vector<long long>& Distance, vector<int>& Parent) { priority_queue<int> q; Distance = vector<long long>(Edges + 1, std::numeric_limits<long long>::max()); Parent = vector<int>(Edges + 1, 0); q.push(Source); Distance[Source] = 0; while (!q.empty()) { auto current = q.top(); q.pop(); for (const auto& keyValuePair : Graph[current]) { auto target = keyValuePair.first; auto weight = keyValuePair.second; if (Distance[current] + weight < Distance[target]) { Parent[target] = current; Distance[target] = Distance[current] + weight; q.push(target); } } } } void PrintPath(vector<int>& Parent, int index) { if (index == 0) return; PrintPath(Parent, Parent[index]); printf("%d ", index); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, m, x, y, w; cin >> n >> m; map<int, vector<pair<int, int>>> graph; vector<long long> distance; vector<int> parent; for (int i = 1; i <= m; ++i) { cin >> x >> y >> w; graph[x].push_back({ y,w }); graph[y].push_back({ x,w }); } BellmanFord(n, graph, 1, distance, parent); if (distance[n] == numeric_limits<long long>::max()) { cout << "-1\n"; } else { PrintPath(parent, n); } return 0; }<file_sep># https://codeforces.com/contest/266/problem/A # https://codeforces.com/contest/266/submission/13408006 n=int(input()) s=input() nr=0 for i in range(1,len(s)): if s[i]==s[i-1]: nr+=1 print(nr) <file_sep># https://codeforces.com/contest/337/problem/A # https://codeforces.com/contest/337/submission/13961119 n,m=map(int,input().split()) l=list(map(int,input().split())) l.sort() mins=1000 for i in range(0,len(l)-n+1): if l[i+n-1]-l[i]<mins: mins=l[i+n-1]-l[i] print(mins) <file_sep>// https://codeforces.com/contest/679/problem/A // https://codeforces.com/contest/679/submission/18453358 #include <iostream> #include <string> using namespace std; int main() { int lst[] = { 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71 }; int i, cnt = 0, nr, tmp = 0; string s; for (i = 1; i <= 20; i++) { cout << lst[i - 1] << "\n"; fflush(stdout); cin >> s; fflush(stdin); if (s == "yes") nr = lst[i - 1], cnt++; if (cnt > 0) break; } for (; i < 20; i++) { (nr*lst[i - 1] <= 100) ? cout << nr*lst[i - 1] << "\n" : cout << lst[i] << " "; fflush(stdout); cin >> s; fflush(stdin); if (s == "yes") cnt++; if (cnt > 1) break; } fflush(stdout); (cnt > 1) ? puts("composite") : puts("prime"); return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/789/problem/B // https://codeforces.com/contest/789/submission/25930709 #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <map> #include <unordered_map> #include <set> #include <vector> #include <cstdio> #include <string> using namespace std; #define ll long long #define ull unsigned long long /*------------------------------------------------------------------*/ unordered_map < long long , bool > in; long long b1, q, l, m, x; int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); cin >> b1 >> q >> l >> m; for(int i = 1; i<=m; ++i) { cin >> x; in[x] = true; } long long cnt = 0; long long last = b1; while (b1 != 0 && abs(b1) <= l) { if (in.find(b1) == in.end()) cnt++; b1 *= q; if (abs(b1) == last || b1 == last) break; last = b1; } if(b1 == 0 ) { if (in.find(b1) == in.end()) cnt = -1; } else if ( (abs(b1) == last || b1 == last) && abs(b1) <= l) { if (in.find(b1) == in.end()) cnt = -1; if (q == -1) { if (in.find(b1) == in.end() || in.find(-b1) == in.end()) cnt = -1; } } if (cnt == -1)cout << "inf\n"; else cout << cnt; return 0; }<file_sep>// https://codeforces.com/gym/100810/problem/G // https://codeforces.com/gym/100810/submission/18255909 #include <iostream> #include <vector> #include <map> using namespace std; map<int, vector<int>> frecv; int cd[200005], ord[200005]; int main() { int poz, max, n, m, x; bool ok; for (cin >> n >> m; n != 0 && m != 0; cin >> n >> m) { ok = true; frecv.clear(); for (int i = 0; i <= 200002; i++) cd[i] = -1, ord[i] = -1; for (int i = 1; i <= n; i++) { cin >> x; poz = -1; max = -1; for (int j = 1; j <= m; j++) { if (cd[j] <= x && cd[j] >= max) { max = cd[j]; poz = j; } } if (poz == -1) ok = false; else { cd[poz] = x; frecv[x].push_back(poz); } ord[i] = poz; } if (!ok) cout << "Transportation failed\n"; else { for (int i = 1; i <= n; i++) { cout << ord[i]<<" "; } cout << "\n"; for (auto it = frecv.begin(); it != frecv.end(); it++) { for (int j = 0; j < (int)it->second.size(); j++) { cout << it->second[j]<< " "; } } cout << "\n"; } } return 0; }<file_sep>// https://codeforces.com/contest/705/problem/A // https://codeforces.com/contest/705/submission/21340464 #include <stdio.h> #include <stdlib.h> int main() { int n, i = 0; scanf("%d", &n); for (i = 1; i < n; ++i) { (i % 2 == 0) ? printf("I love that ") : printf("I hate that "); } (n % 2 == 0) ? printf("I love it") : printf("I hate it"); return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/146/problem/A // https://codeforces.com/contest/146/submission/17291944 #include <iostream> #include <string> int main() { int n, s1 = 0, s2 = 0; std::string nm; std::cin >> n >> nm; for (int i = 0; i < n / 2; i++) { if (nm[i] != '4' && nm[i] != '7' || nm[n - i - 1] != '4' && nm[n - i - 1] != '7') { std::cout << "NO"; goto EXIT; } else { s1 += nm[i] - '0'; s2 += nm[n - i - 1] - '0';} } if (s1 != s2) std::cout << "NO"; else std::cout << "YES"; EXIT: return EXIT_SUCCESS; }<file_sep># https://codeforces.com/contest/118/problem/B # https://codeforces.com/contest/118/submission/14544078 n = int(input()) k = n for i in range(1,n+n+2): for j in range(1,k+1): print(' ',end=' ') for j in range(n-k+1): if n-k==0: print(j,sep=' ',end='') else: print(j,sep=' ',end=' ') for j in range(n-k): if j==n-k-1: print(n-k-j-1,sep=' ',end='') else: print(n-k-j-1,sep=' ',end=' ') if i<=n: k-=1 else: k+=1 print() <file_sep>// https://codeforces.com/contest/733/problem/A // https://codeforces.com/contest/733/submission/22040766 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> #include <map> #include <vector> #include <string> #include <iostream> using namespace std; #define MIN(a,b) (((a) < (b)) ? (a) : (b)) #define MAX(a,b) (((a) > (b)) ? (a) : (b)) #define ABS(a) (((a) > 0) ? (a) : (-(a))) bool is_vowel(const char& c) { return(c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' || c == 'Y'); } int main() { string s; int start = -1; unsigned int ability = 0; cin >> s; size_t size = s.size(); for (size_t i = 0; i < size; ++i) { if (is_vowel(s[i])) { ability = MAX(ability, i - start); start = i; } } ability = MAX(ability, size - start); printf("%d\n", ability); return EXIT_SUCCESS; }<file_sep># https://codeforces.com/contest/263/problem/A # https://codeforces.com/contest/263/submission/13580409 for i in range(5): x=list(map(int, input().split())) for j in range(5): if x[j]==1: ax,ay=i+1,j+1 x.clear() print(abs(3-ax)+abs(3-ay)) <file_sep>// https://codeforces.com/contest/675/problem/D // https://codeforces.com/contest/675/submission/47971947 #include <iostream> #include <map> #include <set> #include <algorithm> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); map<int, int> kinder; set<int> bst; int n, x; cin >> n >> x; bst.insert(x); for (int i = 1; i < n; ++i) { cin >> x; auto smaller = --bst.lower_bound(x); int parent = 0; if (smaller != bst.end()) { if (kinder[*smaller] != 0) smaller = bst.upper_bound(*smaller); parent = *smaller; } else { parent = *bst.upper_bound(x); } if (parent <= x) kinder[parent] = x; bst.insert(x); cout << parent << " "; } return 0; }<file_sep># https://codeforces.com/contest/472/problem/A # https://codeforces.com/contest/472/submission/13580206 n = int(input()) from math import sqrt def e_prim(k): if k==1: return False for d in range(2,int(sqrt(n))+1): if k%d==0: return False return True if n % 2 == 0: print(n-4, 4) else: k=4 while e_prim(n-k) == True: k=k+2 print(k, n-k) <file_sep>// https://www.spoj.com/problems/FARIDA/ #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <map> #include <unordered_map> #include <set> #include <vector> #include <cstdio> #include <string> using namespace std; #define ll long long #define ull unsigned long long /*------------------------------------------------------------------*/ ull sol[10009], ptc[10009]; int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); int n, t; cin >> t; for(int j = 1; j<=t; ++j){ cin >> n; for (int i = 1; i <= n; ++i)cin >> ptc[i]; sol[1] = ptc[1]; for (int i = 2; i <= n; ++i) sol[i] = max(sol[i - 2] + ptc[i], sol[i - 1]); cout <<"Case "<< j<<": "<< sol[n]<<"\n"; } return 0; }<file_sep>// https://codeforces.com/contest/278/problem/A // https://codeforces.com/contest/278/submission/17335998 #include <iostream> #include <algorithm> void swap(int&x, int&y) { int aux; aux = x; x = y; y = aux; } int main() { int n, v[105], x, y; v[1] = v[0] = 0; std::cin >> n; for (int i = 2; i <= n + 1; i++) { std::cin >> x; v[i] = v[i - 1] + x; } std::cin >> x >> y; if (x > y) swap(x, y); std::cout << std::min(v[y] - v[x], v[x] + v[n + 1] - v[y]); return EXIT_SUCCESS; } <file_sep>// https://codeforces.com/contest/630/problem/J // https://codeforces.com/contest/630/submission/17323407 #include <iostream> int main() { unsigned long long n; std::cin >> n; std::cout << n / 2520; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/754/problem/A // https://codeforces.com/contest/754/submission/24060119 #include <iostream> #include <vector> using namespace std; int main() { int v[105], n; vector<pair<int, int>>res; cin >> n; for (int i = 1; i <= n; ++i) cin >> v[i]; int zer = 1; int st = 1; while (v[zer] == 0) zer++; while (zer <= n) { int end = zer; for (int i = zer + 1; i <= n && v[i] == 0; end = i, ++i); res.push_back(make_pair(st, end)); st = zer = ++end; } if (res.size() == 0) cout << "NO"; else { cout << "YES\n" << res.size() << "\n"; for (auto e : res) cout << e.first << " " <<e.second <<"\n"; } return 0; }<file_sep>// https://codeforces.com/contest/363/problem/B // https://codeforces.com/contest/363/submission/46625690 /****************************************************************************** Online C++ Compiler. Code, Compile, Run and Debug C++ program online. Write your code in this editor and press "Run" button to compile and execute it. *******************************************************************************/ #include <iostream> #include <vector> using namespace std; int main() { int n, k, x; long long min = 0; int idx = 0; vector<long long> v; vector<long long> qp; cin >> n >> k; for(int i = 0; i < n; ++i) { cin >> x; v.push_back(x); qp.push_back(x); } for(int i = 1; i < k; ++i) { qp[i] += qp[i-1]; } min = qp[k-1]; for(int i = k; i < n; ++i) { qp[i] = qp[i] + qp[i-1] - v[i-k]; if(qp[i] < min) { min = qp[i]; idx = i - k + 1; } } cout << idx + 1; return 0; }<file_sep>// https://codeforces.com/contest/787/problem/A // https://codeforces.com/contest/787/submission/25738084 #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <map> #include <unordered_map> #include <set> #include <vector> #include <cstdio> #include <string> using namespace std; #define ll long long #define ull unsigned long long /*------------------------------------------------------------------*/ int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); int a, b, c, d; cin >> a >> b >> c >> d; unordered_map<int, int> mp; int ans = -1; for(int i = 0; i<= 50000; ++i) { mp[b + a * i] = 1; } for(int i = 0; i<=50000; ++i) { if(mp.find(d + i * c) != mp.end()) { ans = d + i * c; break; } } cout << ans; return 0; }<file_sep>// https://codeforces.com/contest/606/problem/B // https://codeforces.com/contest/606/submission/17916859 #include <iostream> #include <string> using namespace std; int main() { int n, m, x, y, sm = 1, i; int mat[505][505]; memset(mat, 0, 505 * 505 * sizeof(int)); string s; cin >> n >> m >> x >> y >> s; mat[x][y] = 1; cout << "1 "; for (i = 0; i < (int)s.size() - 1; ++i) { if (s[i] == 'D') { x++; if (mat[x][y] == 0) { if (x > n) cout << "0 ", x--; else cout << "1 ", sm++, mat[x][y] = 1; } else { cout << "0 "; } } if (s[i] == 'U') { x--; if (mat[x][y] == 0) { if (x < 1) cout << "0 ", x++; else cout << "1 ", sm++, mat[x][y] = 1; } else { cout << "0 "; } } if (s[i] == 'R') { y++; if (mat[x][y] == 0) { if (y > m) cout << "0 ", y--; else cout << "1 ", sm++, mat[x][y] = 1; } else { cout << "0 "; } } if (s[i] == 'L') { y--; if (mat[x][y] == 0) { if (y < 1) cout << "0 ", y++; else cout << "1 ", sm++, mat[x][y] = 1; } else { cout << "0 "; } } } cout << m*n - sm; return EXIT_SUCCESS; }<file_sep># https://codeforces.com/contest/339/problem/A # https://codeforces.com/contest/339/submission/13408149 s=input() v=[0, 0, 0, 0] for i in range(len(s)): if s[i]=="1": v[1]+=1 elif s[i]=="2": v[2]+=1 elif s[i]=="3": v[3]+=1 nr=0 i=0 for i in range(4): while v[i]>0: print(i,end='') nr+=1 if nr<len(s): print("+",end='') nr+=1 v[i]-=1 <file_sep>// https://codeforces.com/contest/719/problem/A // https://codeforces.com/contest/719/submission/22851797 #include <iostream> using namespace std; int main() { int n; int a,b; cin>>n; cin>>b; for(int i = 2; i<=n; ++i) { a = b; cin>>b; } if (b == 0) puts("UP"); else if (b == 15) puts("DOWN"); else if (n == 1) puts("-1"); else if (b - a > 0) puts("UP"); else puts("DOWN"); return 0; }<file_sep># https://codeforces.com/contest/379/problem/A # https://codeforces.com/contest/379/submission/13583372 n,m = map(int,input().split()) nr = n while n // m > 0: notlighted = n % m nr += n//m n = n//m + notlighted print(nr) <file_sep>// https://codeforces.com/contest/43/problem/A // https://codeforces.com/contest/43/submission/18055085 #include <string> #include <iostream> using namespace std; int main() { string read, a, ot; int scoreA = 0, scoreB = 0, n; cin >> n; cin >> a; scoreA++; for (; n > 1; n--) { cin >> read; if (a == read) scoreA++; else scoreB++, ot = read; } (scoreA > scoreB) ? cout<<a : cout<<ot; return EXIT_SUCCESS; }<file_sep># https://codeforces.com/contest/160/problem/A # https://codeforces.com/contest/160/submission/13419910 n=int(input()) v=list(map(int,input().split())) v.sort() sum=0 for i in range(n): sum+=v[i] ok="true" i=n-1 sumax=v[i] while (ok=="true"): if sumax>sum-sumax: ok="false" else: i-=1 sumax+=v[i] print(n-i) <file_sep>// https://codeforces.com/contest/492/problem/A // https://codeforces.com/contest/492/submission/13875822 #include <stdio.h> #include <stdlib.h> int main() { int n,s,i; scanf("%d",&n); s = 0; i = 0; while (s<=n) { i++; s = s+ ((1+i)*i)/2; } printf("%d",i-1); return 0; } <file_sep>// https://codeforces.com/contest/908/problem/A // https://codeforces.com/contest/908/submission/46923986 #include <iostream> #include <string> using namespace std; inline bool ShouldFlip(char c) { switch (c) { case 'a': case 'e': case 'i': case 'o': case 'u': case '1': case '3': case '5': case '7': case '9': return true; default: return false; } } int main() { std::ios::sync_with_stdio(false); cin.tie(NULL); string s; int nr = 0; cin >> s; for (auto& c : s) { if (ShouldFlip(c)) nr++; } cout << nr; return 0; }<file_sep>#include <iostream> #include <fstream> #include <chrono> #include <iomanip> #include <algorithm> #include <string> #include <vector> #include <map> #include <set> #include <queue> #include <numeric> #include <bitset> using namespace std; class Node { friend class Trie; public: Node() = default; ~Node() { for (auto& node : Children) delete node.second; } private: map<char, Node*> Children; size_t Words = 0; }; class Trie { public: Trie() { Root = new Node(); } ~Trie() { delete Root; } bool InsertUnique(const string& String) { auto current = Root; bool ok = false; for (auto& c : String) { if (current->Children.find(c) == current->Children.end()) { current->Children[c] = new Node(); ok = true; } current = current->Children[c]; if (current->Words != 0) { return false; } } current->Words++; return ok; } private: Node* Root; }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cerr.tie(nullptr); int t, n; cin >> t; while (t--) { cin >> n; Trie trie; string s; bool ok = true; for (int i = 1; i <= n; ++i) { cin >> s; ok = ok && trie.InsertUnique(s); } (ok) ? cout << "YES\n" : cout << "NO\n"; } return 0; }<file_sep>// https://codeforces.com/contest/1006/problem/A // https://codeforces.com/contest/1006/submission/46828520 #include <iostream> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(NULL); int n, x; cin >> n; while (n--) { cin >> x; if ((x & 1) == 0) --x; cout << x << " "; } return 0; }<file_sep>// https://codeforces.com/contest/672/problem/A // https://codeforces.com/contest/672/submission/17927943 #include <iostream> using namespace std; int main() { int n, c, i, k; cin >> n; for (i = 1, c = 1; i < n && i <= 9; i++, c++); for (i = 10, k = 10; i <= n && k<=99; i += 2, k++) { if (i == n) c = k / 10; else if (i + 1 == n) c = k % 10; } for (k = 100; i <= n; i += 3, k++) { if (i == n) c = k / 100; else if (i + 1 == n) c = (k / 10) % 10; else if (i + 2 == n) c = k % 10; } cout << c; return EXIT_SUCCESS; }<file_sep># https://codeforces.com/contest/612/problem/A # https://codeforces.com/contest/612/submission/15041261 def gaseste(a,b,n): gasit = False k = 0 while k * a <= n and not gasit: p = 0 while (p * b) + (k*a) <= n and not gasit: if (p*b)+(k*a) == n: gasit = True else: p+=1 if not gasit: k+=1 return (-1,-1) if not gasit else (k,p) n,p,q = map(int,input().split()) s = input() a,b = gaseste(p,q,n) if (a,b) != (-1,-1): i = 0 print(a+b) while a > 0: print(s[i:i+p]) i+=p a -=1 while b>0: print(s[i:i+q]) i+=q b-=1 else: print(-1) <file_sep># https://codeforces.com/contest/82/problem/A # https://codeforces.com/contest/82/submission/13476587 n=int(input()) nr=5 i=1 k=1 while nr<n: k=k*2 + 1 nr=5*k i=i*2 cont=1 while nr-i+1>n: nr=nr-i cont+=1 if cont==1: strn='Howard' elif cont==2: strn='Rajesh' elif cont==3: strn='Penny' elif cont==4: strn='Leonard' else: strn='Sheldon' print(strn) <file_sep>// https://www.spoj.com/problems/TEST/ #include <iostream> #include <bits/stdc++.h> using namespace std; int main() { int x; cin >> x; while(x!=42) { cout<<x <<endl; cin>>x; } return 0; } <file_sep># https://codeforces.com/contest/122/problem/A # https://codeforces.com/contest/122/submission/13477054 def is_lucky(a): """ Check if a given number (a) is lucky. @input: an integer a (1<=a<=1000) @output: True - if a is lucky False - if a is not lucky """ ok=True # We assume that a is lucky while (a>0 and ok==True): if (int(a%10) == 4 or int(a%10) == 7): a=a//10 else: ok=False return ok def almost_lucky(n): """ Check if a given number (n) is almost lucky. @input: an integer n (1<=n<=1000) @output: True - if n is almost lucky False - if n is not almost lucky """ # n is "almost lucky" if n is lucky if (is_lucky(n)==True): ok=True else: ok=False #If n is not lucky, we check to to see if it is "almost lucky" d=2 while (d<=n//2 and ok==False): if (int(n%d)==0 and is_lucky(d)==True): ok=True else: d+=1 return ok def citire(): """ Read an integer. @output: an integer n (1<=n<=1000) """ return int(input()) n=citire() #read n if (almost_lucky(n)==True): print("YES") else: print("NO") <file_sep>// https://codeforces.com/gym/101020/problem/A // https://codeforces.com/gym/101020/submission/18653242 #include <iostream> using namespace std; int main() { long long x, y,t; for (cin >> t; t-- > 0; cin >> x >> y, cout << x*y << '\n'); return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/581/problem/C // https://codeforces.com/contest/581/submission/14394891 #include <iostream> using namespace std; int main() { long long v[102],n,k,x; for (int i = 0; i < 101; i++) v[i] = 0; cin >> n >> k; for (int i = 0; i < n; i++) { cin >> x; v[x]++; } long long aux = k; while (k > 0) { for (int p = 1; p <= 10; p++) { for (int i = 100 - p; i >= 0; i -= 10) { while (v[i] > 0 && k - p >= 0) { v[i + p]++; v[i]--; k -= p; } } } if (k == aux) k = 0; aux = k; } unsigned long long s = 0; for (int i = 1; i <= 100; i++) { s += ((i / 10) * v[i]); } cout << s; return 0; } #include <iostream> using namespace std; int a[102]; int main() { int n,x; long long k; cin >> n >> k; for (int i = 1; i <= n; i++) { cin >> x; a[x]++; } int poz = 100; long long cost =1; while (k > 0) { int j = 0; while (j < 100 && k > 0) { if (poz-j-cost!=100 && a[poz-j-cost]!=0 ){ if (a[poz-j-cost]*cost < k) { k-=a[poz-j-cost]*cost; a[poz-j]+=a[poz-j-cost]; a[poz-j-cost]=0; } else { k = k/cost; a[poz-j-cost] -= k; a[poz-j] +=k; k = 0; } } j+=10; } if (a[100]==n){k=0;} if (cost<10) { cost++; } } cost = 0; for (int i=1;i<=100;i++) { cost += a[i]*(i/10); } cout<<cost; return 0; } <file_sep>// https://codeforces.com/contest/474/problem/F // https://codeforces.com/contest/474/submission/25364936 #include <iostream> using namespace std; #define NMAX 100005 int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a%b); } typedef struct arbore { int cmmdc; int nmb; arbore() { cmmdc = nmb = 0; } }arbore; int n; arbore arb[4 * NMAX]; void build(int node, int start, int end, int pos, int val) { if (start == end) { arb[node].cmmdc = val; arb[node].nmb = 1; return; } int mid = (start + end) / 2; if (pos <= mid) build(node * 2, start, mid, pos, val); else build(node * 2 + 1, mid + 1, end, pos, val); arb[node].cmmdc = gcd(arb[node * 2].cmmdc, arb[node * 2 + 1].cmmdc); arb[node].nmb = 0; if (arb[node].cmmdc == arb[node * 2].cmmdc) arb[node].nmb += arb[node * 2].nmb; if (arb[node].cmmdc == arb[node * 2 + 1].cmmdc) arb[node].nmb += arb[node * 2 + 1].nmb; } arbore querry(int node, int start, int end, int left, int right) { if (start > end || start > right || left > end) return arbore{}; if (left <= start && end <= right) return arb[node]; int mid = (start + end) / 2; arbore leftAns = querry(node * 2, start, mid, left, right); arbore rightAns = querry(node * 2 + 1, mid + 1, end, left, right); arbore ans{}; ans.cmmdc = gcd(leftAns.cmmdc, rightAns.cmmdc); if (ans.cmmdc == leftAns.cmmdc) ans.nmb += leftAns.nmb; if (ans.cmmdc == rightAns.cmmdc) ans.nmb += rightAns.nmb; return ans; } int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); int m, x, i, a, b; for(i = 1, cin>>n; i<=n; ++i) { cin >> x; build(1, 1, n, i, x); } cin >> m; for(;m--;) { cin >> a >> b; cout << (b - a + 1) - querry(1, 1, n, a, b).nmb << "\n"; } return 0; }<file_sep># https://codeforces.com/contest/405/problem/A # https://codeforces.com/contest/405/submission/14009514 n=int(input()) l=list(map(int,input().split())) l.sort() for el in l: print(el,sep=' ',end=' ') <file_sep>// https://codeforces.com/contest/777/problem/C // https://codeforces.com/contest/777/submission/25124989 #include <stdio.h> #include <vector> #include <algorithm> #include <unordered_map> using namespace std; int main() { unordered_map<int, vector<int>> mat; unordered_map<int, vector<int>> crescator; int n, m, x; scanf("%d %d", &n, &m); vector<int> rows(m + n + 1, 0); for (auto i = 1; i <= m; ++i) mat[i].push_back(0), crescator[i].push_back(0); for(auto i = 1; i <= n; ++i) { for(auto j = 1; j <= m; ++j) { scanf("%d", &x); crescator[j].push_back(mat[j].back() <= x ? crescator[j].back() + 1 : 1); mat[j].push_back(x); rows[i] = max(rows[i], crescator[j].back()); } } int q, l, r; bool ok; for(scanf("%d",&q); q-- ;) { scanf("%d %d", &l, &r); ok = rows[r] >= r - l + 1; puts(!ok ? "No" : "Yes"); } return 0; }<file_sep>// https://codeforces.com/contest/404/problem/A // https://codeforces.com/contest/404/submission/17155021 #include <iostream> using namespace std; int main() { int diag[27], nDiag[27], n; memset(diag, 0, 27 * sizeof(int)); memset(nDiag, 0, 27 * sizeof(int)); char mat[300][300]; cin >> n; for (int i = 0; i < n; i++) { getchar(); for (int j = 0; j < n; j++) { mat[i][j] = getchar(); if (i == j || (i == n - j - 1)) diag[mat[i][j] - 'a'] = 1; else nDiag[mat[i][j] - 'a'] = 1; } } int count = 0 , count2 = 0; bool notDiag = true; for (int i = 0; i < 27; i++) { count += diag[i]; count2 += nDiag[i]; if (diag[i] != 0 && nDiag[i] != 0) notDiag = false; } if (count == 1 && notDiag && count2 == 1) cout << "YES"; else cout << "NO"; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/835/problem/C // https://codeforces.com/contest/835/submission/29152450 // Example program #include <stdio.h> #include <string> using namespace std; int mat[12][102][102]; int main() { int n,q,c,p,x,y,t,x1,y1,x2,y2, sum; scanf("%d %d %d", &n, &q, &c); for (int i = 0; i < n; ++ i) { scanf("%d %d %d", &x, &y, &p); mat[p][x][y]++; } for (int k = 0; k <= c; ++ k) { for (int i = 100; i >= 0; --i) { for(int j = 100; j >= 0; --j) { mat[k][i][j] = mat[k][i][j] + mat[k][i+1][j] + mat[k][i][j+1] - mat[k][i+1][j+1]; } } } while(q--) { scanf("%d %d %d %d %d", &t, &x1, &y1, &x2, &y2); sum = 0; for (int i = 0; i <= c; ++i) { sum += (mat[i][x1][y1] - mat[i][x1][y2+1] - mat[i][x2+1][y1] + mat[i][x2+1][y2+1]) * ((i + t) % (c+1)); } printf("%d\n", sum); } return 0; } // Example program #include <iostream> #include <string> using namespace std; int mat[12][102][102]; int GetSum(int x1, int y1, int x2, int y2, int t, int c) { int sum = 0; for (int i = 0; i <= c; ++i) { sum += (mat[i][x1][y1] - mat[i][x1][y2+1] - mat[i][x2+1][y1] + mat[i][x2+1][y2+1]) * ((i + t) % (c+1)); } return sum; } int main() { int n,q,c,p,x,y,t,x1,y1,x2,y2; cin >>n >> q >> c; for (int i = 0; i < n; ++ i) { cin >> x >> y >> p; mat[p][x][y]++; } for (int k = 0; k <= c; ++ k) { for (int i = 100; i >= 0; --i) { for(int j = 100; j >= 0; --j) { mat[k][i][j] = mat[k][i][j] + mat[k][i+1][j] + mat[k][i][j+1] - mat[k][i+1][j+1]; } } } while(q--) { cin >> t >> x1 >> y1 >> x2 >> y2; cout << GetSum(x1,y1,x2,y2,t,c) << "\n"; } return 0; } <file_sep>// https://codeforces.com/contest/741/problem/C // https://codeforces.com/contest/741/submission/23044412 #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <vector> #include <stdio.h> using namespace std; vector<int> colors(200005, 0); vector<int> graph[200005]; vector<pair<int, int>> perechi; inline int oppositeColor(int node) { return (colors[node] == 1) ? 2 : 1; } bool color(int nodulet) { bool ok = true; for (auto vecin : graph[nodulet]) { if (colors[vecin] == colors[nodulet]) ok = false; else if (colors[vecin] == 0) { colors[vecin] = oppositeColor(nodulet); ok = ok & color(vecin); } } return ok; } int main() { int n, x, y; bool ok = true; scanf("%d", &n); for (int i = 0; i < n; ++i) { graph[2 * i + 1].push_back(2 * i + 2); graph[2 * i + 2].push_back(2 * i + 1); } for (int i = 1; i <= n; ++i) { scanf("%d %d", &x, &y); graph[x].push_back(y); graph[y].push_back(x); perechi.push_back(make_pair(x, y)); } for (int i = 1; i <= 2 * n; ++i) { if (colors[i] == 0) { colors[i] = 1; ok = ok & color(i); } } if (!ok) { puts("-1"); return 0; } pair<int, int> pereche; for (int i = 0; i < n; ++i) { pereche = perechi[i]; printf("%d %d\n", colors[pereche.first], colors[pereche.second]); } return 0; }<file_sep>// https://codeforces.com/contest/832/problem/A // https://codeforces.com/contest/832/submission/46924171 #include <iostream> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(NULL); unsigned long long n, k; cin >> n >> k; (n / k) & 1 ? cout << "YES" : cout << "NO"; return 0; }<file_sep>// https://codeforces.com/contest/977/problem/B // https://codeforces.com/contest/977/submission/46637241 #include <iostream> #include <map> #include <string> using namespace std; int main() { map<pair<char, char>, int> mp; std::string str; int n, mx = 0; pair<char, char> res; cin >> n >> str; for (int i = 0; i < n - 1; ++i) { auto c = make_pair(str[i], str[i + 1]); if (mx < ++mp[c]) { res = c; mx = mp[c]; } } cout << res.first << res.second; return 0; }<file_sep>// https://codeforces.com/contest/630/problem/D // https://codeforces.com/contest/630/submission/17323566 #include <iostream> using namespace std; int main() { unsigned long long n; cin >> n; cout << 1 + 6 * n*(n + 1) / 2; return EXIT_SUCCESS; }<file_sep># https://codeforces.com/contest/567/problem/A # https://codeforces.com/contest/567/submission/14261083 def diferenta(x,y): if x>=0 and y>=0: return y-x elif x<=0 and y<=0: return abs(x)-abs(y) else: return abs(x)+y n = int(input()) l = list(map(int,input().split())) print(diferenta(l[0],l[1]), diferenta(l[0],l[len(l)-1])) for i in range (1,len(l)-1): print(min(diferenta(l[i-1],l[i]),diferenta(l[i],l[i+1])),max(diferenta(l[i],l[len(l)-1]),diferenta(l[0],l[i]))) print(diferenta(l[len(l)-2],l[len(l)-1]), diferenta(l[0],l[len(l)-1])) <file_sep># https://codeforces.com/contest/69/problem/A # https://codeforces.com/contest/69/submission/13613715 def check(l): for i in range(len(l)): if l[i]!=0: return ('NO') return('YES') n = int(input()) l = [0, 0, 0] for _ in range(n): m=list(map(int, input().split())) for i in range(3): l[i]+=m[i] m[:]=[] print(check(l)) <file_sep>// https://codeforces.com/contest/550/problem/A // https://codeforces.com/contest/550/submission/17522891 #include <iostream> #include <string> using namespace std; int main() { int mab, Mab, mba, Mba; mab = mba = Mab = Mba = -1; string s; cin >> s; for (int i = 0; i < s.size() - 1; i++) { if (s[i] == 'A' && s[i + 1] == 'B') { if (mab == -1) mab = i; Mab = i; } else if (s[i] == 'B' && s[i + 1] == 'A') { if (mba == -1) mba = i; Mba = i; } } if (abs(Mab - mba) < 2 && abs(Mba - mab) < 2 || mba == -1 || mab == -1) puts("NO"); else puts("YES"); return EXIT_SUCCESS; }<file_sep>// https://www.spoj.com/problems/COINS/ #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <map> #include <unordered_map> #include <set> #include <vector> #include <cstdio> #include <string> using namespace std; #define ll long long #define ull unsigned long long /*------------------------------------------------------------------*/ unordered_map<int, ull> mp; ull solve(int n) { if (mp.find(n) != mp.end()) return mp[n]; return mp[n] = solve(n / 2) + solve(n / 3) + solve(n / 4); } int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); mp[0] = 0; mp[1] = 1; for (int i = 2; i <= 100000; ++i) mp[i] = max(static_cast<ull>(i), mp[i / 2] + mp[i / 3] + mp[i / 4]); int n; while(cin>>n) { cout << solve(n) << "\n"; } return 0; }<file_sep>// https://codeforces.com/contest/672/problem/B // https://codeforces.com/contest/672/submission/17927993 #include <iostream> #include <string> using namespace std; int main() { int n, v[27]; string s; cin >> n; if (n >= 27) puts("-1"); else { cin >> s; int i, nr; memset(v, 0, 27 * sizeof(int)); for (i = 0, nr = 0; i < (int)s.size(); i++) { v[s[i] - 'a']++; if (v[s[i] - 'a'] > 1) nr++; } cout << nr; } return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/984/problem/A // https://codeforces.com/contest/984/submission/38437486 #include <algorithm> #include <vector> #include <iostream> using namespace std; int main() { int n, x; vector<int> v; cin>>n; for(int i = 0; i < n; ++i) { cin >> x; v.push_back(x); } sort(v.begin(),v.end()); cout << v[(n-1)/2]; return 0; }<file_sep>// https://codeforces.com/contest/378/problem/A // https://codeforces.com/contest/378/submission/16639290 #include <stdlib.h> #include <stdio.h> int main() { int a, b, eq = 0, aWin = 0, bWin = 0; scanf_s("%d %d", &a, &b); for (int i = 1; i <= 6; i++) { if (abs(a - i) < abs(b - i)) aWin++; else if (abs(a - i) == abs(b - i)) eq++; else bWin++; } printf("%d %d %d", aWin, eq, bWin); return EXIT_SUCCESS; }<file_sep># https://codeforces.com/contest/37/problem/A # https://codeforces.com/contest/37/submission/14575678 n = int(input()) l = list(map(int,input().split())) dicts = {} ma = 0 for i in l: if i in dicts.keys(): dicts[i] += 1 else: dicts[i] = 1 if dicts[i]>ma: ma = dicts[i] print(ma,len(list(dicts.keys()))) <file_sep>// https://www.spoj.com/problems/ADDREV/ #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <map> #include <unordered_map> #include <set> #include <vector> #include <cstdio> #include <string> using namespace std; #define ll long long #define ull unsigned long long /*------------------------------------------------------------------*/ int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); string a, b; int n1, n2, n; cin >> n; while (n-- ) { cin >> a >> b; reverse(a.begin(), a.end()); reverse(b.begin(), b.end()); n1 = stoi(a); n2 = stoi(b); a = to_string(n1 + n2); reverse(a.begin(), a.end()); a.erase(0, a.find_first_not_of('0')); cout << a << "\n"; } return 0; }<file_sep>// https://codeforces.com/contest/189/problem/A // https://codeforces.com/contest/189/submission/17418226 #include <iostream> using namespace std; #define max(a,b) ((a)>(b) ? (a): (b)) int main() { int a, n, v[4001]; memset(v, 0, 4001 * sizeof(int)); cin >> n; while (cin >> a) for (int i = a; i <= n; i++) if (v[i - a] != 0 || (i%a == 0)) v[i] = max(v[i - a] + 1, v[i]); cout << v[n]; return EXIT_SUCCESS; }<file_sep>// https://www.spoj.com/problems/MIXTURES/ #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <map> #include <unordered_map> #include <set> #include <vector> #include <cstdio> #include <string> using namespace std; #define ll long long #define ull unsigned long long /*------------------------------------------------------------------*/ ull mat[105][105], col[105], smoke[105][105]; int n; int main() { //ios_base::sync_with_stdio(false) , cin.tie(nullptr) , cout.tie(nullptr); while (cin>>n) { for (int i = 1; i <= n; ++i) cin >> col[i], mat[i][i] = col[i]; for (int i = 1; i <= n - 1; ++i) smoke[i][i + 1] = col[i] * col[i + 1], mat[i][i + 1] = (col[i] + col[i + 1]) % 100; for (int d = 2; d <= n - 1; ++d) { for (int i = 1; i <= n - d; ++i) { smoke[i][i + d] = numeric_limits<ull>::max(); for (int k = i, pr = i +d; k <= pr; ++k) { if (smoke[i][i + d] > mat[i][k] * mat[k + 1][i + d] + smoke[i][k] + smoke[k + 1][i + d]) { smoke[i][i + d] = mat[i][k] * mat[k + 1][i + d] + smoke[i][k] + smoke[k + 1][i + d]; mat[i][i + d] = (mat[i][k] + mat[k + 1][i + d]) % 100; } } } } if (n == 1) smoke[1][1] = 0; cout << smoke[1][n] << "\n"; } return 0; } <file_sep># https://codeforces.com/contest/467/problem/A # https://codeforces.com/contest/467/submission/13477314 def read(): """ Read 2 values p and q, 0<=p<=q<=100. @output: p - the number of people who already live in room q - room's capacity """ p,q=map(int,input().split()) return p,q def room_spec(n): """ Return the number of rooms where George and Alex can move in. @input: n - the total number of rooms @output: the number of rooms where George and Alex can move in. """ nr=0 for i in range(n): p,q=read() if q-p>=2: nr+=1 return nr n=int(input()) # read an integer n (1<=n<=100) - the number of rooms print(room_spec(n)) <file_sep># https://codeforces.com/contest/266/problem/B # https://codeforces.com/contest/266/submission/14007696 import copy n,k=map(int,input().split()) s=input() while (k>0): p=[]; i=0; while i<=n-1: if i<=n-2 and s[i]=='B' and s[i+1] =='G': p.append('G') p.append('B') i+=2 else: p.append(s[i]) i+=1 del(s) s=copy.deepcopy(p) del(p) k-=1 for el in s: print(el,end='',sep='') <file_sep>// https://codeforces.com/gym/101246/problem/F // https://codeforces.com/gym/101246/submission/25245739 #include <iostream> #include<fstream> #include<string> #include <queue> #include <algorithm> #include <set> #include <string.h> #define cin f #define cout g using namespace std; int main() { ifstream f("input.txt"); ofstream g("output.txt"); int e[110], viz[110]={0}; int n, fl, x; cin>>n>>fl; for(int i=0; i<n; i++){ cin>>e[i]; viz[e[i]]=1; } int curpoz=fl; int idx=0; while(idx < n){ if(curpoz < e[idx]){ for(int i=curpoz+1; i<=e[idx]; i++) if(viz[i]==1){ cout<<i<<" "; viz[i]=0; } } else{ for(int i=curpoz-1; i>=e[idx]; i--) if(viz[i]==1){ cout<<i<<" "; viz[i]=0; } } curpoz = e[idx]; while( idx < n && viz[e[idx]]==0) idx++; } f.close(); g.close(); return 0; }<file_sep>// https://codeforces.com/contest/384/problem/A // https://codeforces.com/contest/384/submission/16465578 #include <stdio.h> #include <stdlib.h> void printC(int); void printP(int); int main(){ int n,i,j,count; scanf("%d",&n); count = ((n/2)+(n%2))*((n/2)+(n%2))+(n/2)*(n/2); printf("%d\n",count); for (i = 0; i < n; i++){ if (i & 1) printC(n); else printP(n); } return EXIT_SUCCESS; } void printC(int lg){ int i; for (i = 0; i < lg; i++){ if (i & 1) putchar('C'); else putchar('.'); } putchar('\n'); } void printP(int lg){ int i; for (i = 0; i < lg; i++){ if (i & 1) putchar('.'); else putchar('C'); } putchar('\n'); } <file_sep>// https://codeforces.com/contest/401/problem/A // https://codeforces.com/contest/401/submission/14899014 #include <iostream> using namespace std; int main() { int s = 0, n, x,p; cin>>n>>x; while (n>0) { cin>>p; s += p; n -- ; } if (s<0) s *= -1; if (s % x != 0) cout<< 1 + s/x; else cout << s/x; return 0; } <file_sep>// https://codeforces.com/contest/766/problem/B // https://codeforces.com/contest/766/submission/46828176 #include <iostream> #include <stdio.h> #include <vector> #include <algorithm> using namespace std; int main() { std::ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n, x; scanf("%d", &n); vector<int> v(n, 0); for (int i = 0; i < n; ++i) { scanf("%d", &x); v[i] = x; } sort(v.begin(), v.end()); bool ok = false; for (size_t i = 2; !ok && i < v.size(); ++i) { ok = (v[i - 2] + v[i - 1]) > v[i]; } (ok) ? cout << "YES" : cout << "NO"; return 0; } #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { std::ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n, x; cin >> n; vector<int> v(n, 0); for (int i = 0; i < n; ++i) { cin >> x; v[i] = x; } sort(v.begin(), v.end()); bool ok = false; for (size_t i = 2; !ok && i < v.size(); ++i) { ok = (v[i - 2] + v[i - 1]) > v[i]; } (ok) ? cout << "YES" : cout << "NO"; return 0; } #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { int n, x; cin >> n; vector<int> v(n, 0); for (int i = 0; i < n; ++i) { cin >> x; v[i] = x; } sort(v.begin(), v.end()); bool ok = false; for (size_t i = 2; !ok && i < v.size(); ++i) { ok = (v[i - 2] + v[i - 1]) > v[i]; } (ok) ? cout << "YES" : cout << "NO"; return 0; }<file_sep>// https://codeforces.com/contest/723/problem/A // https://codeforces.com/contest/723/submission/21321216 #include <stdio.h> #include <stdlib.h> #include <algorithm> #include <math.h> using namespace std; int main() { int v[3]; for (size_t i = 0; i < 3; ++i) scanf("%d", &v[i]); sort(v, v + 3); printf("%d", v[2] - v[0]); return 0; }<file_sep>// https://codeforces.com/contest/732/problem/C // https://codeforces.com/contest/732/submission/21665568 #include <iostream> #include <algorithm> using namespace std; int main() { unsigned long long a[3], s = 0; cin >> a[0] >> a[1] >> a[2]; sort(a, a + 3); if (a[2] - a[0] > 1) { if (a[2] - a[1] > 1) { s += (a[2] - a[1] - 1); } s += (a[2] - a[0] - 1); } cout << s; return 0; }<file_sep>// https://codeforces.com/contest/352/problem/A // https://codeforces.com/contest/352/submission/17171732 #include <iostream> using namespace std; int main() { int n, n0 = 0, n5 = 0; char x; char five[] = "555555555"; cin >> n; getchar(); for (int i = 0; i < n; i++) { x = getchar(); if (x == '0') n0++; else n5++; getchar(); } if (n0 == 0) cout << -1; else { if (n5 / 9 == 0) n0 = 1; for (int i = 1; i <= n5 / 9; i++) cout << five; for (int i = 1; i <= n0; i++) putchar('0'); } return EXIT_SUCCESS; }<file_sep># https://codeforces.com/contest/474/problem/A # https://codeforces.com/contest/474/submission/14042125 keyboard='qwertyuiopasdfghjkl;zxcvbnm,./' miss=input() if miss=='R': opt=-1 else: opt=1 text=input() for i in range(len(text)): print(keyboard[keyboard.index(text[i])+opt],sep='',end='') <file_sep>// https://codeforces.com/contest/677/problem/A // https://codeforces.com/contest/677/submission/18234721 #include <iostream> using namespace std; int main() { int n, t, x, s, i; for (cin >> n >> t >> x, i = 1, s = 0; i < n; i++, cin >> x) (x > t) ? s += 2 : s++; (x > t) ? s += 2 : s++; cout << s; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/675/problem/A // https://codeforces.com/contest/675/submission/18242837 #include <iostream> using namespace std; int main() { int a, b, c; cin >> a >> b >> c; if (c == 0 && a != b) puts("NO"); else if (c == 0 && a == b) puts("YES"); else if (c < 0 && a < b || c > 0 && a > b) puts("NO"); else if ((b - a) % c != 0) puts("NO"); else puts("YES"); return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/476/problem/B // https://codeforces.com/contest/476/submission/46794053 #include <iostream> #include <string> #include <iomanip> using namespace std; int output = 0, actual = 0, unknown = 0, need = 0; void Parse(const string& input, const string& expected) { for (auto& c : input) { (c == '+') ? output = output + 1 : output = output - 1; } for (auto& c : expected) { if (c == '+') actual = actual + 1; if (c == '-') actual = actual - 1; if (c == '?') unknown = unknown + 1; } } unsigned long long Comb(unsigned long long n, unsigned long k) { unsigned long long fact[12]; fact[0] = 1; for (int i = 1; i < 12; ++i) fact[i] = i * fact[i - 1]; return fact[n] / (fact[k] * fact[n - k]); } double GetSol() { if (need > unknown) return 0; if ((unknown - need) % 2 != 0) return 0; need = need + (unknown - need) / 2; auto comb = Comb(unknown, need); return static_cast<double>(comb) / static_cast<double>(1 << unknown); } int main() { string s1, s2; cin >> s1 >> s2; Parse(s1, s2); need = abs(output - actual); cout << setprecision(12) << fixed << GetSol(); return 0; }<file_sep>// https://codeforces.com/contest/9/problem/A // https://codeforces.com/contest/9/submission/46892122 #include <iostream> #include <algorithm> using namespace std; void Reduct(int& a, int& b) { for (int i = 2; i <= 6; ++i) { while (a % i == 0 && b % i == 0) { a = a / i; b = b / i; } } } int main() { int x, y, p, q; cin >> x >> y; p = (7 - max(x,y)); q = 6; Reduct(p, q); cout << p << "/" << q; return 0; }<file_sep>// https://codeforces.com/contest/462/problem/A // https://codeforces.com/contest/462/submission/17418438 #include <iostream> using namespace std; int main() { char matrix[102][102]; memset(matrix, 'x', 102 * 102 * sizeof(char)); int n, count; bool ok = true; cin >> n; getchar(); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) matrix[i][j] = getchar(); getchar(); } for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { count = 0; if (matrix[i - 1][j] == 'o') count++; if (matrix[i + 1][j] == 'o') count++; if (matrix[i][j - 1] == 'o') count++; if (matrix[i][j + 1] == 'o') count++; if (count & 1) ok = false; } } if (ok) cout << "YES"; else cout << "NO"; return EXIT_SUCCESS; } <file_sep>// https://codeforces.com/contest/689/problem/A // https://codeforces.com/contest/689/submission/22211157 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> #include <map> #include <vector> #include <string> #include <iostream> using namespace std; int main() { int a[6][5] = { {-1,-1,-1,-1,-1},{-1,1,2,3,-1},{-1,4,5,6,-1},{-1,7,8,9,-1 },{-1,-1,0,-1,-1},{-1,-1,-1,-1,-1} }; pair<int, int> poz[10]; poz[0] = make_pair(4, 2); poz[7] = make_pair(3, 1); poz[8] = make_pair(3, 2); poz[9] = make_pair(3, 3); poz[4] = make_pair(2, 1); poz[5] = make_pair(2, 2); poz[6] = make_pair(2, 3); poz[1] = make_pair(1, 1); poz[2] = make_pair(1, 2); poz[3] = make_pair(1, 3); vector<int> v; int n; cin >> n; char el; int mx[] = { -1,0,1 }; int my[] = { -1,0,1 }; for (int i = 0; i < n; i++) { cin >> el; v.push_back((int)(el - '0')); } bool sePoate = false; for (int i = 0; i <= 2; i++) { for (int j = 0; j <= 2; j++) if(i!=1 || j!=1) { sePoate = true; for (auto el : v) { auto p = poz[el]; if (a[p.first + mx[i]][p.second + my[j]] == -1) sePoate = false; } if (sePoate) { cout << "NO"; return 0; } } } cout << "YES"; return 0; }; <file_sep>// https://codeforces.com/contest/545/problem/D // https://codeforces.com/contest/545/submission/17154734 #include <iostream> #include <algorithm> using namespace std; int main() { int v[100001], n, count = 0; unsigned long long s = 0; cin >> n; for (int i = 0; i < n; i++) cin >> v[i]; sort(v, v + n); for (int i = 0; i < n; i++) { if (v[i] >= s) { s += v[i]; count++;} } cout << count; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/115/problem/A // https://codeforces.com/contest/115/submission/47157726 #include <vector> #include <map> #include <iostream> #include <algorithm> using namespace std; void DFS(int node, map<int, vector<int>>& graph, vector<bool>& visited, map<int,int>& sol, int& best) { visited[node] = true; for (auto& neighbour : graph[node]) { if (!visited[neighbour]) { DFS(neighbour, graph, visited, sol, best); } sol[node] = max(sol[node], sol[neighbour] + 1); } best = max(best, sol[node]); } int main() { ios::sync_with_stdio(false); cin.tie(NULL); int n, best = 1, x; cin >> n; map<int, vector<int>> graph; map<int, int> sol; for (int i = 1; i <= n; ++i) { cin >> x; sol[x] = 1; sol[i] = 1; if (x == -1) continue; graph[x].push_back(i); } vector<bool> visited(n + 1, false); for (auto& keyValuePair : graph) { if (!visited[keyValuePair.first]) { DFS(keyValuePair.first, graph, visited, sol, best); } } cout << best; return 0; }<file_sep>// https://codeforces.com/gym/101021/problem/A // https://codeforces.com/gym/101021/submission/18652939 #include <iostream> #include <string> using namespace std; #define MAX 1000000 #define MIN 1 void cautBin() { int mid, lo = MIN, hi = MAX; string ans; while (hi > lo ) { mid = (lo + hi) / 2; cout << mid << "\n"; fflush(stdout); cin >> ans; if (ans == "<") hi = --mid; else (lo = mid); if (lo >= hi - 1) { cout << mid + 1 <<"\n"; fflush(stdout); cin >> ans; if (ans == "<") { cout << mid <<"\n"; fflush(stdout); cin >> ans; if (ans == "<") cout << "! " << mid - 1 << "\n"; else cout << "! " << mid << "\n"; }else cout << "! " << mid + 1 << "\n"; lo = hi + 1; } } } int main() { cautBin(); return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/785/problem/A // https://codeforces.com/contest/785/submission/25504142 #include <iostream> #include <string> using namespace std; int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); int n; long long cnt = 0; string s; cin >> n; for(int i = 0; i < n; ++i) { cin >> s; if (s[0] == 'T') cnt += 4; else if (s[0] == 'C') cnt += 6; else if (s[0] == 'O') cnt += 8; else if (s[0] == 'D') cnt += 12; else if (s[0] == 'I') cnt += 20; } cout << cnt; return 0; }<file_sep># https://codeforces.com/contest/535/problem/A # https://codeforces.com/contest/535/submission/14926852 numbers = {0:'zero',1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',\ 8:'eight',9:'nine',10:'ten',11:'eleven',12:'twelve',13:'thirteen',14:'fourteen',\ 15:'fifteen',16:'sixteen',17:'seventeen',18:'eighteen',19:'nineteen',20:'twenty',\ 30:'thirty',40:'forty',50:'fifty',60:'sixty',70:'seventy',80:'eighty',90:'ninety'} a = int(input()) if a <= 20 or a % 10 == 0: print(numbers[a]) else: print(numbers[a//10 * 10],'-',numbers[a%10],sep='') <file_sep>// https://codeforces.com/contest/616/problem/B // https://codeforces.com/contest/616/submission/15329996 #include <iostream> using namespace std; int main() { short int n,m; long long int max = 0; cin >> n >> m; for (int i = 1; i <= n; i++) { long long min = 0x3B9ACA00, x; for (int j = 1; j <= m; j++) { cin >> x; if (x < min) min = x; } if (min > max) max = min; } cout << max; return 0; } <file_sep>// https://codeforces.com/contest/1167/problem/A // https://codeforces.com/contest/1167/submission/68001596 #include <iostream> #include <algorithm> #include <string> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cerr.tie(nullptr); int queries = 0, length = 0; string s; cin >> queries; while (queries--) { cin >> length >> s; size_t first8 = s.size(); for (size_t i = 0; i < s.size(); ++i) { if (s[i] == '8') { first8 = i; break; } } (s.size() - first8 >= 11) ? cout << "YES\n" : cout << "NO\n"; } return 0; }<file_sep># https://codeforces.com/contest/443/problem/A # https://codeforces.com/contest/443/submission/13614190 s=input() l=[] for i in range(26): l.append(0) for i in range(len(s)): if s[i]>='a' and s[i]<='z': l[ord(s[i])-97]=1 nr=0 for i in range(26): if l[i]==1: nr+=1 print(nr) <file_sep>// https://codeforces.com/contest/984/problem/B // https://codeforces.com/contest/984/submission/38439439 #include <algorithm> #include <vector> #include <iostream> #include <stdio.h> using namespace std; bool IsDigit(char x) { return (x >= '0' && x <= '9'); } int GetDigit(char x) { return x - '0'; } int main() { int n, m; vector<int> dX = { -1, -1, 0, 1, 1, 1, 0, -1 }; vector<int> dY = { 0, 1, 1, 1, 0, -1, -1, -1 }; bool ok = true; string line; char matrix[102][102] = {0}; scanf("%d %d", &n,&m); for(int i = 1; i<=n; ++i) { getchar(); scanf("%s",&(matrix[i][1])); for(int j = 1; j<=m; ++j) { if (matrix[i][j] == '.') { matrix[i][j] = '0'; } } } for(int i = 1; i <= n; ++i) { for(int j = 1; j <= m; ++j) { if (!IsDigit(matrix[i][j])) { continue; } int d = GetDigit(matrix[i][j]); int matches = 0; for(int k = 0; k < 8; ++k) { int ox = i + dX[k]; int oy = j + dY[k]; if (matrix[ox][oy] == '*') { matches++; } } if(matches != d) { ok = false; } } } cout << (ok ? "YES" : "NO") << "\n"; return 0; }<file_sep># https://codeforces.com/contest/431/problem/A # https://codeforces.com/contest/431/submission/14639640 l = [0] + list(map(int,input().split())) s = input() sm = 0 for i in range(len(s)): sm += l[int(s[i])] print(sm) <file_sep># https://codeforces.com/contest/514/problem/A # https://codeforces.com/contest/514/submission/14419432 s = input() j = 0 if s[0]=='9': print(9,sep='',end='') j = 1 for i in range(j,len(s)): print(min(9-int(s[i]),int(s[i])),sep='',end='') <file_sep>// https://codeforces.com/contest/463/problem/A // https://codeforces.com/contest/463/submission/17434138 #include <iostream> using namespace std; int main() { int $$,c,n, s, max = -1; cin >> n >> s; for (; n > 0; n--) { cin >> $$ >> c; if (s - $$ >= 0) { if (s - $$ > 0 && c != 0 && 100 - c > max) max = 100 - c; else if (c == 0 && max == -1) max = 0; } } cout << max; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/501/problem/B // https://codeforces.com/contest/501/submission/48032053 #include <string> #include <algorithm> #include <iostream> #include <map> #include <vector> using namespace std; void Add(map<string, int>& hash, map<int, string>& revHash, int& id, string& handle) { if (hash[handle] == 0) { hash[handle] = ++id; revHash[id] = handle; } } int find(map<int, int>& parent, int x) { if (x == parent[x]) return x; return parent[x] = find(parent, parent[x]); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int q, id = 0; map<string, int> hash; map<int, string> revHash; map<int, int> parent; map<int, bool> visited; vector<pair<string, string>> changes; string oldH, newH; cin >> q; for (int i = 1; i <= q; ++i) { cin >> oldH >> newH; Add(hash, revHash, id, oldH); Add(hash, revHash, id, newH); auto x = hash[oldH]; if (parent[x] == 0) parent[x] = x; auto y = hash[newH]; if (parent[y] == 0) parent[y] = y; parent[find(parent, x)] = y; } for (int i = 1; i <= id; ++i) { auto px = find(parent, i); if (visited[px]) continue; visited[px] = true; changes.push_back(make_pair(revHash[i], revHash[px])); } cout << changes.size() << "\n"; for (const auto& value : changes) { cout << value.first << " " << value.second << "\n"; } return 0; }<file_sep>// https://codeforces.com/contest/478/problem/A // https://codeforces.com/contest/478/submission/13753654 #include <stdio.h> #include <stdlib.h> int main() { int x,i,sum = 0; for (i=1;i<=5;i+=1) { scanf("%d",&x); sum +=x; } if ((sum%5!=0) || (sum==0)){printf("-1");} else{printf("%d",sum/5);} return 0; } <file_sep>// https://codeforces.com/contest/592/problem/B // https://codeforces.com/contest/592/submission/13994484 #include <iostream> using namespace std; unsigned long long n; int main() { cin>>n; cout<<(n-2)*(n-2); return 0; } <file_sep>// https://www.spoj.com/problems/BRCKTS/ #include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; struct Node { Node(char Bracket) { if (Bracket == ')') { StartClosed = 1; } else { EndOpened = 1; } } Node() = default; ~Node() = default; int StartClosed = 0; int EndOpened = 0; }; class SegmentTree { public: SegmentTree(const string& Array) : Array{ Array }, Tree(Array.size() * 4 + 4, Node()) { Build(1, 0, Array.size() - 1); }; bool Query(size_t Low, size_t High) { auto node = Query(1, 0, Array.size() - 1, Low, High); return (node.StartClosed == 0 && node.EndOpened == 0); } void Update(size_t Low, size_t High) { Update(1, 0, Array.size() - 1, Low, High); } ~SegmentTree() = default; private: void Build(size_t Node, size_t Start, size_t End) { if (Start == End) { Tree[Node] = ::Node(Array[Start]); return; } size_t mid = (Start + End) / 2; Build(Node * 2, Start, mid); Build(Node * 2 + 1, mid + 1, End); Tree[Node] = Combine(Tree[Node * 2], Tree[Node * 2 + 1]); } void Update(size_t Node, size_t Start, size_t End, size_t Low, size_t High) { if (Low > End || High < Start) { return; } if (Start == End) { Array[Start] = (Array[Start] == ')') ? '(' : ')'; Tree[Node] = ::Node(Array[Start]); return; } size_t mid = (Start + End) / 2; Update(Node * 2, Start, mid, Low, High); Update(Node * 2 + 1, mid + 1, End, Low, High); Tree[Node] = Combine(Tree[Node * 2], Tree[Node * 2 + 1]); } Node Query(size_t Node, size_t Start, size_t End, size_t Low, size_t High) { if (Low > End || High < Start) { return ::Node(); } if (Low >= Start && End <= High) { return Tree[Node]; } size_t mid = (Start + End) / 2; auto left = Query(Node * 2, Start, mid, Low, High); auto right = Query(Node * 2 + 1, mid + 1, End, Low, High); return Combine(left, right); } Node Combine(const Node& Left, const Node& Right) { Node node; node.StartClosed = Left.StartClosed; node.EndOpened = Right.EndOpened; node.EndOpened += max(0, Left.EndOpened - Right.StartClosed); node.StartClosed += max(0, Right.StartClosed - Left.EndOpened); return node; } string Array; vector<Node> Tree; }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, m, k; string s; for (int i = 1; i <= 10; ++i) { cin >> n >> s >> m; SegmentTree tree(s); cout << "Test " << i << ":\n"; for (int j = 1; j <= m; ++j) { cin >> k; if (k > 0) tree.Update(k - 1, k - 1); else tree.Query(0, s.size() - 1) ? cout << "YES\n" : cout << "NO\n"; } } return 0; }<file_sep>// https://codeforces.com/contest/681/problem/A // https://codeforces.com/contest/681/submission/18456914 #include <iostream> #include <string> using namespace std; int main() { int n, b, a; string s; bool ok = false; cin >> n; for (; n > 0; n--) { cin >> s >> b >> a; if (b >= 2400 && a > b) ok = true; } (ok) ? puts("YES") : puts("NO"); return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/721/problem/A // https://codeforces.com/contest/721/submission/21808058 #include <iostream> #include <vector> #include <string> using namespace std; int main() { ios::sync_with_stdio(false); vector<int> sol; string s; int n; bool ok = true; int ct = 0; cin >> n >> s; for (size_t i = 0; i < s.size(); ++i) { if (s[i] == 'B' && ok) ct++; else if (s[i] == 'B' && !ok) ok = true, ct = 1; else { if (ct > 0) sol.push_back(ct); ok = false; ct = 0; } } if (ok > 0) sol.push_back(ct); cout << sol.size() << "\n"; for (size_t i = 0; i < sol.size(); ++i) { cout << sol[i] << " "; } return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/19/problem/D // https://codeforces.com/contest/19/submission/68014305 #include <iostream> #include <algorithm> #include <functional> #include <map> #include <set> #include <string> #include <vector> using namespace std; struct Point { Point() = default; Point(int x, int y) : x{ x }, y{ y } {}; bool operator<(const Point& Other) const { return (this->x != Other.x) ? this->x < Other.x : this->y < Other.y; } int x = std::numeric_limits<int>::min(); int y = std::numeric_limits<int>::min(); }; class SegmentedTree { public: SegmentedTree(size_t NoPoints) : Tree{ NoPoints * 4 + 4, Point() }, noPoints{NoPoints} {}; void Update(size_t Position, const Point& Point) { Update(1, 0, noPoints - 1, Position, Position, Point); } Point Query(const Point& Requested) { return Query(1, 0, noPoints - 1, Requested); } private: Point Query(size_t Node, size_t Start, size_t End, const Point& Requested) { if (Tree[Node].x <= Requested.x || Tree[Node].y <= Requested.y) { return Point(); } if (Start == End) { return Tree[Node]; } size_t mid = (Start + End) / 2; auto solution = Query(Node * 2, Start, mid, Requested); if (solution.x == std::numeric_limits<int>::min() || solution.y == std::numeric_limits<int>::min()) { solution = Query(Node * 2 + 1, mid + 1, End, Requested); } return solution; } void Update(size_t Node, size_t Start, size_t End, size_t Low, size_t High, const Point& Point) { if (Start > High || End < Low) { return; } if (Start == End) { Tree[Node] = ::Point(Point); return; } size_t mid = (Start + End) / 2; Update(Node * 2, Start, mid, Low, High, Point); Update(Node * 2 + 1, mid + 1, End, Low, High, Point); Tree[Node] = Combine(Tree[Node * 2], Tree[Node * 2 + 1]); } Point Combine(const Point& Left, const Point& Right) { Point node; node.x = max(Left.x, Right.x); node.y = max(Left.y, Right.y); return node; } private: vector<Point> Tree; size_t noPoints = 0; }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cerr.tie(nullptr); vector<Point> points; vector<pair<int, Point>> queries; int n = 0; cin >> n; while (n--) { int x = 0, y = 0; string s; cin >> s >> x >> y; Point point{ x,y }; points.push_back(point); if (s == "add") queries.push_back({ 'a', point }); else if (s == "remove") queries.push_back({ 'r',point }); else queries.push_back({ 'f',point }); } sort(points.begin(), points.end()); SegmentedTree tree(points.size()); for (const auto& query : queries) { auto command = query.first; auto point = query.second; auto pointMapping = std::lower_bound(points.begin(), points.end(), point); if (command == 'a') tree.Update(pointMapping - points.begin(), point); else if (command == 'r') tree.Update(pointMapping - points.begin(), Point{}); else if (command == 'f') { auto p = tree.Query(point); if (p.x == std::numeric_limits<int>::min() || p.y == std::numeric_limits<int>::min()) { cout << "-1\n"; } else { cout << p.x << " " << p.y << "\n"; } } } return 0; }<file_sep>// https://codeforces.com/contest/789/problem/A // https://codeforces.com/contest/789/submission/25902327 #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <map> #include <unordered_map> #include <set> #include <vector> #include <cstdio> #include <string> using namespace std; #define ll long long #define ull unsigned long long /*------------------------------------------------------------------*/ int v[100005]; int n, k; int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); cin >> n >> k; int cnt = 0; int buzunare; for (int i = 1; i <= n; ++i) cin >> v[i]; for(int i = 1; i<=n; ++i) { if (v[i] == 0) continue; if (v[i] >= k) { buzunare = v[i] / k; if (v[i] % k != 0) buzunare++; } else { buzunare = 1; } cnt += buzunare / 2; if (buzunare % 2 != 0) { cnt++; v[i + 1] = max(0, v[i + 1] - k); } } cout << cnt; return 0; }<file_sep># https://codeforces.com/contest/59/problem/A # https://codeforces.com/contest/59/submission/14287298 import string lower = string.ascii_lowercase upper = string.ascii_uppercase s = input() nrl,nru = 0, 0 for i in range (len(s)): if s[i] in lower: nrl+=1 else: nru+=1 if nrl>=nru: print(s.lower()) else: print(s.upper()) <file_sep># https://codeforces.com/contest/500/problem/A # https://codeforces.com/contest/500/submission/14007783 n,m=map(int,input().split()) l=list(map(int,input().split())) p=[0]+l rez=1+p[1] while (rez<m): rez=p[rez]+rez if rez==m: print('YES') else: print('NO') <file_sep>// https://codeforces.com/contest/752/problem/B // https://codeforces.com/contest/752/submission/23310052 #include <iostream> #include <string> #include <map> using namespace std; int main() { map<char, char> m; string s, t; int cnt = 0; cin >> s >> t; bool ok = true; int size = s.size(); for (int i = 0; i < size; ++i) { if (s[i] == t[i]) { if (m.find(s[i]) != m.end()) { if (m[s[i]] != t[i]) ok = false; } else m[s[i]] = t[i], m[t[i]] = s[i]; } else if (m.find(s[i]) == m.end() && m.find(t[i]) == m.end()) { m[s[i]] = t[i]; m[t[i]] = s[i]; } else { if (m[s[i]] != t[i]) ok = false; } if (!ok) break; } for (auto key : m) { if (key.second != '-') cnt++, m[key.second] = '-'; if (key.second == key.first) cnt--; } if (!ok) puts("-1"); else { cout << cnt << "\n"; for (auto key : m) { if (key.second != '-') cout << key.first << " " << key.second << "\n"; } } return 0; }<file_sep># https://codeforces.com/contest/208/problem/A # https://codeforces.com/contest/208/submission/13960065 import string s=input() a=s.replace('WUB',' ') del(s) s=a.lstrip() del(a) a=s.rstrip() print(a) <file_sep>// https://codeforces.com/contest/750/problem/A // https://codeforces.com/contest/750/submission/23458514 #include <iostream> using namespace std; int main() { int n, k, s = 240, i = 1, cnt = 0; cin >> n >> k; s -= k; while (s - i * 5 >= 0 && i <= n) cnt++, s -= i++ * 5; cout << cnt; return 0; }<file_sep># https://codeforces.com/contest/268/problem/B # https://codeforces.com/contest/268/submission/14056730 n=int(input()) print(int((n*n*n + (5*n))/6)) <file_sep>// https://www.spoj.com/problems/GSS1/ #include <iostream> #include <vector> #include <algorithm> using namespace std; struct Node { Node(int Value) { this->Sum = Value; this->MaxPrefixSum = Value; this->MaxSuffixSum = Value; this->MaxCombinedSum = Value; } Node() = default; ~Node() = default; long long Sum = numeric_limits<int>::min(); long long MaxPrefixSum = numeric_limits<int>::min(); long long MaxSuffixSum = numeric_limits<int>::min(); long long MaxCombinedSum = numeric_limits<int>::min(); }; class SegmentedTree { public: SegmentedTree(const vector<int>& Array): Array{Array}, Tree(Array.size() * 4 + 4, Node()) { Build(1, 0, Array.size() - 1); } long long Query(size_t Low, size_t High) { std::vector<size_t> path; Query(1, 0, Array.size() - 1, Low, High, path); Node previous{ numeric_limits<int>::min() }; previous.Sum = 0; for (auto& nodeIdx : path) { const auto& node = Tree[nodeIdx]; previous = Combine(previous, node); } return MaxSum(previous); } private: void Build(size_t Node, size_t Start, size_t End) { if (Start == End) { Tree[Node] = ::Node(Array[Start]); return; } size_t mid = (Start + End) / 2; Build(Node * 2, Start, mid); Build(Node * 2 + 1, mid + 1, End); Tree[Node] = Combine(Tree[Node * 2], Tree[Node * 2 + 1]); } void Query(size_t Node, size_t Start, size_t End, size_t Low, size_t High, std::vector<size_t>& Nodes) { if (Start > High || End < Low) { return; } if (Low <= Start && End <= High) { Nodes.push_back(Node); return; } size_t mid = (Start + End) / 2; Query(Node * 2, Start, mid, Low, High, Nodes); Query(Node * 2 + 1, mid + 1, End, Low, High, Nodes); } Node Combine(const Node& Left, const Node& Right) { Node node; node.Sum = Left.Sum + Right.Sum; node.MaxPrefixSum = max(Left.MaxPrefixSum, Left.Sum + Right.MaxPrefixSum); node.MaxSuffixSum = max(Right.MaxSuffixSum, Left.MaxSuffixSum + Right.Sum); node.MaxCombinedSum = max(Left.MaxCombinedSum, Right.MaxCombinedSum); node.MaxCombinedSum = max(node.MaxCombinedSum, Left.MaxSuffixSum + Right.MaxPrefixSum); return node; } long long MaxSum(const Node& Node) { auto res = Node.Sum; res = max(res, Node.MaxCombinedSum); res = max(res, Node.MaxPrefixSum); res = max(res, Node.MaxSuffixSum); return res; } vector<int> Array; vector<Node> Tree; }; vector<int> ReadVector() { int n; cin >> n; vector<int> v(n, 0); for (int i = 0; i < n; ++i) { cin >> v[i]; } return v; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int q, r, l; auto vector = ReadVector(); SegmentedTree tree(vector); cin >> q; for (int i = 1; i <= q; ++i) { cin >> r >> l; cout << tree.Query(r - 1, l - 1) << '\n'; } return 0; }<file_sep># https://codeforces.com/contest/149/problem/A # https://codeforces.com/contest/149/submission/14449996 k = int(input()) l = sorted(list(map(int,input().split()))) i = 11 nr = 0 while k>0 and i>=0: k-=l[i] nr+=1 i-=1 if k>0: print(-1) else: print(nr) <file_sep>// https://codeforces.com/contest/734/problem/A // https://codeforces.com/contest/734/submission/22307512 #include <iostream> #include <string> using namespace std; int main() { int An,Dn, size; string s; cin >> An >> s; An = Dn = 0; size = s.size(); for (int i = 0; i < size; ++i) { (s[i] == 'A') ? An++ : Dn++; } (An > Dn) ? puts("Anton") : (An == Dn) ? puts("Friendship") : puts("Danik"); return 0; }<file_sep>// https://codeforces.com/contest/731/problem/C // https://codeforces.com/contest/731/submission/21641965 #include <iostream> #include <stdio.h> #include <vector> #include <string.h> #include <map> using namespace std; vector<int> colors(200005,0); vector<int> graph[200005]; bool visited[200005]; map<int, int> cls; int maxCol = 0; int maxFrecv = 0; void dfs(int node) { visited[node] = 1; for (auto nd : graph[node]) { if (visited[nd] == 0) { if (maxCol < ++cls[colors[nd]]) maxCol = cls[colors[nd]]; ++maxFrecv; dfs(nd); } } } int main() { int n, m, k, x, y; scanf("%d %d %d", &n, &m, &k); for (int i = 1; i <= n; ++i) cin >> colors[i]; for (int i = 0; i < m; ++i) { scanf("%d %d", &x, &y); graph[x].push_back(y); graph[y].push_back(x); } int all = 0; for (int i = 1; i <= n; ++i) { if (visited[i] == 0) { cls.clear(); cls[colors[i]] = 1; maxCol = 1; maxFrecv = 1; dfs(i); all += (maxFrecv - maxCol); } } printf("%d", all); return 0; }<file_sep>// https://codeforces.com/contest/745/problem/C // https://codeforces.com/contest/745/submission/23064233 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <map> #include <vector> #include <algorithm> using namespace std; int parent[1004]; int kids[1004]; int muchii[1004]; map<int, bool> rep; vector<int>reps; void swap(int&x, int&y) { int aux = x; x = y; y = aux; } int find(int x) { return (x == parent[x]) ? x : parent[x] = find(parent[x]); } int main() { int n, m, k, reprez, x, y, px, py; scanf("%d %d %d", &n, &m, &k); for (int i = 1; i <= n; i++) { parent[i] = i; kids[i] = 1; } for (int i = 1; i <= k; ++i) { scanf("%d", &reprez); rep[reprez] = 1; } for (int i = 1; i <= m; ++i) { scanf("%d %d", &x, &y); px = find(x); py = find(y); if (rep[px] == 1) swap(px, py); if (px != py) parent[px] = py, kids[py] += kids[px], muchii[py] += muchii[px]; muchii[py]++; } int contor = 0; int freeNodes = 0; int freeMuchii = 0; for (int i = 1; i <= n; ++i) { if (find(i) != i) continue; contor += ((kids[i] * (kids[i] - 1)) / 2 - muchii[i]); if (rep[i] == 1) reps.push_back(kids[i]); else { freeMuchii += freeNodes*kids[i]; freeNodes += kids[i]; } } sort(reps.begin(), reps.end()); int mx = reps[reps.size() - 1]; freeMuchii += mx * freeNodes; contor += freeMuchii; printf("%d", contor); return 0; }<file_sep>// https://codeforces.com/contest/749/problem/B // https://codeforces.com/contest/749/submission/23148975 #include <iostream> using namespace std; int main() { int x1, y1, x2, y2, x3, y3; cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3; cout << 3 << "\n"; cout << x2 - x3 + x1 << " " << y2 - y3 + y1 << "\n"; cout << x1 - x2 + x3 << " " << y1 - y2 + y3 << "\n"; cout << x3 - x1 + x2 << " " << y3 - y1 + y2 << "\n"; return 0; }<file_sep>// https://codeforces.com/contest/822/problem/A // https://codeforces.com/contest/822/submission/30913465 #include <iostream> #include <algorithm> using namespace std; typedef unsigned int ui; ui Fact(const ui& a) { ui res = 1; for (ui i = 2; i <= a; ++i) { res *= i; } return res; } int main() { ui a = 0, b = 0; cin >> a >> b; cout << Fact(min(a, b)); cin >> a; return 0; }<file_sep>// https://codeforces.com/contest/615/problem/A // https://codeforces.com/contest/615/submission/16452036 #include <stdlib.h> #include <stdio.h> typedef enum elem{ONE, ZERO} STATE; int main() { int n, m, i, j, x, y; scanf_s("%d %d", &n, &m); STATE *v, ok = ONE; v = (STATE*)malloc((m+1)*sizeof(STATE)); for (i = 0; i <= m; i++) v[i] = ZERO; for (i = 0; i < n; i++) { scanf_s("%d", &x); for (j = 0; j < x; j++) { scanf_s("%d", &y); v[y] = ONE; } } i = 1; while (i <= m && ok != ZERO) { ok = v[i]; i++; } if (ok == ONE) printf("YES"); else printf("NO"); free(v); return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/gym/101246/problem/D // https://codeforces.com/gym/101246/submission/25263041 #include <iostream> #include<fstream> #include<string> #include <queue> #include <algorithm> #include <set> #include <string.h> #define cin f #define cout g using namespace std; vector<int> vecini[100100]; int viz[100100]; int nivel[100100]; int grd[100100]; void bfs(){ queue<int> q; q.push(1); viz[1]=1; int p; while(!q.empty()){ p=q.front(); q.pop(); for(int vec:vecini[p]){ if(viz[vec]==0){ q.push(vec ); viz[vec]=1; nivel[vec]=nivel[p]+1; } } } } int mex(set<int>& s){ int m=0; while( s.find(m)!=s.end() )m++; return m; } void dfs(int nod){ set<int> s; viz[nod]=1; bool frunza=true; for(int vec:vecini[nod]){ if( nivel[vec]==nivel[nod]+1){ frunza=false; dfs(vec); s.insert(grd[vec]); } } if(frunza) grd[nod]=0; else grd[nod]=mex(s); } int main() { ifstream f("input.txt"); ofstream g("output.txt"); int n, m; cin>>n>>m; int x, y; for(int i=0; i<m; i++) { cin>>x>>y; vecini[x].push_back(y); vecini[y].push_back(x); } bfs(); memset(viz, 0, sizeof(int)*100100); dfs(1); if(!grd[1]){ cout<<"Nikolay\n"; } else cout<<"Vladimir\n"; //cout<<nivel[1]<<" "<<nivel[2]<<" "<<nivel[3]<< " "<<nivel[4]<<"\n"; //cout<<grd[1]<<" "<<grd[2]<<" "<<grd[3]<< " "<<grd[4]; f.close(); g.close(); return 0; }<file_sep>// https://codeforces.com/contest/508/problem/B // https://codeforces.com/contest/508/submission/17535879 #include <string> #include <iostream> using namespace std; int main() { int max = -9, poz = -1; string s; cin >> s; for (int i = 0; i < s.size() - 1; i++) { if ((s[i] - '0') % 2 == 0) { if (s[s.size()-1] > s[i] && max < 0){ max = 0; poz = i; } else if (max!=0) { poz = i; } } } if (poz == -1) puts("-1"); else { char c = s[s.size() - 1]; s[s.size() - 1] = s[poz]; s[poz] = c; cout<<s; } return EXIT_SUCCESS; }<file_sep># https://codeforces.com/contest/237/problem/A # https://codeforces.com/contest/237/submission/14397970 n = int(input()) m,h = map(int,input().split()) nr=1; nr1=1; while n-1>0: x,y=map(int,input().split()) if x==m and y==h: nr1+=1 else: m,h,nr1 = x,y,1 if nr1>nr: nr=nr1 n-=1 print(nr) <file_sep>// https://codeforces.com/contest/678/problem/D // https://codeforces.com/contest/678/submission/18451856 #include <iostream> using namespace std; const unsigned long long MOD=1000000007; unsigned long long pow(unsigned long long a, unsigned long long b) { if (b == 1) return a; if (b == 0) return 1; if (b % 2 == 0) return pow(((a% MOD)*(a% MOD)) % MOD, b / 2); return ((a% MOD)*pow(((a% MOD)*(a% MOD)) % MOD, b / 2)) % MOD; } int main() { unsigned long long a, b, n, x, rez, td, pt; cin >> a >> b >> n >> x; pt = pow(a, n); if (a == 1) td = ((b%MOD) * (n%MOD)) % MOD; else td = (b % MOD * ((pt - 1) % MOD * pow(a-1,MOD-2) % MOD)) % MOD; rez = (((pt%MOD) * (x%MOD)) % MOD + td ) % MOD; cout << rez; return 0; }<file_sep># https://codeforces.com/contest/124/problem/A # https://codeforces.com/contest/124/submission/14872673 n, a, b = map(int,input().split()) print(n-max(a+1,n-b)+1) <file_sep>// https://codeforces.com/contest/712/problem/C // https://codeforces.com/contest/712/submission/21841423 #include <stdio.h> #include <stdlib.h> #include <math.h> #define MIN(a,b) (((a) < (b)) ? (a) : (b)) #define MAX(a,b) (((a) > (b)) ? (a) : (b)) int main() { int a, b, c, goal, steps = 0; bool ok = false; scanf("%d %d", &goal, &a); b = c = a; while (!ok) { ok = true; if (a != goal) { ok = false; a = MIN(b + c - 1, goal); steps++; } if (b != goal) { ok = false; b = MIN(a + c - 1, goal); steps++; } if (c != goal) { ok = false; c = MIN(a + b - 1, goal); steps++; } } printf("%d\n", steps); return EXIT_SUCCESS; }<file_sep># https://codeforces.com/contest/131/problem/A # https://codeforces.com/contest/131/submission/13407839 s=input() if s.isupper(): print(s.lower()) elif len(s)==1 and s.islower(): print(s.upper()) elif s[1:len(s)].isupper(): print(s.capitalize()) else: print(s) <file_sep>// https://codeforces.com/contest/748/problem/D // https://codeforces.com/contest/748/submission/23312486 #include <string> #include <iostream> #include <map> #include <vector> #include <algorithm> using namespace std; string revers(string& s) { string c = s; reverse(c.begin(), c.end()); return c; } int main() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n, k; long long ctt = 0, pr, se, c; long long mx = 0; long long zero = 0; cin >> n >> k; map<string, vector<long long>> m; string s, rev; for (int i = 0; i < n; ++i) { cin >> s >> c; m[s].push_back(c); } for (auto& key : m) { sort(key.second.begin(), key.second.end()); } for (auto& key : m) { s = key.first; rev = revers(s); if (s == rev) { while (m[s].size() > 1) { pr = m[s].back(); m[s].pop_back(); se = m[s].back(); m[s].pop_back(); if (pr > 0 && se < 0) mx = max(mx, pr - max(pr + se, zero)); ctt += max(pr + se, zero); } if (m[s].size() > 0) { pr = m[s].back(); m[s].pop_back(); mx = max(mx, pr); } } else { while (m[s].size() > 0 && m[rev].size() > 0) { pr = m[s].back();m[s].pop_back(); se = m[rev].back();m[rev].pop_back(); ctt += max(pr + se, zero); } } m[s].clear(); m[rev].clear(); } cout << ctt + mx; return 0; }<file_sep># https://codeforces.com/contest/282/problem/A # https://codeforces.com/contest/282/submission/13407539 n=int(input()) nr=0 for i in range(n): s=input() if s[1]=="+": nr+=1 else: nr-=1 print(nr) <file_sep>// https://codeforces.com/contest/701/problem/A // https://codeforces.com/contest/701/submission/21841936 #include <stdio.h> #include <algorithm> #include <vector> using namespace std; typedef struct _STR { int idx, value; _STR() { idx = 0, value = 0; } _STR(int idx, int value) { this->idx = idx, this->value = value; } }STR; bool compare(STR l, STR r) { return l.value < r.value; } int main() { vector<STR> vct; int n, x; scanf("%d", &n); for (int i = 1; i <= n; ++i) { scanf("%d", &x); vct.push_back(STR(i, x)); } sort(vct.begin(), vct.end(), compare); int i = 0; --n; while (i < n) { printf("%d %d\n", vct[i].idx, vct[n].idx); ++i, --n; } return EXIT_SUCCESS; }<file_sep>#include <iostream> #include <fstream> #include <chrono> #include <iomanip> #include <algorithm> #include <string> #include <vector> #include <map> #include <set> #include <queue> #include <numeric> #include <bitset> using namespace std; void Play() { unsigned long long start = 0; unsigned long long end = 1; string result = "y"; while(result == "y") { cout << "? " << start << " " << end << endl; cin >> result; if (result == "y") { start = end; end *= 2; } } while(end - start > 1) { auto mid = (start + end) / 2; cout << "? " << start << " " << mid << endl; cin >> result; (result == "y") ? start = mid : end = mid; }; cout << "! " << start + 1 << endl; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cerr.tie(nullptr); string status; for (cin >> status; status == "start"; cin >> status) { Play(); } return 0; }<file_sep># https://codeforces.com/contest/540/problem/A # https://codeforces.com/contest/540/submission/14011088 n=int(input()) s=input() s2=input() rez=0; for i in range(n): t1=int(s[i]) t2=int(s2[i]) if abs(t1-t2)>min(t1,t2)+10-max(t1,t2): rez+=min(t1,t2)+10-max(t1,t2) else: rez+=abs(t1-t2) print(rez) <file_sep>// https://codeforces.com/problemset/problem/1017/A // https://codeforces.com/problemset/submission/1017/49365147 #include <iostream> #include <fstream> #include <chrono> #include <iomanip> #include <algorithm> #include <string> #include <vector> #include <map> #include <set> #include <queue> #include <numeric> #include <bitset> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cerr.tie(nullptr); int a, b, c, d, thomas, n, rank = 1; cin >> n >> a >> b >> c >> d; thomas = a + b + c + d; for (int i = 1; i < n; ++i) { cin >> a >> b >> c >> d; if (a + b + c + d > thomas) rank++; } cout << rank; return 0; }<file_sep>// https://codeforces.com/contest/369/problem/A // https://codeforces.com/contest/369/submission/17419130 #include <stdio.h> #include <stdlib.h> int main() { int n, a, b, x, i, count; scanf("%d %d %d", &n, &a, &b); for (i = 0, count = 0; i < n; i++) { scanf("%d", &x); if (x == 1) { if (a > 0) a--; else count++; } else { if (b > 0) b--; else if (a > 0) a--; else count++; } } printf("%d", count); return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/731/problem/B // https://codeforces.com/contest/731/submission/21570145 #include <iostream> using namespace std; int main() { int n, x, cup = 0; bool ok = true; cin >> n; for (int i = 0; i < n; ++i) { cin >> x; if (cup == 1) x--; if (x < 0) ok = false; cup = x % 2; } ok = ok && (cup == 0); (ok) ? puts("YES") : puts("NO"); return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/1003/problem/A // https://codeforces.com/contest/1003/submission/46796608 #include <iostream> #include <algorithm> using namespace std; int main() { int v[101] = { 0 }; int n, x, mx = -1; cin >> n; while (n--) { cin >> x; mx = max(mx, ++v[x]); } cout << mx; return 0; }<file_sep>// https://codeforces.com/contest/488/problem/A // https://codeforces.com/contest/488/submission/17418962 #include <iostream> using namespace std; bool valid(long long x) { while (x != 0) { if (x % 10 == 8 || x%10 == -8) return true; x /= 10; } return false; } int main() { long long n, k = 1; cin >> n; for (long long i = n+1; !valid(i); k++, i++); cout << k; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/712/problem/A // https://codeforces.com/contest/712/submission/21814728 #include <stdio.h> using namespace std; int main() { int ai, bi, n; scanf("%d %d", &n, &ai); for (; n > 1; n--) { scanf("%d", &bi); printf("%d ", ai + bi); ai = bi; } printf("%d\n", ai); return 0; } #include <iostream> using namespace std; int main() { ios::sync_with_stdio(false); int ai, bi, n; cin >> n; cin >> ai; for (; n > 1; n--) { cin >> bi; cout << ai + bi << ' '; ai = bi; } cout << ai << '\n'; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/problemset/problem/999/A // https://codeforces.com/contest/999/submission/49378361 #include <iostream> #include <fstream> #include <chrono> #include <iomanip> #include <algorithm> #include <string> #include <vector> #include <map> #include <set> #include <queue> #include <numeric> #include <bitset> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cerr.tie(nullptr); int n, k, cnt = 0, idx = 0; cin >> n >> k; vector<int> v(n); for (int i = 0; i < n; ++i) { cin >> v[i]; } for (idx = 0; idx < n; ++idx) { if (v[idx] > k) break; ++cnt; } for (int i = n - 1; i > idx; --i) { if (v[i] > k) break; ++cnt; } cout << cnt; return 0; }<file_sep># https://codeforces.com/contest/579/problem/A # https://codeforces.com/contest/579/submission/14411323 def power(a,b): if b==1: m = a elif b==0: m = 1 elif b%2==0: m = power(a*a,b//2) else: m = a*power(a*a,(b-1)//2) return m def find_bacteria(n): ans = power(2,1) i = 1 while ans<n: i+=1 ans = power(2,i) if ans>n: ans = power(2,i-1) return ans n = int(input()) nr = 0 while n>1: p = find_bacteria(n) n = n-p nr += 1 if n ==1: nr += 1 print(nr) <file_sep>// https://codeforces.com/contest/519/problem/C // https://codeforces.com/contest/519/submission/17145705 #include <iostream> #include <algorithm> using namespace std; int main() { int n, m; cin >> n >> m; cout << min(n, min(m, (n + m) / 3)); return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/gym/101191/problem/C // https://codeforces.com/gym/101191/submission/47897843 #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; void init(vector<long long>& v) { v.push_back(0); v.push_back(1); for (long long i = 2; v.back() <= 1e9; ++i) { v.push_back(v.back() + i); } } long long bin_search(vector<long long>& v, long long X) { long long lo = 0; long long hi = v.size() - 1; long long idx = 0; while (lo <= hi) { long long mi = (lo + hi) / 2; if (v[static_cast<size_t>(mi)] > X) hi = mi - 1; else idx = mi, lo = mi + 1; } return idx; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); vector<long long> sums; string cbs = ""; long long n = 0; cin >> n; init(sums); while(n > 0) { cbs = "(" + cbs + ")"; --n; string nextCbs = "("; auto idx = bin_search(sums, n - 2); for (long long i = 0; i < idx; ++i) nextCbs += "()"; nextCbs += ")"; long long total = sums[static_cast<size_t>(idx)] + 2; if (n - total >= 0) cbs += nextCbs, n -= total; } cout << cbs; return 0; }<file_sep>// https://codeforces.com/contest/839/problem/A // https://codeforces.com/contest/839/submission/46637035 #include <iostream> #include <algorithm> using namespace std; int main() { int n, k, x, t = 0, d = -1; cin >> n >> k; for (int i = 0; i < n; ++i) { cin >> x; k -= min(8, t + x); t = t + x - min(8, t + x); if (k <= 0) { d = i + 1; break; } } cout << d; return 0; }<file_sep>// https://codeforces.com/problemset/problem/1191/A // https://codeforces.com/contest/1191/submission/68001731 #include <iostream> #include <algorithm> #include <string> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cerr.tie(nullptr); int x; cin >> x; if (x % 4 == 0) cout << "1 A"; else if (x % 4 == 1) cout << "0 A"; else if (x % 4 == 2) cout << "1 B"; else cout << "2 A"; return 0; }<file_sep>// https://codeforces.com/contest/569/problem/B // https://codeforces.com/contest/569/submission/17996677 #include <iostream> #include <string.h> #include <vector> using namespace std; int main(){ int v[100003],f[100003],n; vector<int> ramas; cin>>n; int contor=0; memset(f,0,100003*sizeof(int)); for(int i = 1; i<=n; i++){ cin>>v[i]; f[v[i]]++; } for(int i=1;i<=n;i++) if(f[i]==0) ramas.push_back(i); for(int i=1;i<=n;i++){ if(f[v[i]]>1 || v[i]> n || v[i]<=0){//duplicate f[v[i]]--; cout << ramas[contor++] << " "; } else{ cout << v[i] << " "; } } return 0; } <file_sep>// https://codeforces.com/contest/595/problem/A // https://codeforces.com/contest/595/submission/17558105 #include <stdio.h> #include <stdlib.h> int main() { int n, m, x, y, i, j, nr; scanf("%d %d", &n, &m); for (i = 0, nr = 0; i < n; i++) { for (j = 0; j < 2 * m; j += 2) { scanf("%d %d", &x, &y); if (x || y) nr++; } } printf("%d", nr); return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/problemset/problem/1108/A // https://codeforces.com/contest/1108/submission/49355225 #include <iostream> #include <fstream> #include <chrono> #include <iomanip> #include <algorithm> #include <string> #include <vector> #include <map> #include <set> #include <queue> #include <numeric> #include <bitset> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cerr.tie(nullptr); int q, l1, r1, l2, r2; for (cin >> q; q > 0; --q) { cin >> l1 >> r1 >> l2 >> r2; if (l1 == r2) l1 = r1; cout << l1 << " " << r2 << "\n"; } return 0; }<file_sep>// https://codeforces.com/contest/913/problem/A // https://codeforces.com/contest/913/submission/46626161 #include <iostream> using namespace std; int minpow() { int i = 1; for(int j = 2; j <= 1e8; ++i, j = j<<1); return i; } int main() { int n,m; cin>>n>>m; (n >= minpow()) ? cout << m : cout << m % (1 << n); return 0; }<file_sep>// https://codeforces.com/contest/710/problem/A // https://codeforces.com/contest/710/submission/20566928 #include <stdio.h> #include <stdlib.h> int main() { char c = getchar(), r = getchar(); int rez = 0; if (c == 'a' || c == 'h') { if (r == '1' || r == '8') { rez = 3; } else rez = 5; } else { if (r == '1' || r == '8') { rez = 5; } else rez = 8; } printf("%d\n",rez); return EXIT_SUCCESS; } <file_sep>// https://codeforces.com/problemset/problem/919/A // https://codeforces.com/contest/919/submission/48049287 #include <iostream> #include <iomanip> #include <algorithm> using namespace std; int main() { int n, m, a, b; double res = numeric_limits<double>::max(); cin >> n >> m; while (n--) { cin >> a >> b; res = min(res, static_cast<double>(m * a) / static_cast<double>(b)); } cout << setprecision(12) << fixed << res; return 0; }<file_sep>// https://codeforces.com/contest/680/problem/A // https://codeforces.com/contest/680/submission/18452312 #include <iostream> using namespace std; int main() { int v[102], x, i, s, st = 0; memset(v, 0, 102 * sizeof(int)); for (i = 0; i < 5; i++) cin>>x, v[x]++, st += x; s = st; for (int i = 100; i > 0; i--) { if (v[i] >= 3) { if (st - i * 3 < s) s = st - i * 3; } else if (v[i] == 2) { if (st - i * 2 < s) s = st - i * 2; } } cout << s; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/586/problem/A // https://codeforces.com/contest/586/submission/17471048 #include <iostream> using namespace std; int main() { int n, i = 1, count = 0; char x, y, ok = '1'; cin >> n; getchar(); for (; i <= n && count == 0; i++) { x = getchar(); if (x == '1') count++; getchar(); } y = x; for (; i <= n; i++) { x = getchar(); if (x == '1' && ok == '0' ) count+=2, ok = '1'; else if (x == '1') count++; else { if (y == '1' && ok == '1') ok = '0'; else if (y == '0' && ok == '0') ok = '1'; } y = x; getchar(); } cout << count; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/246/problem/A // https://codeforces.com/contest/246/submission/18055009 #include <iostream> #include <random> using namespace std; int main() { int n; cin >> n; if (n < 3) puts("-1"); else for (; n > 0; n--)cout << n << " "; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/gym/101246/problem/E // https://codeforces.com/gym/101246/submission/25245302 #include <iostream> #include<fstream> #include<string> #include <queue> #include <algorithm> #include <set> #include <string.h> #define cin f #define cout g using namespace std; int mat[110][110]; int main() { ifstream f("input.txt"); ofstream g("output.txt"); int n,k; int mat[205][205]; int vis[205]; queue<pair<int,int>> v; set<int> sol; f>> n; for(int i = 1; i<= n; ++i) for(int j = 1; j<= n; ++j) f>>mat[i][j]; f >> k; v.push(make_pair(1,1)); int niv = 1, road; while(k > 0) { memset(vis,0,205*sizeof(int)); f >> road; if (v.empty()) break; while(!v.empty() && v.front().second == niv) { int el = v.front().first; v.pop(); for(int i = 1; i<=n; ++i) if (vis[i] == 0 && mat[el][i] == road) v.push(make_pair(i,niv+1)), vis[i] = 1; } niv++; k--; } while(!v.empty()) { sol.insert(v.front().first); v.pop(); } g<<sol.size()<<"\n"; for(int el : sol) g<< el<<" "; f.close(); g.close(); return 0; }<file_sep># https://codeforces.com/contest/448/problem/A # https://codeforces.com/contest/448/submission/14009316 a,b,c=map(int,input().split()) r=int((a+b+c)/5) if (a+b+c)%5!=0: r+=1 a,b,c=map(int,input().split()) r2=int((a+b+c)/10) if (a+b+c)%10!=0: r2+=1 r+=r2 n=int(input()) if r>n: print('NO') else: print('YES') <file_sep>// https://codeforces.com/contest/478/problem/B // https://codeforces.com/contest/478/submission/28727713 #include <iostream> #include <string> using namespace std; int main() { int n, m; cin >> n >> m; unsigned long long mic = n / m, mic2 = n % m; unsigned long long mare = n - m + 1; cout << mic2 * (mic + 1) * mic / 2 + (m - mic2) * (mic - 1 ) * mic / 2<< " " << (mare - 1) * mare / 2; return 0; } <file_sep>// https://codeforces.com/contest/894/problem/A // https://codeforces.com/contest/894/submission/46639459 #include <iostream> #include <string> #include <vector> using namespace std; int Bsearch0(vector<int>& Vec, int X) { int lo = 0; int hi = Vec.size() - 1; int m; int found = -1; while (lo <= hi) { m = (lo + hi) / 2; if (Vec[m] > X) hi = m - 1; else found = m, lo = m + 1; } return found; } int Bsearch1(vector<int>& Vec, int X) { int lo = 0; int hi = Vec.size() - 1; int m; int found = -1; while (lo <= hi) { m = (lo + hi) / 2; if (Vec[m] <= X) lo = m + 1; else found = m, hi = m - 1; } return found == -1 ? 0 : Vec.size() - found; } int main() { string s; vector<int> q; vector<int> a; int t = 0; cin >> s; for (size_t i = 0; i < s.size(); ++i) { if (s[i] == 'A') a.push_back(i); else if (s[i] == 'Q') q.push_back(i); } for (const auto& pa : a) { t = t + (Bsearch0(q, pa) + 1) * Bsearch1(q, pa); } cout << t; return 0; }<file_sep># https://codeforces.com/contest/486/problem/A # https://codeforces.com/contest/486/submission/13960500 n=int(input()) if n%2==0: print(int(n/2)) else: print(int(-1-(n/2))) <file_sep>// https://codeforces.com/contest/519/problem/A // https://codeforces.com/contest/519/submission/14057025 #include <iostream> using namespace std; int white['Z'+1],black['z'+1]; void init() { white['Q']=9; black['q']=9; white['R']=5; black['r']=5; white['B']=3; black['b']=3; white['N']=3; black['n']=3; white['P']=1; black['p']=1; white['K']=0; black['k']=0; } int main() { char c; int black_points=0, white_points=0; init(); for (int i=0;i<8;i++) { for (int j=0;j<8;j++) { cin>>c; if (c!='.' && c<'Z') { white_points+=white[c]; } else if (c!='.') { black_points+=black[c]; } } } if (white_points>black_points) { cout<<"White"; } else if (white_points<black_points) { cout<<"Black"; } else { cout<<"Draw"; } return 0; } <file_sep># https://codeforces.com/contest/560/problem/A # https://codeforces.com/contest/560/submission/14575554 n = int(input()) l = list(map(int,input().split())) if 1 in l: print('-1') else: print('1') <file_sep>// https://codeforces.com/contest/764/problem/A // https://codeforces.com/contest/764/submission/28727849 #include <iostream> #include <string> using namespace std; int main() { int n, m, z; cin>>n>>m>>z; int gcd = 1; //gcd - zsisku for(int i=1; i<=z; i++) { if(n% i == 0 && m%i == 0) gcd = i; } int lcm = (n*m)/gcd; cout << (z/lcm); return 0; } <file_sep>// https://codeforces.com/contest/451/problem/B // https://codeforces.com/contest/451/submission/18724654 #ifndef _CRT_NONSTDC_NO_WARNINGS #define _CRT_NONSTDC_NO_WARNINGS #include <cstdio> #include <cstdlib> #include <iostream> #include <string> #include <cmath> #include <vector> using namespace std; void swap(int&a, int&b) {int aux = a;a = b;b = aux;} int main() { int n, v[100005], i = 0, j; vector<int> rez; for (scanf("%d", &n); i < n; scanf("%d", &v[i++])); i = 0; while (i < n - 1) { if (v[i] > v[i + 1]) { rez.push_back(i + 1); j = i; while (j < n - 1 && v[j] > v[j + 1]) j++; rez.push_back(j+1); swap(v[i], v[j]); if (i > 0 && v[i - 1] > v[i]) i = n, rez.push_back(2); else i = j; } else i++; } (rez.size() > 2) ? puts("no") : ((rez.size() == 0) ? puts("yes\n1 1\n") : printf("yes\n%d %d\n", rez[0], rez[1])); return EXIT_SUCCESS; } #endif //_CRT_NONSTDC_NO_WARNINGS<file_sep>// https://codeforces.com/contest/712/problem/B // https://codeforces.com/contest/712/submission/21840726 #include <string> #include <iostream> using namespace std; #define ABS(x) (((x) > (0)) ? (x) : (-x)) int main() { string s; cin >> s; int y, x = y = 0; if (s.size() % 2 == 1) { puts("-1"); return EXIT_SUCCESS; } for (size_t i = 0; i < s.size(); ++i) { if (s[i] == 'U') y++; else if (s[i] == 'D') y--; else if (s[i] == 'L') x--; else if (s[i] == 'R') x++; } cout << ABS( ABS(x) / 2 + ABS(y) / 2) + ABS(x) % 2; return EXIT_SUCCESS; }<file_sep># https://codeforces.com/contest/519/problem/B # https://codeforces.com/contest/519/submission/14419382 n = int(input()) l = list(map(int,input().split())) dicts = {} for el in l: if el in dicts.keys(): dicts[el]+=1 else: dicts[el]=1 p = list(map(int,input().split())) dictssec={} for el in p: if dicts[el]>1: dicts[el]-=1 else: del(dicts[el]) if el in dictssec.keys(): dictssec[el]+=1 else: dictssec[el]=1 l = list(map(int,input().split())) h = list(dicts.keys()) print(h[0]) for el in l: if dictssec[el]>1: dictssec[el]-=1 else: del(dictssec[el]) h = list(dictssec.keys()) print(h[0]) <file_sep># https://codeforces.com/contest/136/problem/A # https://codeforces.com/contest/136/submission/13580602 def find(k,l): for i in range(len(l)): if l[i]==k: return i+1 n = int(input()) l = list(map(int,input().split())) for i in range(n): print(find(i+1,l),end=' ') <file_sep>// https://codeforces.com/contest/456/problem/B // https://codeforces.com/contest/456/submission/17592868 #include <iostream> #include <string> using namespace std; int main() { string s; getline(cin, s); if (s.size() == 1) { if (s[0] == '0' || s[0] == '4' || s[0] == '8') putchar('4'); else putchar('0'); } else { if (stoi(s.substr(s.size() - 2, 2)) % 4 == 0) putchar('4'); else putchar('0'); } return EXIT_SUCCESS; }<file_sep># https://codeforces.com/contest/231/problem/A # https://codeforces.com/contest/231/submission/13406348 n=int(input()) nr=0 for i in range(n): a,b,c=map(int, input().split()) nraux=0 if a==1: nraux+=1 if b==1: nraux+=1 if c==1: nraux+=1 if nraux>=2: nr+=1 print(nr) <file_sep>// https://codeforces.com/contest/606/problem/C // https://codeforces.com/contest/606/submission/17916901 #include <iostream> using namespace std; int main() { int v[100002], n, x, mx = 0; memset(v, 0, 100002 * sizeof(int)); cin >> n; for (int i = 0; i < n; i++) { cin >> x; v[x] = 1 + v[x - 1]; if (v[x] > mx) mx = v[x]; } cout << n - mx; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/791/problem/C // https://codeforces.com/contest/791/submission/25626271 #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <map> #include <unordered_map> #include <set> #include <vector> #include <cstdio> #include <string> using namespace std; #define ll long long #define ull unsigned long long /*------------------------------------------------------------------*/ int n, k, idx; int nou[60]; string t = "Aa"; string next(int idx) { if (t[t.size() - 1] != 'z')t[t.size() - 1]++; else t += 'a'; return t; } int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); int amAjuns = 1; string s, last = next(idx); cin >> n >> k; vector<string> sol; for(int i = 1; i<=n-k+1;++i) { cin >> s; if (s == "YES") { for (int j = max(i, amAjuns); j <= i + k - 1; ++j)sol.push_back(next(++idx)); amAjuns = i + k; } else { if (i == 1) sol.push_back(next(idx)), amAjuns++; sol.push_back(sol[i - 1]); amAjuns++; } } while (amAjuns++ <= n) sol.push_back(next(++idx)); for (string s : sol)cout << s<<" "; return 0; }<file_sep>// https://codeforces.com/contest/743/problem/D // https://codeforces.com/contest/743/submission/22983812 #include <vector> #include <stdio.h> #include <algorithm> #include <iostream> using namespace std; vector<int> graph[200005]; vector<long long> cost(200005, 0); vector<bool> visited(200005, false); vector<long long> maxSuma(200005, LLONG_MIN); int n; long long ans = LLONG_MIN; void dfs(int nodulet) { visited[nodulet] = true; long long mare = LLONG_MIN; long long mare2 = LLONG_MIN; long long sumaFii = 0; for (auto vecin : graph[nodulet]) { if (visited[vecin] == true) continue; dfs(vecin); sumaFii += cost[vecin]; if (maxSuma[vecin] >= mare) { mare2 = mare; mare = maxSuma[vecin]; } else if (maxSuma[vecin] > mare2) { mare2 = maxSuma[vecin]; } } cost[nodulet] += sumaFii; maxSuma[nodulet] = max(mare, cost[nodulet]); if (mare != LLONG_MIN && mare2 != LLONG_MIN) ans = max(ans, mare + mare2); } int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) scanf("%I64d", &cost[i]); int x, y; for (int i = 0; i < n - 1; ++i) { scanf("%d %d", &x, &y); graph[x].push_back(y); graph[y].push_back(x); } dfs(1); if (ans == LLONG_MIN) puts("Impossible"); else cout << ans; return 0; }<file_sep># https://codeforces.com/contest/499/problem/B # https://codeforces.com/contest/499/submission/16472830 n,m = map(int,input().split()) dic = {} while m > 0 : key,value = input().split() dic[key] = value; m -= 1 l = list(input().split()) for el in l: if len(el) <= len(dic[el]): print(el, sep = ' ', end = ' ') else: print(dic[el], sep = ' ', end = ' ') <file_sep>// https://codeforces.com/contest/608/problem/A // https://codeforces.com/contest/608/submission/18043778 #include <iostream> using namespace std; int main() { int n, s, v[1001], sm = 0, et, arrival; memset(v, 0, 1001 * sizeof(int)); cin >> n >> s; for (int i = 0; i < n; i++) { cin >> et >> arrival; if (v[et] < arrival) v[et] = arrival; } sm = 0; for (int i = s; i > 0; i--, sm++) { if (sm < v[i]) sm += v[i] - sm; } cout << sm; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/731/problem/A // https://codeforces.com/contest/731/submission/21480669 #include <iostream> #include <string> #include <algorithm> using namespace std; int main() { string s; cin >> s; int sum, ma, mi; size_t size = s.size(); sum = min(s[0] - 'a', 27 - (s[0] - 96)); for (size_t i = 1; i < size; ++i) { if (s[i] > s[i - 1]) ma = s[i], mi = s[i - 1]; else ma = s[i - 1], mi = s[i]; sum += min(ma - mi, 26 - (ma - mi)); } cout << sum; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/621/problem/A // https://codeforces.com/contest/621/submission/16450717 #include <stdio.h> #include <stdlib.h> #define MAX 0x3B9ACA01 int main(){ int n,i,odds = 0; unsigned long long x, oddmin = MAX, s = 0; scanf_s("%d", &n); for (i = 0; i < n; i++){ scanf_s("%llu", &x); s += x; if (x & 1) { odds++; if (x < oddmin) oddmin = x; } } if (odds & 1) s -= oddmin; printf("%llu", s); return EXIT_SUCCESS; } #include <stdio.h> #include <stdlib.h> #define MAX 0x3B9ACA01 int main(){ int n,i,odds = 0; unsigned long long x, oddmin = MAX, s = 0; scanf_s("%d", &n); for (i = 0; i < n; i++){ scanf_s("%llu", &x); s += x; if (x % 2 == 1) { odds++; if (x < oddmin) oddmin = x; } } if (odds % 2 == 1) s -= oddmin; printf("%llu", s); return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/548/problem/A // https://codeforces.com/contest/548/submission/17433560 #include <iostream> #include <string> using namespace std; bool ispal(const string& p); int main() { string s,p; int n,sz; cin >> s >> n; if (s.size() % n != 0) { puts("NO"); goto Clean; } sz = s.size() / n; for (int pivot = 0; pivot < n; pivot++) { p = s.substr(sz*pivot, sz); if (!ispal(p)) { puts("NO"); goto Clean; }; } puts("YES"); Clean: return EXIT_SUCCESS; } bool ispal(const string& p) { int size = p.size(); for (int i = 0; i < size / 2; i++) { if (p[i] != p[size - i - 1]) return false; } return true; }<file_sep># https://codeforces.com/contest/270/problem/A # https://codeforces.com/contest/270/submission/14468305 n = int(input()) while n>0: x = int(input()) if 360 % (180-x) ==0: print('YES') else: print('NO') n-=1 <file_sep>// https://codeforces.com/contest/472/problem/C // https://codeforces.com/contest/472/submission/18054753 #include <iostream> #include <cstdlib> #include <string> #include <cstdio> #include <vector> #include <algorithm> using namespace std; class Elev { public: string nume; string prenume; Elev(const string& nume, const string& prenume) : nume{ nume }, prenume{ prenume } {}; Elev() :nume{ "" }, prenume{ "" } {}; }; int main() { int n, poz; bool ok = true; Elev first, last; string nume, prenume; vector <Elev> v; cin >> n; for (int i = 1; i <= n; i++) { cin >> nume >> prenume; v.push_back(Elev(nume, prenume)); } cin >> poz; nume = min(v[poz - 1].nume, v[poz - 1].prenume); int i = 2; while (i <= n && ok == true) { cin >> poz; last = v[poz - 1]; if (last.nume >= nume && last.prenume < nume) nume = last.nume; else if (last.prenume >= nume && last.nume < nume) nume = last.prenume; else if (last.nume >= nume && last.prenume >= nume) nume = min(last.nume, last.prenume); else { ok = false; } i++; } (ok) ? puts("YES") : puts("NO"); return EXIT_SUCCESS; } <file_sep>// https://codeforces.com/contest/749/problem/D // https://codeforces.com/contest/749/submission/23162259 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <vector> #include <algorithm> using namespace std; #define INT32_MIN (-1) vector<int> arbore(800005, INT32_MIN); vector<int> indecsi(800005, INT32_MIN); vector<int> v[200005]; int maxi = INT32_MIN; int pos = INT32_MIN; void update(int node, int left, int right, int value, int pos) { if (left == right) { arbore[node] = value; indecsi[node] = pos; return; } int mid = (left + right) / 2; if (pos <= mid) update(2 * node, left, mid, value, pos); else update(2 * node + 1, mid + 1, right, value, pos); if (arbore[node * 2] > arbore[node * 2 + 1]) { indecsi[node] = indecsi[node * 2]; arbore[node] = arbore[node * 2]; } else { indecsi[node] = indecsi[node * 2 + 1]; arbore[node] = arbore[node * 2 + 1]; } } void Querry(int node, int left, int right, int start, int finish) { if (start <= left && right <= finish) { if (maxi < arbore[node]) maxi = arbore[node], pos = indecsi[node]; return; } int mid = (left + right) / 2; if (start <= mid) update(2 * node, left, mid, start, finish); if (mid < finish) update(2 * node + 1, mid + 1, right, start, finish); } int main() { int n, contestant, bid, x; scanf("%d", &n); for (int i = 1; i <= n; ++i) { v[i].push_back(INT32_MIN); scanf("%d %d", &contestant, &bid); update(1, 1, n, bid, contestant); v[contestant].push_back(bid); } for (int i = 1; i <= n; ++i) { sort(v[i].begin(), v[i].end()); } int m, sz; vector<int>querry; scanf("%d", &m); for (int i = 0; i < m; ++i) { querry.clear(); scanf("%d", &sz); pos = INT32_MIN; maxi = INT32_MIN; for (int j = 0; j < sz; ++j) { scanf("%d", &x); querry.push_back(x); update(1, 1, n, INT32_MIN, x); } Querry(1, 1, n, 1, n); if (pos == INT32_MIN) puts("0 0"); else { int maximLocal = maxi; int posLocal = pos; pos = INT32_MIN; maxi = INT32_MIN; querry.push_back(posLocal); update(1, 1, n, INT32_MIN, posLocal); Querry(1, 1, n, 1, n); if (maxi == maximLocal) printf("0 0\n"); else { maximLocal = *(lower_bound(v[posLocal].begin(), v[posLocal].end(), maxi + 1)); printf("%d %d\n", posLocal, maximLocal); } } for (int p : querry) { update(1, 1, n, v[p][v[p].size() - 1], p); } } return 0; }<file_sep>// https://codeforces.com/contest/735/problem/A // https://codeforces.com/contest/735/submission/22532948 #include <iostream> #include<string> #include<cstdlib> #include<algorithm> using namespace std; int main() { int n, k; int g, t; string s; cin >> n >> k >> s; bool ok = true; for (int i = 0; i < s.size(); i++) { if (s[i] == 'G') g = i; if (s[i] == 'T') t = i; } if ((g - t) % k == 0) { int A, B; A = min(g, t); B = max(g, t); while (ok && A != B) { if (s[A] == '#') ok = false; A += k; } } else ok = false; cout << ((ok) ? ("YES") : ("NO")); return 0; }<file_sep>// https://codeforces.com/contest/230/problem/A // https://codeforces.com/contest/230/submission/14058507 #include <iostream> #include <algorithm> using namespace std; struct dragon{ int level,power; }; bool accompare (dragon lhs, dragon rhs){return lhs.level<rhs.level;} int main() { dragon list[10000]; int n,s; cin>>s>>n; for (int i=0;i<n;i++) { cin>>list[i].level>>list[i].power; } sort(list,list+n,accompare); bool ok=true; int i=0; while (i<n && ok==true) { if (s<=list[i].level) { ok = false; } else { s=s+list[i].power; i++; } } if (ok==false) { cout<<"NO"; } else { cout<<"YES"; } return 0; } <file_sep># https://codeforces.com/contest/50/problem/A # https://codeforces.com/contest/50/submission/13405987 m,n = map(int, input().split()) c=m*n/2 print(int(c)) <file_sep>// https://codeforces.com/contest/688/problem/B // https://codeforces.com/contest/688/submission/22867635 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <math.h> #include <algorithm> #include <iostream> #include <string> using namespace std; int main() { string s; cin >> s; cout << s; reverse(s.begin(), s.end()); cout << s; return 0; } <file_sep># https://codeforces.com/contest/459/problem/B # https://codeforces.com/contest/459/submission/14543529 n = int(input()) l = sorted(list(map(int,input().split()))) nr = 0 nr2 = 0 i = 0 if l[0]==l[n-1]: nr = (n)*(n-1)//2 n = n-1 else: while i<n-1 and l[0] == l[i]: i,nr = i+1, nr+1 n -= 1 i = n while i>1 and l[n] == l[i]: i, nr2 = i-1, nr2+1 nr = nr*nr2 if len(l)==2: nr+=1 print(l[n]-l[0],nr) <file_sep>// https://codeforces.com/contest/465/problem/A // https://codeforces.com/contest/465/submission/17145967 #include <iostream> using namespace std; int main() { int n, count = 1; char x; bool ok = true; cin >> n; getchar(); while (ok) { x = getchar(); if (x != '1') ok = false; else count++; } if (x != '0') count--; cout << count; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/599/problem/B // https://codeforces.com/contest/599/submission/14385888 #include <iostream> using namespace std; int main() { int a[100001],f[100001],b[100001],n,m; for (int i=1;i<=100001;i++) { a[i]=-1; } cin>>n>>m; for (int i=1;i<=n;i++) { cin>>f[i]; } for (int i=1;i<=m;i++) { cin>>b[i]; } for (int i=1;i<=n;i++) { if (a[f[i]]==-1) { a[f[i]]=i; } else { a[f[i]]=-999; } } bool okimp = true; bool okamb = true; for (int i=1;i<=m;i++) { if (a[b[i]]==-1) { okimp = false; } else { if (a[b[i]]==-999) { okamb = false; } } } if (!okimp){cout<<"Impossible";} else if (!okamb){cout<<"Ambiguity";} else { cout<<"Possible"<<"\n"; for (int i=1;i<=m;i++) { cout<<a[b[i]]<<" "; } } return 0; } <file_sep>// https://codeforces.com/contest/570/problem/A // https://codeforces.com/contest/570/submission/14395674 #include <iostream> using namespace std; long long v[102]; int main() { int n,m,x; int cand_for_city,cand_index,grand_total=-1,total_index=-1; cin>>m>>n; for (int i=1;i<=n;i++) { cand_for_city = -1; for (int j=1;j<=m;j++) { cin>>x; if (x>cand_for_city) { cand_for_city = x; cand_index = j; } } v[cand_index]++; if (grand_total<v[cand_index]||(grand_total==v[cand_index] && cand_index<total_index)) { grand_total=v[cand_index]; total_index=cand_index; } } cout<<total_index; return 0; } <file_sep>// https://codeforces.com/contest/611/problem/A // https://codeforces.com/contest/611/submission/16614944 #include <iostream> #include <string.h> using namespace std; int main(int argc, char* argv[]) { int months[] = { 0,31,29,31,30,31,30,31,31,30,31,30,31 }, days[] = { 0,52,52,52,52,53,53,52 }, n, sum = 0; char s[10]; cin >> n >> s >> s; if (!strcmp(s, "week")) cout << days[n]; else { for (int i = 1; i <= 12; i++) if (months[i] >= n) sum++; cout << sum; } return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/277/problem/A // https://codeforces.com/contest/277/submission/48031502 #include <map> #include <algorithm> #include <set> #include <iostream> using namespace std; int find(map<int, int>& parent, int x) { if (x == parent[x]) return x; return parent[x] = find(parent, parent[x]); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, m, k, x, y, ctx = 0; map<int, int> languages; set<int> masters; cin >> n >> m; for (int i = 1; i <= n; ++i) { cin >> k; if (k == 0) { ++ctx; continue; } cin >> x; if (languages[x] == 0) languages[x] = x; auto px = find(languages, x); for (int j = 2; j <= k; ++j) { cin >> y; if (languages[y] == 0) languages[y] = y; auto py = find(languages, y); languages[py] = px; } } for (auto& keyValuePair : languages) { masters.insert(find(languages, keyValuePair.first)); } if (masters.size() == 0) cout << ctx; else cout << masters.size() - 1 + ctx; return 0; }<file_sep>// https://codeforces.com/contest/606/problem/D // https://codeforces.com/contest/606/submission/17913074 #include <iostream> #include <algorithm> using namespace std; typedef struct _DATE { int cost, in, poz; }DATE, *DATEPTR; typedef struct _MUCHIE { int x, y; }MUCHIE, *MUCHIEPTR; int main() { DATEPTR date; MUCHIEPTR muchii; int v[100002], n, m, lastNode = 2, currNode = 1; for (int i = 1; i < 100002; i++) v[i] = i + 2; cin >> n >> m; date = (DATEPTR)malloc((m+1) * sizeof(DATE)); muchii = (MUCHIEPTR)malloc((m+1)* sizeof(MUCHIE)); for (int i = 1; i <= m; i++) { cin >> date[i].cost >> date[i].in; date[i].poz = i; } sort(date+1, date + 1 + m, [&](DATE& dataLeft, DATE& dataRight) { return (dataLeft.cost < dataRight.cost || dataLeft.cost == dataRight.cost && dataLeft.in > dataRight.in || dataLeft.cost == dataRight.cost && dataLeft.in == dataRight.in && dataLeft.poz < dataRight.poz ); }); if (date[1].in == 0) { puts("-1"); goto Cleanup; } muchii[date[1].poz].x = 1; muchii[date[1].poz].y = 2; for (int i = 2; i <= m; i++) { if (date[i].in == 1) { muchii[date[i].poz].x = lastNode; muchii[date[i].poz].y = lastNode + 1; lastNode++; currNode = 1; } else { if (v[currNode] <= lastNode) { muchii[date[i].poz].x = currNode; muchii[date[i].poz].y = v[currNode]; v[currNode]++; if (v[currNode] > lastNode)currNode++; } else { puts("-1"); goto Cleanup;; } } } for (int i = 1; i <= m; i++)cout << muchii[i].x << " " << muchii[i].y << "\n"; Cleanup: free(muchii); free(date); return EXIT_SUCCESS; }<file_sep># https://codeforces.com/contest/61/problem/A # https://codeforces.com/contest/61/submission/13614120 a=input() b=input() c=[] for i in range(len(a)): if a[i]==b[i]: c.append(0) else: c.append(1) for i in range (len(a)): print(c[i],sep='', end='') <file_sep>// https://codeforces.com/contest/629/problem/A // https://codeforces.com/contest/629/submission/17462230 #include <iostream> using namespace std; int main() { int lin[101], col[101], n, s = 0; memset(lin, 0, 101 * sizeof(int)); memset(col, 0, 101 * sizeof(int)); cin >> n; getchar(); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (getchar() == 'C') lin[i]++, col[j]++; } getchar(); } for (int i = 1; i <= n; i++) s += (lin[i] - 1)*lin[i] / 2 + (col[i] - 1) * col[i] / 2; cout << s; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/732/problem/B // https://codeforces.com/contest/732/submission/21650297 #include <stdio.h> #include <stdlib.h> int main() { int n, k, v[504], s = 0; scanf("%d %d", &n, &k); for (int i = 0; i < n; ++i) scanf("%d", &v[i]); for (int i = 1; i < n; ++i) { if (v[i - 1] + v[i] < k) { s += (k - (v[i - 1] + v[i])); v[i] += (k - (v[i - 1] + v[i])); } } printf("%d\n", s); for (int i = 0; i < n; ++i) printf("%d ", v[i]); return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/217/problem/A // https://codeforces.com/contest/217/submission/48030693 #include <iostream> #include <algorithm> #include <map> #include <vector> #include <set> using namespace std; int find(map<int, int>& parent, int x) { if (x == parent[x]) return x; return parent[x] = find(parent, parent[x]); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, x, y; map<int, int> uniX; map<int, int> east; set<int> newDrifts; cin >> n; for (int i = 1; i <= n; ++i) { cin >> x >> y; if (uniX[x] == 0) uniX[x] = x; if (east[y] == 0) east[y] = x; auto px = find(uniX, x); auto py = find(uniX, east[y]); uniX[py] = px; east[y] = px; } for (auto& keyValuePair : uniX) { newDrifts.insert(find(uniX, keyValuePair.first)); } cout << newDrifts.size() - 1; return 0; }<file_sep>// https://codeforces.com/contest/598/problem/A // https://codeforces.com/contest/598/submission/17154517 #include <iostream> using namespace std; int main() { int t; unsigned long long n, s1, s2, ratio; long long s; cin >> t; for (; t > 0; t--) { cin >> n; s1 = (1 + n) * n / 2; ratio = 1; while (ratio <= n) ratio <<= 1; s2 = ratio - 1; s = (s1 - 2 * s2); cout << s << endl; } return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/368/problem/B // https://codeforces.com/contest/368/submission/25721896 #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <map> #include <unordered_map> #include <set> #include <vector> #include <cstdio> #include <string> using namespace std; #define ll long long #define ull unsigned long long /*------------------------------------------------------------------*/ int n, m, ct; unordered_map<int, bool> mp; int pt[100005], dp[100005]; int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); cin >> n >> m; for (int i = 1; i <= n; ++i) cin >> pt[i]; for(int i = n; i > 0; --i) { if (mp[pt[i]] != true) ct++; mp[pt[i]] = true; dp[i] = ct; } for(int x, i = 1; i<=m;++i ) { cin >> x; cout << dp[x] << "\n"; } return 0; }<file_sep>// https://codeforces.com/contest/552/problem/A // https://codeforces.com/contest/552/submission/17433232 #include <stdio.h> #include <stdlib.h> int main() { int cnt = 0, n, x1, y1, x2, y2; scanf("%d", &n); for (; n > 0; n--) { scanf("%d %d %d %d", &x1, &y1, &x2, &y2); cnt += (x2 - x1 + 1) * (y2 - y1 + 1); } printf("%d", cnt); return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/758/problem/A // https://codeforces.com/contest/758/submission/27364470 #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int n; int mx = numeric_limits<int>::min(); vector<int> vct(100, 0); int s = 0; cin >> n; for (int i = 0; i < n; ++i)cin >> vct[i] , mx = max(mx, vct[i]); for (int i = 0; i < n; ++i) s += mx - vct[i]; cout << s; return 0; } <file_sep>// https://codeforces.com/contest/219/problem/A // https://codeforces.com/contest/219/submission/18041939 #include <iostream> #include <string> using namespace std; int main() { int n, v[28], min; string s; cin >> n >> s; min = n; memset(v, 0, 28 * sizeof(int)); for (size_t i = 0; i < s.size(); i++) v[s[i] - 'a']++; for (size_t i = 0; i < 28; i++) { if (v[i] != 0) { if (v[i] % n != 0) { cout << -1; goto exit; } else if (min > v[i]) min = v[i]; } } for (int i = 0; i < min; i++) { for (size_t j = 0; j < 28; j++) { for (int k = 0; k < v[j] / n; k++) { putchar(j + 'a'); } } } exit: return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/gym/100810/problem/C // https://codeforces.com/gym/100810/submission/18234771 #include <iostream> #include <string.h> using namespace std; int vals( const string& str){ int nr = 0; int i = 0; int size = str.size(); while (i < size && str[i] == 'M')nr+=1000,i++; if (i < size && i+1 < size && str[i] == 'C' && str[i + 1] == 'M') nr+=900, i+=2; if (i < size && str[i] == 'D') nr += 500, i++; if (i < size && i+1 < size && str[i] == 'C' && str[i + 1] == 'D') nr+=400, i+=2; while (i < size && str[i] == 'C')nr+=100,i++; if (i < size && i+1 < size && str[i] == 'X' && str[i + 1] == 'C') nr+=90, i+=2; if (i < size && str[i] == 'L') nr += 50, i++; if (i < size && i+1 < size && str[i] == 'X' && str[i + 1] == 'L') nr+=40, i+=2; while (i < size && str[i] == 'X')nr+=10,i++; if (i < size && i+1 < size && str[i] == 'I' && str[i + 1] == 'X') nr+=9, i+=2; if (i < size && str[i] == 'V') nr += 5, i++; if (i < size && i+1 < size && str[i] == 'I' && str[i + 1] == 'V') nr+=4, i+=2; while (i < size && str[i] == 'I')nr+=1,i++; if (i < size && str[i] == 'O') nr = 0; return nr; } string roman(int val){ string roman = ""; while (val >= 1000) roman+="M", val-=1000; if (val >= 900) roman +="CM", val-=900; if (val >= 500) roman+="D", val-=500; if (val >= 400) roman+="CD",val-=400; while (val >= 100) roman+="C",val-=100; if (val >= 90) roman+="XC",val-=90; if (val >= 50) roman+="L",val-=50; if (val >= 40) roman+="XL",val-=40; while (val >= 10)roman+="X",val-=10; if (val>=9) roman+="IX", val-=9; if (val>=5) roman+="V", val-=5; if (val>=4) roman+="IV", val-=4; while (val >= 1) roman+="I",val--; if (roman == "" && val == 0) roman = "O"; return roman; } bool is_digit(char c){ return (c == '0' || c=='1' || c =='2' ||c == '3' || c=='4' || c=='5' || c=='6' || c=='7' || c=='8' || c=='9'); } int main() { string line = ""; int v[10]; for (int i = 0; i< 10; i++) v[i] = -1; while (line != "QUIT"){ cin>>line; if (line == "RESET"){ cout<<"Ready\n"; for (int i = 0; i< 10; i++) v[i] = -1; } else if (line == "QUIT"){ cout<<"Bye\n"; } else{ int registru = line[0] - 48; int val = 0; char op = '+'; int i = 2; bool ok = true; if (line[2] == '-' || line[2] == '+'){ cout<<"Error\n"; }else{ while (i < line.size() && ok){ string expr = ""; while(i < line.size() && !is_digit(line[i]) && line[i] != '+' && line[i] !='-'){ expr+=line[i]; i++; } if (expr == ""){ if (is_digit(line[i])){ int cifra = line[i] - 48; if (v[cifra] == -1){ ok = false; } else{ if (op =='+') val+=v[cifra]; else val-=v[cifra]; } } else op = line[i]; i++; } else{ if (op =='+') val+=vals(expr); else val-=vals(expr); } } if (val < 0 || val > 10000) ok = false; if (!ok) cout<<"Error\n"; else{ v[registru] = val; cout<<registru<<"="<<roman(val)<<"\n"; } } } } return 0; }<file_sep>// https://codeforces.com/contest/716/problem/A // https://codeforces.com/contest/716/submission/21733770 #include <stdio.h> #include <stdlib.h> int main() { int c, n, ct = 1, f, cur; scanf("%d %d %d", &n, &c, &f); for (int i = 1; i < n; ++i) { scanf("%d", &cur); if (cur - f> c) { ct = 1; } else ct++; f = cur; } printf("%d", ct); return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/432/problem/A // https://codeforces.com/contest/432/submission/14416498 #include <iostream> using namespace std; int main() { int n,k,x,nr=0; cin>>n>>k; while (n>0) { cin>>x; if (x+k<=5){nr++;} n--; } cout<<nr/3; return 0; } <file_sep>// https://codeforces.com/contest/651/problem/B // https://codeforces.com/contest/651/submission/47181097 #include <iostream> #include <algorithm> #include <map> #include <set> using namespace std; int main() { int n, x, nr = 0; map<int, int> frecv; set<int> elements; cin >> n; for (int i = 0; i < n; ++i) { cin >> x; frecv[x]++; elements.insert(x); } for (auto& keyValuePair : frecv) { while (keyValuePair.second != 0) { --keyValuePair.second; auto current = keyValuePair.first; for (auto next = elements.upper_bound(current); next != elements.end(); next = elements.upper_bound(current)) { ++nr; current = *next; if (--frecv[current] == 0) { elements.erase(current); } } } } cout << nr; return 0; }<file_sep>// https://codeforces.com/contest/791/problem/B // https://codeforces.com/contest/791/submission/25625859 #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <map> #include <unordered_map> #include <set> #include <vector> #include <cstdio> #include <string> using namespace std; #define ll long long #define ull unsigned long long /*------------------------------------------------------------------*/ const int NMAX = 150006; int n, m; vector<int> graph[NMAX]; int vis[NMAX]; ll noduri, muchii; void dfs(int node) { vis[node] = 1; noduri++; for(auto g: graph[node]) { muchii++; if (vis[g] == 0) { dfs(g); } } } int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); int x, y; scanf("%d %d", &n, &m); for(int i = 0; i< m; ++i) { scanf("%d %d", &x, &y); graph[x].push_back(y); graph[y].push_back(x); } bool ok = true; for(int i = 1; i<=n; ++i) { if(vis[i] == 0) { noduri = muchii = 0; dfs(i); if (muchii != (noduri *(noduri - 1))) ok = false; } } (ok) ? cout << "YES\n" : cout << "NO\n"; return 0; }<file_sep>// https://codeforces.com/contest/741/problem/B // https://codeforces.com/contest/741/submission/23036476 #define _CRT_SECURE_NO_WARNINGS #include <vector> #include <stdio.h> #include <algorithm> using namespace std; typedef struct HOS { int beauty; int weight; HOS() { beauty = 0, weight = 0; } }HOS; int parent[1005], bestDP[1005], usedDP[1005]; HOS basics[1005]; HOS combs[1005]; vector<HOS> groupies[1005]; int find(int x) { return (x == parent[x]) ? x : parent[x] = (find(parent[x])); } int main() { int n, m, w; int x, y; int px, py; int ans = 0; HOS g; scanf("%d %d %d", &n, &m, &w); for (int i = 1; i <= n; ++i) { scanf("%d", &basics[i].weight); } for (int i = 1; i <= n; ++i) { scanf("%d", &basics[i].beauty); } for (int i = 1; i <= n; ++i) { parent[i] = i; combs[i] = basics[i]; } for (int i = 1; i <= m; ++i) { scanf("%d %d", &x, &y); px = find(x); py = find(y); if (px == py) continue; combs[px].beauty += combs[py].beauty; combs[px].weight += combs[py].weight; parent[py] = px; } for (int i = 1; i <= n; ++i) { if (i == find(i)) groupies[i].push_back(combs[i]); groupies[find(i)].push_back(basics[i]); } for (int i = 1; i <= n; ++i) { if (i != find(i)) continue; for (size_t p = 0; p < groupies[i].size(); ++p) { g = groupies[i][p]; for (int k = w; k > 0; --k) { if (k - g.weight >= 0) { bestDP[k] = max(bestDP[k], usedDP[k - g.weight] + g.beauty); ans = max(ans, bestDP[k]); } } } for (int i = 0; i <= w; ++i) usedDP[i] = bestDP[i]; } printf("%d", ans); return 0; } <file_sep>// https://codeforces.com/contest/330/problem/A // https://codeforces.com/contest/330/submission/14898824 #include <iostream> using namespace std; int main() { int n,m; bool lin[11],col[11]; for (int i = 1; i <= 10; i++) { lin[i] = true; col[i] = true; } cin>>n>>m; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { char x; cin>>x; if (x == 'S') { lin[i] = false; col[j] = false; } } } int nrcol = 0, nrlin = 0; for (int i = 1; i <= m; i++) { if (col[i]){nrcol++;} } for (int i = 1; i <= n; i++) { if (lin[i]){nrlin++;} } cout<<(nrcol*(n-nrlin) + (nrlin*m)); return 0; } <file_sep>// https://codeforces.com/contest/151/problem/A // https://codeforces.com/contest/151/submission/17418748 #include <iostream> using namespace std; #define MIN(a,b) (((a)<(b))?(a):(b)) int main() { int n, k, l, c, d, p, nl, np; cin >> n >> k >> l >> c >> d >> p >> nl >> np; cout << MIN(MIN(k*l / nl, c*d), p/np ) / n; return EXIT_SUCCESS; }<file_sep>// https://codeforces.com/contest/673/problem/A // https://codeforces.com/contest/673/submission/17928098 #include <iostream> using namespace std; int main() { int n, t1 = 0, t2, s = 0; bool ok = true; cin >> n; for (int i = 0; i < n && ok; i++) { cin >> t2; if (t2 - t1 <= 15) s = t2; else s += 15, ok = false; t1 = t2; } if (ok) s += 15; if (s > 90) s = 90; cout << s; return EXIT_SUCCESS; }<file_sep># https://codeforces.com/contest/592/problem/C # https://codeforces.com/contest/592/submission/47395386 def gcd(a,b): if b == 0: return a return gcd(b,a%b) def reduct(x,y): g = gcd(x,y) while g != 1: while x % g == 0 and y % g == 0: x = x // g y = y // g g =gcd(x,y) print(str(x) + "/" + str(y)) (t, w, b) = map(int,input().split()) rest = min(w,b) - 1 s = (w*b) // gcd(w,b) div = t // s mod = t % s ans = div + div * rest + min(mod,rest) reduct(ans,t) <file_sep># https://codeforces.com/contest/510/problem/A # https://codeforces.com/contest/510/submission/14007946 n,m=map(int,input().split()) ok=1 for i in range(1,n+1): for j in range(1,m+1): if (i%2==1): print('#',sep='',end='') elif j==m and ok==-1: print('#',sep='',end='') elif j==1 and ok==1: print('#',sep='',end='') else: print('.',sep='',end='') print() if i%2==1: ok=-ok <file_sep>// https://codeforces.com/contest/734/problem/D // https://codeforces.com/contest/734/submission/22308457 #include <iostream> #include <stdio.h> #include <algorithm> using namespace std; typedef struct _PIECE { unsigned long long dist; char c; }PIECE; inline bool diagonala(long long x, long long y, long long xr, long long yr) { return (abs(x - xr) == abs(y - yr)); } inline unsigned long long distance(long long x, long long y, long long xr, long long yr) { return (unsigned long long)((x - xr)*(x - xr) + (y - yr)*(y - yr)); } int main() { long long xr, yr, n, x, y; char c; PIECE v[10]; PIECE aux; unsigned long long dist; for (int i = 0; i < 10; ++i) v[i].c = '0', v[i].dist = -1; scanf("%lld %lld %lld", &n, &xr, &yr); while (n--) { getchar(); scanf("%c %lld %lld",&c, &x, &y); dist = distance(x, y, xr, yr); aux.c = c; aux.dist = dist; if (x == xr && y > yr && dist < v[1].dist) v[1] = aux; else if (x == xr && y < yr && dist < v[2].dist) v[2] = aux; else if (x > xr && y == yr && dist < v[3].dist) v[3] = aux; else if (x < xr && y == yr && dist < v[4].dist) v[4] = aux; else if (diagonala(x, y, xr, yr)) { if (x < xr && y > yr && dist < v[5].dist) v[5] = aux; else if (x > xr && y > yr && dist < v[6].dist) v[6] = aux; else if (x < xr && y < yr && dist < v[7].dist) v[7] = aux; else if (x > xr && y < yr && dist < v[8].dist) v[8] = aux; } } bool won = (v[1].c != 'Q' && v[1].c != 'R' && v[2].c != 'Q' && v[2].c != 'R' && v[3].c != 'Q' && v[3].c != 'R' && v[4].c != 'Q' && v[4].c != 'R' && v[5].c != 'Q' && v[5].c != 'B' && v[6].c != 'Q' && v[6].c != 'B' && v[7].c != 'Q' && v[7].c != 'B' && v[8].c != 'Q' && v[8].c != 'B'); (won) ? puts("NO") : puts("YES"); return 0; } #include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; struct my{ char tip; unsigned long long distanta; my(){ tip = '0'; distanta = -1; } }; inline bool diagonale(long long xP,long long yP,long long x,long long y){ return abs(xP - x) == abs(yP - y); } unsigned long long distanta(long long xP,long long yP,long long x,long long y){ return (unsigned long long)((xP - x)*(xP-x) + (yP - y)*(yP - y)); } int main() { my v[8]; long long i,n; long long xR,yR; scanf("%lld %lld %lld",&n,&xR,&yR); char pion; long long xPion,yPion; unsigned long long myDist; for(i=0;i<n;i++){ getchar(); scanf("%c %lld %lld",&pion,&xPion,&yPion); myDist = distanta(xPion,yPion,xR,yR); if(diagonale(xPion,yPion,xR,yR)){ if(xPion < xR && yPion > yR && v[1].distanta > myDist){ v[1].distanta = myDist; v[1].tip = pion; } else if(xPion > xR && yPion > yR && v[2].distanta > myDist){ v[2].distanta = myDist; v[2].tip = pion; } else if(xPion < xR && yPion < yR && v[4].distanta > myDist){ v[4].distanta = myDist; v[4].tip = pion; } else if(xPion > xR && yPion < yR &&v[5].distanta > myDist){ v[5].distanta = myDist; v[5].tip = pion; } } else if(yPion == yR){ if(xPion < xR && v[7].distanta > myDist){ v[7].distanta = myDist; v[7].tip = pion; } else if(xPion > xR && v[6].distanta > myDist){ v[6].distanta = myDist; v[6].tip = pion; } } else if(xPion == xR){ if(yPion > yR && v[0].distanta > myDist){ v[0].distanta = myDist; v[0].tip = pion; } else if( yPion < yR &&v[3].distanta > myDist){ v[3].distanta = myDist; v[3].tip = pion; } } } bool ESah = (v[0].tip == 'R' || v[0].tip == 'Q' || v[3].tip == 'R' || v[3].tip == 'Q' || v[6].tip == 'R' || v[6].tip == 'Q' || v[7].tip == 'R' || v[7].tip == 'Q' || v[1].tip == 'B' || v[1].tip == 'Q' || v[2].tip == 'B' || v[2].tip == 'Q' || v[4].tip == 'B' || v[4].tip == 'Q' || v[5].tip == 'B' || v[5].tip == 'Q' ); (ESah) ? puts("YES") : puts("NO"); return 0; }<file_sep># https://codeforces.com/contest/144/problem/A # https://codeforces.com/contest/144/submission/13589412 n=int(input()) l=list(map(int,input().split())) maxs=-1 mins=102 poz_min, poz_max = -1, -1 for i in range(len(l)): if maxs<l[i]: maxs=l[i] poz_max=i+1 if mins>=l[i]: mins=l[i] poz_min=i+1 if poz_max>poz_min: poz_max-=1 print(poz_max-1+len(l)-poz_min) <file_sep>// https://codeforces.com/contest/570/problem/B // https://codeforces.com/contest/570/submission/28728095 #include <iostream> using namespace std; int main() { int n, m; cin>>n>>m; if (n == 1){ cout<<"1"; return 0; } cout<<( ( m-1 >= n-m)?(m-1):(m+1)); return 0; } <file_sep>// https://codeforces.com/problemset/problem/1114/A // https://codeforces.com/contest/1114/submission/67692580 #include <iostream> #include <algorithm> using namespace std; bool SolveAndrew(int& Andrew, int& green) { if (green < Andrew) { return false; } green -= Andrew; return true; } bool SolveDimitry(int& Dimitry, int& green, int& purple) { if (green + purple < Dimitry) { return false; } if (green < Dimitry) { Dimitry -= green; green = 0; purple -= Dimitry; } else { green -= Dimitry; } return true; } bool SolveMichael(int& Michael, int& green, int& purple, int& black) { if (green + purple + black < Michael) { return false; } return true; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int Andrew, Dimitry, Michael; cin >> Andrew >> Dimitry >> Michael; int green, purple, black; cin >> green >> purple >> black; bool ok = SolveAndrew(Andrew, green) && SolveDimitry(Dimitry, green, purple) && SolveMichael(Michael, green, purple, black); (ok) ? cout << "YES\n" : cout << "NO\n"; return 0; }<file_sep>// https://codeforces.com/gym/101246/problem/B // https://codeforces.com/gym/101246/submission/25244690 #include <iostream> #include<fstream> #include<string> #define cin f #define cout g using namespace std; int mat[110][110]; int main() { ifstream f("input.txt"); ofstream g("output.txt"); int n, m; f>>n>>m; string s; for(int i=1; i<=n; i++) { f>>s; for(int j=1; j<=m; j++) mat[i][j] =(s[j-1]-'0') ; } int sol=0; for(int i=1; i<=n; i++) { for(int j=1; j<=m; j++) { if(mat[i][j]!=0)sol+=2; sol+= (max(0, mat[i][j]-mat[i-1][j])+ max(0, mat[i][j]-mat[i+1][j])+ max(0, mat[i][j]-mat[i][j-1])+ max(0, mat[i][j]-mat[i][j+1])); } } g<<sol<<endl; f.close(); g.close(); return 0; }<file_sep># https://codeforces.com/contest/630/problem/C # https://codeforces.com/contest/630/submission/17323650 n = int(input()) print(2*(1<<n)-2) <file_sep># https://codeforces.com/contest/318/problem/A # https://codeforces.com/contest/318/submission/14008127 n,m=map(int,input().split()) if n%2==0: k=int(n/2) else: k=int(n/2+1) if k<m: print((m-k)*2) else: print(2*m-1) <file_sep># https://codeforces.com/contest/492/problem/B # https://codeforces.com/contest/492/submission/14414432 n,m = map(int,input().split()) v = list(map(float,input().split())) v = sorted(v) if v[0]!=0: maxs = v[0] indice = 2 else: maxs = -1 indice = 1 if v[n-1]!=m: if m-v[n-1]>maxs: maxs=m-v[n-1] while indice <= n-1: if (v[indice]-v[indice-1])/2>maxs: maxs=(v[indice]-v[indice-1])/2 indice+=1 print("%.10f" %maxs)
5608723d4679080cf88d7ed25b10224e508e99a2
[ "Python", "C++" ]
429
C++
AndreiMuntea/Contests
f76b00d36ce737a1921bdca946bc30eb476dca14
1a32e01f4ea19055529cb8206faed26381ef00b8
refs/heads/master
<repo_name>priyanshujain/STARTX2016<file_sep>/SRTX16E.cpp /* Author - <NAME> */ //#include <atomic> #include <cstdio> #include <cmath> #include <cstdlib> #include <iostream> #include <iomanip> #include <fstream> #include <vector> #include <string> #include <map> #include <algorithm> #include <cassert> using namespace std; #define mod 1000000007 #define inf 100000000000000000LL struct _{ios_base::Init i; _(){ cin.sync_with_stdio(0); cin.tie(0);cout.tie(0); }}_ ; typedef long long int ll; #define pll pair<ll,ll> #define ict int t;cin>>t;while(t--) #define rep(i,n) for(ll i=0;i<n;i++) #define repi(i,a,b) for(ll i=a;i<=b;i++) #define endl '\n' const int N = 2001; int m, n; double dp[N][N]; int main() { std::ifstream in("small.in"); std::streambuf *cinbuf = std::cin.rdbuf(); //save old buf std::cin.rdbuf(in.rdbuf()); //redirect std::cin to in.txt! std::ofstream out("small.out"); std::streambuf *coutbuf = std::cout.rdbuf(); //save old buf std::cout.rdbuf(out.rdbuf()); //redirect std::cout to out.txt! for (int i = 1; i < N; i++) dp[i][0] = 1; for (int i = 1; i < N; i++) { for (int j = 1; j < N; j++) { if (i > j) { double p1 = (double)i / (i + j); double p2 = 1 - p1; dp[i][j] = dp[i-1][j] * p1 + dp[i][j-1] * p2; } } } int t, tt; cin>>t; for (int tt = 1; tt <= t; tt++) { cin>>n>>m; std::cout.setf(std::ios::fixed, std::ios::floatfield); cout<<std::setprecision(6); cout<<dp[n][m]<<endl; } return 0; } <file_sep>/SRTX16A.cpp /* Author - <NAME> */ //#include <atomic> #include <cstdio> #include <cmath> #include <cstdlib> #include <iostream> #include <fstream> #include <vector> #include <string> #include <map> #include <algorithm> #include <cassert> using namespace std; #define REP(i,n) for (int i = 1; i <= n; i++) typedef long long ll; int main() { std::ifstream in("in.txt"); std::streambuf *cinbuf = std::cin.rdbuf(); //save old buf std::cin.rdbuf(in.rdbuf()); //redirect std::cin to in.txt! std::ofstream out("out.txt"); std::streambuf *coutbuf = std::cout.rdbuf(); //save old buf std::cout.rdbuf(out.rdbuf()); //redirect std::cout to out.txt! int t; cin>>t; for (size_t i = 0; i < t; i++) { int N,M; cin>>N>>M; cout<<N%M<<endl; } return 0; } <file_sep>/SRTX16C.cpp #include<algorithm> #include<iostream> #include<fstream> #include<cmath> using namespace std; int main() { std::ifstream in("in.txt"); std::streambuf *cinbuf = std::cin.rdbuf(); //save old buf std::cin.rdbuf(in.rdbuf()); //redirect std::cin to in.txt! std::ofstream out("out.txt"); std::streambuf *coutbuf = std::cout.rdbuf(); //save old buf std::cout.rdbuf(out.rdbuf()); //redirect std::cout to out.txt! int test,n; cin>>test; while(test--) { cin>>n; int a[n+3]; for(int i=0;i<n;i++)cin>>a[i]; a[n] = a[n+1] = a[n+2] = 1; int oneStreak = 0, current = 0, jumps = 0; bool flag = true; while(current != n-1) { if(a[current + 3] == 0) { current += 3; jumps++; } else if(a[current + 2] == 0) { current += 2; jumps++; } else if(a[current + 1] == 0) { current += 1; jumps++; } else { flag = false; break; } } if(flag) cout<<jumps<<"\n"; else cout<<"Never Give Up\n"; } } <file_sep>/SRTX16D.cpp /* ** Author - <NAME> (easy_) */ #include<iostream> #define MAX 105 #define ll int using namespace std; ll n, m, xe, ye, xi, yi, xw, yw; bool cave[MAX][MAX]; void flood(ll matrix[MAX][MAX], ll x, ll y, ll xe, ll ye, ll n) { if(!cave[x][y]) //if it's a wall return; if(matrix[x][y] == 0 || matrix[x][y] > n) { matrix[x][y] = n; if(x == xe && y == ye) { return; //no need to flood more } else { n++; flood(matrix, x+1, y, xe, ye, n); flood(matrix, x-1, y, xe, ye, n); flood(matrix, x, y+1, xe, ye, n); flood(matrix, x, y-1, xe, ye, n); } } } ll floodWater() { ll mat[MAX][MAX] = {0}; flood(mat, xw, yw, xe, ye, 1); /* cout<<"WATER FLOODED\n"; for(int i = 0; i < n+2; i++) { for(int j = 0; j < m+2; j++) { if(mat[i][j] == -1) cout<<"x "; else cout<<mat[i][j]<<" "; } cout<<"\n"; }*/ return mat[xe][ye]; } ll runSam() { ll mat[MAX][MAX] = {0}; flood(mat, xi, yi, xe, ye, 1); /* cout<<"SAM FLOODED\n"; for(int i = 0; i < n+2; i++) { for(int j = 0; j < m+2; j++) { if(mat[i][j] == -1) cout<<"x "; else cout<<mat[i][j]<<" "; } cout<<"\n"; }*/ return mat[xe][ye]; } int main() { ll cases; char c; cin>>cases; while(cases--) { cin>>n>>m>>xe>>ye>>xi>>yi>>xw>>yw; for(ll i = 1; i <= n ; i++) { for(ll j = 1; j <= m; j++) { cin>>c; //true if path, false if wall if(c == '0') cave[i][j] = true; else cave[i][j] = false; } } for(ll i = 0; i < n+2; i++) { cave[i][0] = false; cave[i][m+1] = false; } for(ll i = 0; i < m+2; i++) { cave[0][i] = false; cave[n+1][i] = false; } /* cout<<"CAVE\n"; for(ll i = 0; i <= n+1 ; i++) { for(ll j = 0; j <= m+1; j++) { cout<<(cave[i][j]?"_":"x")<<" "; } cout<<endl; }*/ ll w = floodWater(); ll s = runSam(); if(s <= w || w == 0) cout<<s-1<<"\n"; else cout<<"-1\n"; } return 0; }
81b7d62620ce539eac0cbb2ae9cb912b87effd98
[ "C++" ]
4
C++
priyanshujain/STARTX2016
529843216100c5a652d294156f553239735b7358
4388bc4ffe9357b4af94cef43f29cde76f0913e5
refs/heads/master
<repo_name>zaritskiy/shop<file_sep>/main.js var http = require('http'); var express = require ("express"); var bodyParser = require ("body-parser"); var fs = require('fs'); var sticker = JSON.parse(fs.readFileSync('./sticker.json')); // console.log(sticker); var app = express(); app.use(express.static(__dirname + '/public')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); app.get('/goods', function (req, res) { res.header('Content-Type', 'aplication/json'); res.send(sticker); }); app.get('/oneGoods', function (req, res) { for(var i = 0; i < sticker.length; i++){ if(sticker[i].id == req.query.id){ res.header('Content-Type', 'aplication/json'); res.send(sticker[i]); } } }); app.listen(8888); // var express = require('express'); // var bodyParser = require('body-parser'); // var app = express(); // // var bands = [{name: '<NAME>'}]; // // app.use(express.static(__dirname + '/public')); // app.use(bodyParser.json()); // app.use(bodyParser.urlencoded({extended: true})); // // console.log('+++'); // // app.get('/getGroup', function (req, res) { // res.header('Content-Type', 'aplication/json'); // res.send(bands); // }); // app.post('/setGroup', function (req, res) { // bands.push(req.body); // res.send(ok) // }); // // // app.get('/id', function (req, res) { // setTimeout(function () { // res.header('Content-Type', 'aplication/json'); // res.send([{singer: 'Matrix', name: 'Big city life'}]); // }, 100); // // }); // // app.post('/sayme', function (req, res) { // // console.log(req.body); // // }); // app.post('/setGroups', function (res, req) { // req.header('Content-Type', 'aplication/json'); // console.log(req.body); // req.send(bands); // }); // // app.listen(8888); // // // var server = require('./server'); // // var http = require("http"); // // http.createServer(server.server).listen(8888); // // // // var express = require('express'); // // var app = express(); // // app.use(express.static(__dirname + '/public')); // // app.get('/id', function (req, res) { // // setTimeout(function () { // // res.header('Content-Type', 'aplication/json'); // // res.send([{singer: 'Matrix', name: '<NAME>'}]); // // }, 3000); // // }); // // app.listen(8888);<file_sep>/public/test/pages/feedback/test.js var clearAfterTest = function () { $('#wrapper').remove() }; QUnit.module('Проверка добавения содержимого на страницу '); QUnit.test("wrapper", function (assert) { assert.ok(document.querySelector('#wrapper'), "Содержимое добавленно"); clearAfterTest(); }); var prepareForTest = function () { $("header").append( "<div class='navbar navbar-inverse navbar-fixed-top'>" + "<div class='container'>" + "<div class='navbar-header'>" + "<button type='button' class='navbar-toggle collapsed' data-toggle='collapse' data-target='#bs-example-navbar-collapse-1' aria-expanded='false'>" + "<span class='icon-bar'></span>"+ "<span class='icon-bar'></span>"+ "<span class='icon-bar'></span>"+ "</button>"+ "<a class='navbar-brand' href='index.html'>STICKER</a>"+ "</div>"+ "<div class='collapse navbar-collapse ' id='bs-example-navbar-collapse-1'>"+ "<ul class='nav navbar-nav navbar-right'>"+ "<li class='active'><a href='index.html'>Домой</a></li>" + "<li><a href='pages/about/about.html'>О нас</a></li>" + "<li class='contact'><a href='pages/feedback/feedback.html'>Контакти</a></li>" + "<li><a href='pages/response/response.html'>Отзывы</a></li>"+ "<li><a href='pages/delivery/delivery.html'>Доставка</a></li>"+ "<li class='top-cart'><a href='pages/cart/cart.html'> Корзина <span id='m-cart'></span></a></li>"+ "</ul>" + "</div>"+ "</div>"+ "</div>"+ "<div id='headerwrap'>"+ "<div class='container'>"+ "<div class='row centered'>"+ "<div class='col-lg-8 col-lg-offset-2'>"+ "</div>"+ "</div>"+ "</div>"+ "</div>"); }; QUnit.module('Проверка добавения содержимого header '); QUnit.test("header", function (assert) { prepareForTest(); assert.ok(document.getElementsByTagName('header'), "Содержимое header добавленно "); clearAfterTest(); // prepareForTest(); assert.ok($('.navbar-brand'), "Силка на лого добавлена"); clearAfterTest(); // prepareForTest(); assert.ok($('.active'), "Силка на главную страницу добавлена"); clearAfterTest(); // prepareForTest(); assert.ok($('#m-cart'), "мини-корзина на страницу добавлена"); clearAfterTest(); }); var prepareForTest1 = function () { $(".info").append( "<div class='container'>" + "<div class='col-lg-12'>" + "<p><span><strong>" + "Звоните по номерам</strong></span></p>" + "<p></p><p><span>067 322-21-23 или</span><span> 067 373-87-52</span></p><p>" + "<span>Время работы: 10:00 - 19:00</span></p>" + "<p></p><p><span>Ожидаем вас по адресу:<strong> г. Киев, <NAME> 17</strong></span>" + "</p></div></div>"); }; QUnit.module('Проверка добавения содержимого info '); QUnit.test("контакти", function (assert) { prepareForTest1(); assert.ok($('.info'), "Содержимое info добавленно "); clearAfterTest(); // }); var prepareForTest4 = function () { $('footer').append( "<div id='f'>"+ "<div class='container'>"+ "<div class='row centered'>"+ "<a href='https://twitter.com'><img src='images/t.png' alt='twitter'></a>"+ "<a href='https://www.facebook.com'><img src='images/f.png' alt='facebook'></a>"+ "<a href='https://vk.com'><img src='images/B.png' alt='vk'></a>"+ "</div>"+ "</div>"+ "</div>" ); }; QUnit.module('Проверка добавения содержимого футера '); QUnit.test("футер", function (assert) { prepareForTest4(); assert.ok($('footer'), "Содержимое footer добавленно "); clearAfterTest(); // prepareForTest4(); assert.ok($('image'), "добавленно картинки"); clearAfterTest(); }); <file_sep>/public/test/test.js // var culcPer = function (a, b, c) { // if(a < 0 && b < 0 && c < 0)throw 'error'; // if(a < 0 || b < 0 || c < 0)return 0; // return +a + +b + +c; // }; // // QUnit.module('наш первий модуль'); // QUnit.test("Считаем периметр триугольника вызовом функции culcPer", function (assert) { // assert.equal( culcPer(4,5,6), 15, "ноль равен нулю если есть числа"); // assert.equal( culcPer('4',5,6), 15, "ноль равен нулю если есть 1 строка"); // assert.notOk( culcPer(-1,0,3), "если хоть 1 отрицательная сторона то периметр 0"); // try { // culcPer(-1, -3, -4); // assert.ok(false, 'gg') // }catch (ex){ // assert.ok(true, 'gg') // } // // }); var prepareForTest = function () { var obj = {}; obj.__proto__ = buttonContainer; obj.addButton(); }; var clearAfterTest = function () { $('.btn').remove() }; var redButton = function () { $('button').css("color", "rgb(255, 0, 0)"); }; QUnit.module('Проверка добавения на страницу'); QUnit.test("Кнопка", function (assert) { prepareForTest(2); assert.ok(document.querySelector('.btn'), "Кнопка с классом btn добавленна"); clearAfterTest(); // prepareForTest('drgdr'); redButton(); assert.equal($('button').css('color'), 'rgb(255, 0, 0)' , "Кнопка красная"); clearAfterTest(); }); <file_sep>/public/src/index.js var cart = {}; $.ajax({ dataType: 'json', type: 'GET', url: '/goods', success: function (data) { var out = ''; for (var key in data) { out += '<div class="single-goods">'; out += '<img src="' + data[key].image + '">'; out += '<h4>' + data[key]['name'] + '</h4>'; out += '<p>Цена: ' + data[key]['price'] + ' грн.</p>'; out += '<button class="add-to-cart" data-art="' + key + '">Купить</button>'; out += '</div>'; } $('#allGoods').html(out); // $('button.add-to-cart').on('click', addToCart()); $('button.add-to-cart').click(function () { var id = $(this).attr('data-art'); window.location.href = "../goods/oneGoods.html?id=" + id; }); } }); function addToCart() { //добавляем товар в корзину var articul = $(this).attr('data-art'); if (cart[articul]!=undefined) { cart[articul]++; } else { cart[articul] = 1; } localStorage.setItem('cart', JSON.stringify(cart) ); //console.log(cart); showMiniCart(); } function checkCart(){ //проверяю наличие корзины в localStorage; if ( localStorage.getItem('cart') != null) { cart = JSON.parse (localStorage.getItem('cart')); } } checkCart(); function showMiniCart(){ //показываю содержимое корзины var a = 0; for (var key in cart) { a += cart[key]; } $(".top-cart span").html(a); }<file_sep>/public/test/pages/goods/laptop/test.js var clearAfterTest = function () { $('#wrapper').remove() }; QUnit.module('Проверка добавения содержимого на страницу '); QUnit.test("wrapper", function (assert) { assert.ok(document.querySelector('#wrapper'), "Содержимое добавленно"); clearAfterTest(); }); var prepareForTest = function () { $("header").append( "<div class='navbar navbar-inverse navbar-fixed-top'>" + "<div class='container'>" + "<div class='navbar-header'>" + "<button type='button' class='navbar-toggle collapsed' data-toggle='collapse' data-target='#bs-example-navbar-collapse-1' aria-expanded='false'>" + "<span class='icon-bar'></span>"+ "<span class='icon-bar'></span>"+ "<span class='icon-bar'></span>"+ "</button>"+ "<a class='navbar-brand' href='index.html'>STICKER</a>"+ "</div>"+ "<div class='collapse navbar-collapse ' id='bs-example-navbar-collapse-1'>"+ "<ul class='nav navbar-nav navbar-right'>"+ "<li class='active'><a href='index.html'>Домой</a></li>" + "<li><a href='pages/about/about.html'>О нас</a></li>" + "<li class='contact'><a href='pages/feedback/feedback.html'>Контакти</a></li>" + "<li><a href='pages/response/response.html'>Отзывы</a></li>"+ "<li><a href='pages/delivery/delivery.html'>Доставка</a></li>"+ "<li class='top-cart'><a href='pages/cart/cart.html'> Корзина <span id='m-cart'></span></a></li>"+ "</ul>" + "</div>"+ "</div>"+ "</div>"+ "<div id='headerwrap'>"+ "<div class='container'>"+ "<div class='row centered'>"+ "<div class='col-lg-8 col-lg-offset-2'>"+ "</div>"+ "</div>"+ "</div>"+ "</div>"); }; QUnit.module('Проверка добавения содержимого header '); QUnit.test("header", function (assert) { prepareForTest(); assert.ok(document.getElementsByTagName('header'), "Содержимое header добавленно "); clearAfterTest(); // prepareForTest(); assert.ok($('.navbar-brand'), "Силка на лого добавлена"); clearAfterTest(); // prepareForTest(); assert.ok($('.active'), "Силка на главную страницу добавлена"); clearAfterTest(); // prepareForTest(); assert.ok($('#m-cart'), "мини-корзина на страницу добавлена"); clearAfterTest(); }); var prepareForTest1 = function () { $(".info").append( "<div class='container'>" + "<div class='col-lg-12'>" + "<div id='allGoods'></div>"+ "</div>" + "</div>" + "</div>"); }; QUnit.module('Проверка добавения содержимого info '); QUnit.test("товари", function (assert) { prepareForTest1(); assert.ok($('.info'), "Содержимое info добавленно "); clearAfterTest(); // }); var prepareForTest2 = function () { $(".wrap").append( "<div class='row centered'>" + "<br><br>"+ "<div class='col-lg-4'>" + "<h4><a href='pages/goods/scuter.html'>Стикеры на скутер</a></h4>"+ "<p> Наклейки на скутера – вот реальная тема. Да-да, можно и позером заделаться, а можно и по теме. Как заклеить мопед – личное дело райдера. Так что, сделать няшного дырчика или хмурого воина улиц – решать тебе.</p>"+ "</div>"+ "<div class='col-lg-4'>" + "<h4><a href='pages/goods/laptop.html'>Стикеры на ноутбук</a></h4>"+ "<p>Наклейки для ноутбука скроют морщины царапины и потертости, если таковые уже имеются. В добавок они защитят лэптоп от твоих дальнейших шаловливых манипуляций, способных повредить нежную кожицу крышки. Знай, что наклейка на ноутбук добавит +10 к стилю по шкале крутости.</p>"+ "</div>"+ "<div class='col-lg-4'>" + "<h4><a href='pages/goods/goods.html'>Стикеры на авто</a></h4>"+ "<p>Виниловые наклейки на авто, своим появлением обязаны идейному движению токийских дрифтеров, которое смело можно считать отцом JDM бума. Дрифтинг – особая разновидность гонок, где при повороте пилот намеренно производит максимальный занос.</p>"+ "</div>"+ "</div>"+ "<br><br>" ); }; var text = function () { $('p').css("color", "rgb(128, 128, 128)"); }; QUnit.module('Проверка добавения содержимого wrap '); QUnit.test("Основная часть страници", function (assert) { prepareForTest2(); assert.ok($('.wrap'), "Содержимое wrap добавленно "); clearAfterTest(); prepareForTest2(); assert.ok($('h4'), "заголовки добавленно "); clearAfterTest(); // prepareForTest2(); assert.ok($('p'), "text добавленно "); clearAfterTest(); // prepareForTest2(); text(); assert.equal($('p').css('color'), 'rgb(128, 128, 128)' , "текст серий"); clearAfterTest(); // }); var prepareForTest3 = function () { $('#dg').append( "<div class='container'>" + "<div class='row centered'>" + "<h4>Последние работы</h4>" + "<br>" + "<div class='col-lg-4'>" + "<div class='tilt'>" + "<a href='#'><img src='images/1.png' alt=''></a>" + "</div>" + "</div>" + "<div class='col-lg-4'>" + "<div class='tilt'>" + "<a href='#'><img src='images/2.png' alt=''></a>" + "</div>" + "</div>" + "<div class='col-lg-4'>" + "<div class='tilt'>" + "<a href='#'><img src='images/3.png' alt=''></a>" + "</div>" + "</div>" + "</div>" + "</div>"); }; QUnit.module('Проверка добавения содержимого #dg '); QUnit.test("Основная часть страници - низ", function (assert) { prepareForTest3(); assert.ok($('#dg'), "Содержимое #dg добавленно "); clearAfterTest(); prepareForTest3(); assert.ok($('h4'), "заголовок добавленно"); clearAfterTest(); // prepareForTest3(); assert.ok($('p'), "text добавленно"); clearAfterTest(); // prepareForTest3(); text(); assert.equal($('p').css('color'), 'rgb(128, 128, 128)' , "текст серий"); clearAfterTest(); // prepareForTest3(); assert.ok($('image'), "добавленно картинки"); clearAfterTest(); }); var prepareForTest4 = function () { $('footer').append( "<div id='f'>"+ "<div class='container'>"+ "<div class='row centered'>"+ "<a href='https://twitter.com'><img src='images/t.png' alt='twitter'></a>"+ "<a href='https://www.facebook.com'><img src='images/f.png' alt='facebook'></a>"+ "<a href='https://vk.com'><img src='images/B.png' alt='vk'></a>"+ "</div>"+ "</div>"+ "</div>" ); }; QUnit.module('Проверка добавения содержимого футера '); QUnit.test("футер", function (assert) { prepareForTest4(); assert.ok($('footer'), "Содержимое footer добавленно "); clearAfterTest(); // prepareForTest4(); assert.ok($('image'), "добавленно картинки"); clearAfterTest(); }); <file_sep>/public/test/pages/response/test.js var clearAfterTest = function () { $('#wrapper').remove() }; QUnit.module('Проверка добавения содержимого на страницу '); QUnit.test("wrapper", function (assert) { assert.ok(document.querySelector('#wrapper'), "Содержимое добавленно"); clearAfterTest(); }); var text = function () { $('p').css("color", "rgb(128, 128, 128)"); }; var prepareForTest = function () { $("header").append( "<div class='navbar navbar-inverse navbar-fixed-top'>" + "<div class='container'>" + "<div class='navbar-header'>" + "<button type='button' class='navbar-toggle collapsed' data-toggle='collapse' data-target='#bs-example-navbar-collapse-1' aria-expanded='false'>" + "<span class='icon-bar'></span>"+ "<span class='icon-bar'></span>"+ "<span class='icon-bar'></span>"+ "</button>"+ "<a class='navbar-brand' href='index.html'>STICKER</a>"+ "</div>"+ "<div class='collapse navbar-collapse ' id='bs-example-navbar-collapse-1'>"+ "<ul class='nav navbar-nav navbar-right'>"+ "<li class='active'><a href='index.html'>Домой</a></li>" + "<li><a href='pages/about/about.html'>О нас</a></li>" + "<li class='contact'><a href='pages/feedback/feedback.html'>Контакти</a></li>" + "<li><a href='pages/response/response.html'>Отзывы</a></li>"+ "<li><a href='pages/delivery/delivery.html'>Доставка</a></li>"+ "<li class='top-cart'><a href='pages/cart/cart.html'> Корзина <span id='m-cart'></span></a></li>"+ "</ul>" + "</div>"+ "</div>"+ "</div>"+ "<div id='headerwrap'>"+ "<div class='container'>"+ "<div class='row centered'>"+ "<div class='col-lg-8 col-lg-offset-2'>"+ "</div>"+ "</div>"+ "</div>"+ "</div>"); }; QUnit.module('Проверка добавения содержимого header '); QUnit.test("header", function (assert) { prepareForTest(); assert.ok(document.getElementsByTagName('header'), "Содержимое header добавленно "); clearAfterTest(); // prepareForTest(); assert.ok($('.navbar-brand'), "Силка на лого добавлена"); clearAfterTest(); // prepareForTest(); assert.ok($('.active'), "Силка на главную страницу добавлена"); clearAfterTest(); // prepareForTest(); assert.ok($('#m-cart'), "мини-корзина на страницу добавлена"); clearAfterTest(); }); var prepareForTest1 = function () { $(".info").append( "<div class='container'>" + "<div class='col-lg-12'>" + "<div id='response'>"+ "<form>"+ "<h3>Оставить отзыв:</h3><br>"+ "<label>Фамилия:</label><br>"+ "<input class='form-control' type='text' placeholder='Иванов' required><br>"+ "<label>Имя:</label><br>"+ "<input class='form-control' type='text' placeholder='Иван' required><br>"+ "<label>Ваш e-mail:</label><br>"+ "<input class='form-control' type='email' placeholder='<EMAIL>' required><br>"+ "<label>Отзыв:</label><br>"+ "<textarea class='form-control' rows='6' placeholder='' required></textarea><br>"+ "<button class='add-to-card btn btn-default btn-lg' type='submit' title='Отправить отзыв'>Отправить отзыв</button>"+ "</form>"+ "</div>" + "</div>" + "</div>"); }; QUnit.module('Проверка добавения содержимого info '); QUnit.test("Отзиви", function (assert) { prepareForTest1(); assert.ok($('.info'), "Содержимое info добавленно "); clearAfterTest(); // }); var prepareForTest3 = function () { $('#dg').append( "<div class='container'>" + "<div class='row centered'>" + "<h4>Последние работы</h4>" + "<br>" + "<div class='col-lg-4'>" + "<div class='tilt'>" + "<a href='#'><img src='images/1.png' alt=''></a>" + "</div>" + "</div>" + "<div class='col-lg-4'>" + "<div class='tilt'>" + "<a href='#'><img src='images/2.png' alt=''></a>" + "</div>" + "</div>" + "<div class='col-lg-4'>" + "<div class='tilt'>" + "<a href='#'><img src='images/3.png' alt=''></a>" + "</div>" + "</div>" + "</div>" + "</div>"); }; QUnit.module('Проверка добавения содержимого #dg '); QUnit.test("Основная часть страници - низ", function (assert) { prepareForTest3(); assert.ok($('#dg'), "Содержимое #dg добавленно "); clearAfterTest(); prepareForTest3(); assert.ok($('h4'), "заголовок добавленно"); clearAfterTest(); // prepareForTest3(); assert.ok($('p'), "text добавленно"); clearAfterTest(); // prepareForTest3(); text(); assert.equal($('p').css('color'), 'rgb(128, 128, 128)' , "текст серий"); clearAfterTest(); // prepareForTest3(); assert.ok($('image'), "добавленно картинки"); clearAfterTest(); }); var prepareForTest4 = function () { $('footer').append( "<div id='f'>"+ "<div class='container'>"+ "<div class='row centered'>"+ "<a href='https://twitter.com'><img src='images/t.png' alt='twitter'></a>"+ "<a href='https://www.facebook.com'><img src='images/f.png' alt='facebook'></a>"+ "<a href='https://vk.com'><img src='images/B.png' alt='vk'></a>"+ "</div>"+ "</div>"+ "</div>" ); }; QUnit.module('Проверка добавения содержимого футера '); QUnit.test("футер", function (assert) { prepareForTest4(); assert.ok($('footer'), "Содержимое footer добавленно "); clearAfterTest(); // prepareForTest4(); assert.ok($('image'), "добавленно картинки"); clearAfterTest(); }); <file_sep>/public/pages/cart/cart.js $("body").append("<div id='wrapper'> "+ "<header></header>" + "<div class='info'></div>" + "<div class='container wrap'></div>" + "<div id=dg></div>" + "<footer></footer>"+ "</div>" ); $("header").append( "<div class='navbar navbar-inverse navbar-fixed-top'>" + "<div class='container'>" + "<div class='navbar-header'>" + "<button type='button' class='navbar-toggle' data-toggle='collapse' data-target='.navbar-collapse'>" + "<span class='icon-bar'></span>"+ "<span class='icon-bar'></span>"+ "<span class='icon-bar'></span>"+ "</button>"+ "<a class='navbar-brand' href='../../index.html'>STICKER</a>"+ "</div>"+ "<div class='navbar-collapse collapse'>"+ "<ul class='nav navbar-nav navbar-right'>"+ "<li><a href='../../index.html'>Домой</a></li>" + "<li><a href='../about/about.html'>О нас</a></li>" + "<li><a href='../feedback/feedback.html'>Контакти</a></li>" + "<li><a href='../response/response.html'>Отзывы</a></li>"+ "<li><a href='../delivery/delivery.html'>Доставка</a></li>"+ "<li><a href='cart.html'> Корзина </a></li>"+ "</ul>" + "</div>"+ "</div>"+ "</div>"+ "<div id='headerwrap'>"+ "<div class='container'>"+ "<div class='row centered'>"+ "<div class='col-lg-8 col-lg-offset-2'>"+ "</div>"+ "</div>"+ "</div>"+ "</div>"); $(".info").append( "<div class='container'>" + "<div class='row'>" + "<div class='col-lg-12'>" + "<div id='my-cart'></div>" + "<div id='zakaz'><button class='checkout'>Оформити заказ</button></div>" + "</div>" + "</div>" + "</div>"); $('footer').append( "<div id='f'>"+ "<div class='container'>"+ "<div class='row centered'>"+ "<a href='https://twitter.com'><img src='../../images/t.png' alt='twitter'></a>"+ "<a href='https://www.facebook.com'><img src='../../images/f.png' alt='facebook'></a>"+ "<a href='https://vk.com'><img src='../../images/B.png' alt='vk'></a>"+ "</div>"+ "</div>"+ "</div>" );
36d10ea645250ff4392d599eb83e5860c0181ab6
[ "JavaScript" ]
7
JavaScript
zaritskiy/shop
ff17c981c5057cfb9c83232bc6630a22e2667880
8a8c917b230781e21a4045d6b9d0198aa121f62e
refs/heads/master
<file_sep>#include "allocator.hpp" #include <cstdlib> #include <cassert> #include "utils.hpp" void* detail::allocate_aligned_memory(size_t align, size_t size) { assert(align >= sizeof(void*)); assert(is_power_of_two(align)); if (size == 0) { return nullptr; } void* ptr = nullptr; int rc = posix_memalign(&ptr, align, size); if (rc != 0) { return nullptr; } return ptr; } void detail::deallocate_aligned_memory(void *ptr) noexcept { return free(ptr); } <file_sep> add_library(skip_list allocator.cpp allocator.hpp skip_list.hpp utils.hpp ) target_include_directories(skip_list INTERFACE .) <file_sep>cmake_minimum_required(VERSION 3.6) project(skip_list) set(CMAKE_CXX_STANDARD 14) enable_testing() include(gtest.cmake) add_subdirectory(src) add_subdirectory(test) <file_sep>#pragma once #include <cstdint> #include <cstring> #include <cassert> #include <climits> #include <cmath> #include <vector> #include <utility> #include <random> #include <string> #include <array> #include <algorithm> #include <iterator> #include <unordered_set> #include "utils.hpp" #include "allocator.hpp" template<typename key_type, typename value_type, size_t N = (64 - sizeof(key_type) - sizeof(value_type)) / sizeof(void*) > struct skip_list { public: using side_t = uint8_t; constexpr static bool use_uniform_dist = false; constexpr static bool use_log_dist = false; constexpr static bool use_sqrt_dist = false; constexpr static bool use_rev_sqrt_dist = false; constexpr static bool use_rev_log_dist = true; constexpr static bool allow_duplicates = false; protected: static bool eq(key_type a, key_type b) { return a==b; } bool lt(key_type a, key_type b) const { return sd_?(b<a):(a<b); } bool gt(key_type a, key_type b) const { return sd_?(a<b):(b<a); } bool ge(key_type a, key_type b) const { return gt(a,b) || eq(a,b); } struct elem { constexpr static size_t align = 64; key_type key; value_type value; std::array<elem*, N> forwards { nullptr }; elem(key_type k, value_type v) : key(k), value(v), forwards({}) {} elem(key_type k, value_type v, std::array<elem*, N> const & a) : key(k), value(v), forwards(a) {} static void set_forwards(std::array<elem*, N> & forwards, size_t a, size_t b, elem * p) { for(size_t i = a; i < b; ++i) { forwards[i] = p; } } void set_forwards(size_t a, size_t b, elem * p) { set_forwards(forwards, a, b, p); } static std::string distance_between(elem const * p, elem const * o) { if ( !p ) return "."; if ( !o ) return "-"; int r = 0; for(; p != o; p = p->forwards[0], ++r); return std::to_string(r); } template<typename ostream> static ostream & dump_distances(ostream & o, elem const * p, std::array<elem *,N> const & f) { char const * sep = "["; for(auto & e : f) { o << sep << distance_between(p, e) << " (" << e << ")"; sep = ", "; } o << "]"; return o; } template<typename ostream> ostream & dump(ostream & o) const { return dump_distances( o << "[" << (void*)this << ": " << key << " -> " << value << " ", this, forwards ) << "]"; } }; static_assert( sizeof(elem) == 64, "elem is expected to fit into a cache line" ); side_t sd_; size_t size_ = 0; elem * head_ = nullptr; using allocator_type = aligned_allocator< elem, elem::align >; public: skip_list(side_t sd) : sd_(sd) {} ~skip_list() { clear(); } bool empty() const { return head_ == nullptr; } size_t size() const { return size_; } void clear() { elem * p = head_; while( p ) { elem * n = p->forwards[0]; allocator_type::destroy(p); allocator_type::deallocate(p,1); p = n; } size_ = 0; } size_t count() const { size_t r = 0; for(elem const * p = head_; p; p = p->forwards[0], ++r); return r; } std::vector< std::pair<key_type, value_type> > to_vector() const { std::vector< std::pair<key_type, value_type> > r; r.reserve( size_ ); for(elem const * p = head_; p; p = p->forwards[0]) { r.push_back( std::make_pair(p->key, p->value) ); } return r; } value_type * find(key_type k) const { if ( elem * p = head_ ) { if( eq( p->key, k ) ) return &(p->value); for(size_t lvl = N; lvl > 0;) { --lvl; while( p->forwards[lvl] && lt( p->forwards[lvl]->key, k) ) { p = p->forwards[lvl]; } assert( p->forwards[lvl] == nullptr || ge( p->forwards[lvl]->key, k) ); } if ( p->forwards[0] ) { return ( eq( p->forwards[0]->key, k ) ? &(p->forwards[0]->value) : nullptr ); } } return nullptr; } bool contains(key_type k) const { return find(k) != nullptr; } template<typename ostream> ostream & dump(ostream & o, char const * sep = ", ", int limit = INT_MAX, std::set<elem const*> marked = {}) const { o << "[sd=" << (int)sd_ << ", size=" << size_ << ", head=" << (void*)head_ << ": "; int cnt = 0; char const * ssep = sep; for(elem const * p = head_; p; p = p->forwards[0], ssep=sep) { if ( cnt++ >= limit ) { o << sep << "..."; break; } p->dump(o << sep << (marked.count(p) ? "*" : " " )); } o << "]"; return o; } bool insert(key_type k, value_type v) { //dump(std::cout << "-- insert (" << k << "->" << v << "), into:\n", "\n") << std::endl; std::array<elem*, N> forwards {}; if ( elem * p = head_ ) { if ( lt( p->key, k ) ) { for(size_t lvl = N; lvl > 0;) { --lvl; while( p->forwards[lvl] && lt( p->forwards[lvl]->key, k) ) { p = p->forwards[lvl]; } forwards[lvl] = p; assert( lt(p->key, k) ); // p->key < k, k is strictly greater than p->key } if ( !allow_duplicates && p->forwards[0] && eq( p->forwards[0]->key, k ) ) return false; insert_after(p, k, v, random_level(), forwards); } else { if ( !allow_duplicates && eq(p->key, k) ) return false; assert( p == head_ ); assert( lt(k, p->key) || eq(p->key, k) ); // k < p->key // insert before head: take current head's forward as new refs, p->forwards if ( p->forwards[0] ) { assert( p->forwards[N-1] != nullptr && "head needs to have all levels"); insert_head( k, v, random_level(), p->forwards ); } else { assert( size_ == 1 ); elem::set_forwards( forwards, 0, N, p ); insert_head( k, v, random_level(), forwards ); assert( size_ == 2 ); } assert( head_->forwards[N-1] != nullptr && "head needs to have all levels"); assert( head_ != p && "new elem inserted as a head" ); } } else { assert( head_ == nullptr ); assert( std::all_of(forwards.begin(), forwards.end(), [](auto * p){ return p == nullptr; })); insert_head( k, v, 0, forwards ); assert( size_ == 1 ); } return true; } void erase_head() { assert( head_ && size_ > 0 ); elem * old = head_; head_ = head_->forwards[0]; if ( head_ ) { size_t i = 1; for( ; i < N && head_->forwards[i]; ++i ) ; // skip filled cells for( ; i < N; ++i ) { assert( head_->forwards[i] == nullptr ); // copy from old head unless it would cause a loop head_->forwards[i] = ( old->forwards[i] != head_ ) ? old->forwards[i] : head_->forwards[i-1]; } } assert( size_ > 0 ); size_--; allocator_type::destroy(old); allocator_type::deallocate(old, 1); } void erase_after( elem * prev, elem * del, std::array<elem*, N> & fwrds) { assert( prev && size_ > 0 ); assert( del && del == prev->forwards[0]); assert( fwrds[0] == prev ); fwrds[0]->forwards[0] = del->forwards[0]; for(size_t i = 1; i < N; ++i) { // fixup level pointers if ( del == fwrds[i]->forwards[i] ) { // copy from deleted, unless it would cause a loop, then take previous forwards fwrds[i]->forwards[i] = ( del->forwards[i] && del->forwards[i] != fwrds[i] ) ? del->forwards[i] : fwrds[i]->forwards[i-1]; } } assert( size_ > 0 ); size_--; allocator_type::destroy(del); allocator_type::deallocate(del, 1); }; std::pair<value_type, size_t> erase(key_type k) { if ( elem * p = head_ ) { std::array<elem*, N> forwards {}; if ( lt( p->key, k ) ) { for(size_t lvl = N; lvl > 0;) { --lvl; while( p->forwards[lvl] && lt( p->forwards[lvl]->key, k) ) { p = p->forwards[lvl]; } forwards[lvl] = p; assert( lt(p->key, k) ); // p->key < k, k is strictly greater than p->key } elem * q = p->forwards[0]; if ( q && eq( q->key, k ) ) { auto r = q->value; erase_after(p, q, forwards); return std::make_pair(r, 1); } } else { if ( eq(p->key, k) ) { auto r = p->value; assert( p == head_ ); erase_head(); return std::make_pair(r, 1); } } } return std::make_pair(value_type{}, 0); } struct iter_impl : public std::iterator< std::forward_iterator_tag, elem > { elem * p; iter_impl(elem * x) : p(x) {} void next() { p = p->forwards[0]; } bool operator==(iter_impl o) const { return p == o.p; } bool operator!=(iter_impl o) const { return p != o.p; } elem & operator*() { return *p; } elem const & operator*() const { return *p; } elem * operator->() { return p; } elem const * operator->() const { return p; } iter_impl & operator++() { next(); return *this; } iter_impl operator++(int) { iter_impl tmp{*this}; next(); return tmp; } }; using iterator = iter_impl; using const_iterator = const iter_impl; iterator begin() { return iterator{head_}; } iterator end() { return iterator{nullptr}; } const_iterator cbegin() { return const_iterator{head_}; } const_iterator cend() { return const_iterator{nullptr}; } const_iterator begin() const { return const_iterator{head_}; } const_iterator end() const { return const_iterator{nullptr}; } protected: size_t random_level() { static std::random_device rd; size_t r = N; if ( use_uniform_dist ) { std::uniform_int_distribution<int> dist_{1,N}; r = dist_(rd); } else if ( use_log_dist ) { std::uniform_int_distribution<int> dist_{2,1<<N}; r = std::log2(dist_(rd)); } else if ( use_rev_log_dist ) { std::uniform_int_distribution<int> dist_{2,1<<N}; r = N-std::log2(dist_(rd))+1; } else if ( use_sqrt_dist ) { std::uniform_int_distribution<int> dist_{1,N*N}; r = std::sqrt(dist_(rd)); } else if ( use_rev_sqrt_dist ) { std::uniform_int_distribution<int> dist_{1,N*N}; r = N-std::sqrt(dist_(rd))+1; } assert( r != 0 ); assert( 1 <= r && r <= N ); return r; } void insert_after(elem* p, key_type k, value_type v, size_t lvl, std::array<elem*, N> const fwrds) { elem * e = allocator_type::allocate(1); allocator_type::construct(e, k, v); //elem::dump_distances(std::cout << "-- insert_after (p=" << p << ", lvl=" << lvl << ", " // << k << "->" << v << ", fwrds=", nullptr, fwrds) << ")" << std::endl; size_t n = fwrds[N-1] == head_ ? N : lvl; for(size_t i = 0; i < n; ++i) { //TODO: embed ranvom level elem * f = fwrds[i]; elem * aux = f->forwards[i]; f->forwards[i] = e; e->forwards[i] = aux; } size_++; } void insert_head( key_type k, value_type v, size_t lvl, std::array<elem*, N> const & fwrds) { elem * e = allocator_type::allocate(1); allocator_type::construct(e, k, v, fwrds); //elem::dump_distances(std::cout << "-- insert_head (lvl=" << lvl << ", " // << k << "->" << v << ", fwrds=", nullptr, fwrds) << ")" << std::endl; elem * p = head_; head_ = e; head_->set_forwards(0, lvl, p); if ( p ) p->set_forwards(lvl, N, nullptr); size_++; } }; <file_sep>#include "skip_list.hpp" <file_sep>add_executable(tester skip_list_test.cpp) target_link_libraries(tester skip_list libgtest libgtest_main) add_test(NAME skip_list_test COMMAND tester) <file_sep>#include <gtest/gtest.h> #include <iostream> #include "skip_list.hpp" using test_type = skip_list<int32_t, void*>; struct skip_list_test : public ::testing::TestWithParam<int8_t> {}; INSTANTIATE_TEST_CASE_P(bid_or_ask, skip_list_test, ::testing::Values(0,1)); TEST_P(skip_list_test, instance) { EXPECT_NO_THROW({ test_type x(GetParam()); test_type y = x; //const test_type x = y; }); } TEST_P(skip_list_test, empty) { test_type x(GetParam()); EXPECT_TRUE( x.empty() ); EXPECT_EQ( 0, x.size() ); EXPECT_EQ( 0, x.count() ); EXPECT_EQ( nullptr, x.find(0) ); EXPECT_EQ( nullptr, x.find(1) ); EXPECT_FALSE( x.contains(0) ); EXPECT_FALSE( x.contains(1) ); } TEST_P(skip_list_test, insert_1) { test_type x(GetParam()); EXPECT_TRUE( x.empty() ); EXPECT_TRUE( x.insert(1, (void*)1UL ) ); EXPECT_FALSE( x.empty() ); EXPECT_EQ( 1, x.size() ); EXPECT_EQ( x.size(), x.count() ); EXPECT_TRUE( x.contains(1) ); ASSERT_NE( nullptr, x.find(1) ); EXPECT_EQ( (void*)1UL, *x.find(1) ); EXPECT_FALSE( x.insert(1, (void*)1UL ) ); EXPECT_EQ( 1, x.size() ); EXPECT_TRUE( x.contains(1) ); } TEST_P(skip_list_test, insert_315) { test_type x(GetParam()); EXPECT_TRUE ( x.insert(3, (void*)1UL ) ); EXPECT_TRUE ( x.insert(1, (void*)1UL ) ); EXPECT_TRUE ( x.insert(5, (void*)1UL ) ); //x.dump(std::cout, "\n") << std::endl; auto v = x.to_vector(); ASSERT_EQ( 3, v.size() ); if ( GetParam() == 0 ) { EXPECT_EQ( 1, v[0].first ); EXPECT_EQ( 3, v[1].first ); EXPECT_EQ( 5, v[2].first ); } else { EXPECT_EQ( 5, v[0].first ); EXPECT_EQ( 3, v[1].first ); EXPECT_EQ( 1, v[2].first ); } } TEST_P(skip_list_test, insert_duplicates) { test_type x(GetParam()); ASSERT_FALSE( x.allow_duplicates ); EXPECT_TRUE ( x.insert(1, (void*)1UL ) ); EXPECT_FALSE( x.insert(1, (void*)1UL ) ); EXPECT_TRUE ( x.insert(3, (void*)1UL ) ); EXPECT_FALSE( x.insert(1, (void*)1UL ) ); EXPECT_FALSE( x.insert(3, (void*)1UL ) ); EXPECT_TRUE ( x.insert(5, (void*)1UL ) ); EXPECT_FALSE( x.insert(1, (void*)1UL ) ); EXPECT_FALSE( x.insert(3, (void*)1UL ) ); EXPECT_FALSE( x.insert(5, (void*)1UL ) ); //x.dump(std::cout, "\n") << std::endl; auto v = x.to_vector(); ASSERT_EQ( 3, v.size() ); if ( GetParam() == 0 ) { EXPECT_EQ( 1, v[0].first ); EXPECT_EQ( 3, v[1].first ); EXPECT_EQ( 5, v[2].first ); } else { EXPECT_EQ( 5, v[0].first ); EXPECT_EQ( 3, v[1].first ); EXPECT_EQ( 1, v[2].first ); } } TEST_P(skip_list_test, contains) { test_type x(GetParam()); ASSERT_TRUE( x.insert(1, (void*)1UL ) ); ASSERT_TRUE( x.insert(3, (void*)1UL ) ); ASSERT_TRUE( x.insert(5, (void*)1UL ) ); //x.dump(std::cout, "\n") << std::endl; EXPECT_TRUE( x.contains(1) ); EXPECT_TRUE( x.contains(3) ); EXPECT_TRUE( x.contains(5) ); EXPECT_FALSE( x.contains(0) ); EXPECT_FALSE( x.contains(2) ); EXPECT_FALSE( x.contains(4) ); EXPECT_FALSE( x.contains(6) ); } TEST_P(skip_list_test, insert_10) { test_type x(GetParam()); std::array<int, 10> v { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; EXPECT_TRUE( x.empty() ); for(int i : v) { ASSERT_TRUE( x.insert(i, (void*)(size_t)i ) ) << "i=" << i; } EXPECT_FALSE( x.empty() ); EXPECT_EQ( v.size(), x.size() ); EXPECT_EQ( x.size(), x.count() ); //x.dump(std::cout, "\n", 10) << std::endl; for(int i : v) { EXPECT_TRUE( x.contains(i) ) << "i=" << i; } } TEST_P(skip_list_test, insert_10_perm) { test_type x(GetParam()); std::array<int, 10> v { 5, 2, 9, 4, 1, 6, 7, 10, 3, 8 }; EXPECT_TRUE( x.empty() ); for(int i : v) { ASSERT_TRUE( x.insert(i, (void*)(size_t)i ) ) << "i=" << i; } EXPECT_FALSE( x.empty() ); EXPECT_EQ( v.size(), x.size() ); EXPECT_EQ( x.size(), x.count() ); //x.dump(std::cout, "\n", 10) << std::endl; for(int i : v) { EXPECT_TRUE( x.contains(i) ) << "i=" << i; } } TEST_P(skip_list_test, insert_1000) { test_type x(GetParam()); int N = 1000; //test_type::max_elements_in_block(); EXPECT_TRUE( x.empty() ); for(int i = 1; i <= N; ++i) { ASSERT_TRUE( x.insert(i, (void*)(size_t)i ) ) << "i=" << i; } EXPECT_FALSE( x.empty() ); EXPECT_EQ( N, x.size() ); EXPECT_EQ( x.size(), x.count() ); //x.dump(std::cout, "\n") << std::endl; for(int i = 1; i <= N; ++i) { EXPECT_TRUE( x.contains(i) ) << "i=" << i; } } TEST_P(skip_list_test, insert_1000_rev) { test_type x(GetParam()); int N = 1000; EXPECT_TRUE( x.empty() ); for(int i = N; i >= 1; --i) { ASSERT_TRUE( x.insert(i, (void*)(size_t)i ) ) << "i=" << i; } EXPECT_FALSE( x.empty() ); EXPECT_EQ( N, x.size() ); EXPECT_EQ( x.size(), x.count() ); for(int i = 1; i <= N; ++i) { EXPECT_TRUE( x.contains(i) ) << "i=" << i; } } TEST_P(skip_list_test, insert_1000_dup) { test_type x(GetParam()); int N = 1000; //test_type::max_elements_in_block(); EXPECT_TRUE( x.empty() ); ASSERT_FALSE( x.allow_duplicates ); for(int i = 1; i <= N; ++i) { ASSERT_TRUE( x.insert(i, (void*)(size_t)i ) ) << "i=" << i; ASSERT_FALSE( x.insert(i, (void*)(size_t)i ) ) << "i=" << i; } for(int i = N; i >= 1; --i) { ASSERT_FALSE( x.insert(i, (void*)(size_t)i ) ) << "i=" << i; } EXPECT_FALSE( x.empty() ); EXPECT_EQ( N, x.size() ); EXPECT_EQ( x.size(), x.count() ); //x.dump(std::cout, "\n") << std::endl; for(int i = 1; i <= N; ++i) { EXPECT_TRUE( x.contains(i) ) << "i=" << i; } } TEST_P(skip_list_test, erase_when_empty) { test_type x(GetParam()); EXPECT_TRUE( x.empty() ); EXPECT_EQ( nullptr, x.erase(1).first ); EXPECT_EQ( 0, x.erase(1).second ); EXPECT_TRUE( x.empty() ); } TEST_P(skip_list_test, erase_1_after_insert_1) { test_type x(GetParam()); EXPECT_TRUE( x.empty() ); EXPECT_TRUE( x.insert(1, (void*)1UL ) ); EXPECT_FALSE( x.empty() ); EXPECT_TRUE( x.contains(1) ); EXPECT_EQ( (void*)1UL, x.erase(1).first ); EXPECT_TRUE( x.empty() ); EXPECT_FALSE( x.contains(1) ); EXPECT_EQ( nullptr, x.erase(1).first ); } TEST_P(skip_list_test, insert_and_erase_1000) { test_type x(GetParam()); int N = 1000; //test_type::max_elements_in_block(); EXPECT_TRUE( x.empty() ); ASSERT_FALSE( x.allow_duplicates ); for(int i = 1; i <= N; ++i) { ASSERT_TRUE( x.insert(i, (void*)(size_t)i ) ) << "i=" << i; } ASSERT_FALSE( x.empty() ); ASSERT_EQ( N, x.size() ); //x.dump(std::cout, "\n") << std::endl; for(int i = 1; i <= N; ++i) { EXPECT_EQ( (void*)(size_t)i, x.erase(i).first ) << "i=" << i; //x.dump(std::cout << "$$", "\n") << std::endl; } EXPECT_TRUE( x.empty() ); EXPECT_EQ(0, x.size() ); } TEST_P(skip_list_test, erase_10_perm) { test_type x(GetParam()); std::array<int, 10> v { 5, 2, 9, 4, 1, 6, 7, 10, 3, 8 }; int N = 10; for(int i = 1; i <= N; ++i) { ASSERT_TRUE( x.insert(i, (void*)(size_t)i ) ) << "i=" << i; } ASSERT_FALSE( x.empty() ); ASSERT_EQ( N, x.size() ); for(int i : v) { EXPECT_EQ( (void*)(size_t)i, x.erase(i).first ) << "i=" << i; } EXPECT_TRUE( x.empty() ); EXPECT_EQ(0, x.size() ); } <file_sep>#pragma once #include <cstdlib> #include <cstddef> #include <memory> #include <type_traits> #include <utility> namespace detail { void* allocate_aligned_memory(size_t align, size_t size); void deallocate_aligned_memory(void* ptr) noexcept; } template <typename T, size_t Align> class aligned_allocator; template <size_t Align> class aligned_allocator<void, Align> { public: typedef void* pointer; typedef const void* const_pointer; typedef void value_type; template <class U> struct rebind { typedef aligned_allocator<U, Align> other; }; }; template <typename T, size_t Align> class aligned_allocator { public: typedef T value_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef std::true_type propagate_on_container_move_assignment; template <class U> struct rebind { typedef aligned_allocator<U, Align> other; }; public: aligned_allocator() noexcept = default; template <class U> aligned_allocator(const aligned_allocator<U, Align>&) noexcept {} static size_type max_size() noexcept { return (size_type(~0) - size_type(Align)) / sizeof(T); } static pointer address(reference x) noexcept { return std::addressof(x); } static const_pointer address(const_reference x) noexcept { return std::addressof(x); } static pointer allocate(size_type n, typename aligned_allocator<void, Align>::const_pointer = 0) noexcept { const size_type alignment = static_cast<size_type>( Align ); void* ptr = detail::allocate_aligned_memory(alignment , n * sizeof(T)); /* if (ptr == nullptr) { throw std::bad_alloc(); } */ return reinterpret_cast<pointer>(ptr); } static void deallocate(pointer p, size_type) noexcept { return detail::deallocate_aligned_memory(p); } template <class U, class ...Args> static void construct(U* p, Args&&... args) { ::new(reinterpret_cast<void*>(p)) U(std::forward<Args>(args)...); } static void destroy(pointer p) { p->~T(); } }; template <typename T, size_t Align> class aligned_allocator<const T, Align> { public: typedef T value_type; typedef const T* pointer; typedef const T* const_pointer; typedef const T& reference; typedef const T& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef std::true_type propagate_on_container_move_assignment; template <class U> struct rebind { typedef aligned_allocator<U, Align> other; }; public: aligned_allocator() noexcept = default; template <class U> aligned_allocator(const aligned_allocator<U, Align>&) noexcept {} static size_type max_size() noexcept { return (size_type(~0) - size_type(Align)) / sizeof(T); } static const_pointer address(const_reference x) noexcept { return std::addressof(x); } static pointer allocate(size_type n, typename aligned_allocator<void, Align>::const_pointer = 0) noexcept { const size_type alignment = static_cast<size_type>( Align ); void* ptr = detail::allocate_aligned_memory(alignment , n * sizeof(T)); /* if (ptr == nullptr) { throw std::bad_alloc(); } */ return reinterpret_cast<pointer>(ptr); } static void deallocate(pointer p, size_type) noexcept { return detail::deallocate_aligned_memory(p); } template <class U, class ...Args> static void construct(U* p, Args&&... args) { ::new(reinterpret_cast<void*>(p)) U(std::forward<Args>(args)...); } static void destroy(pointer p) { p->~T(); } }; template <typename T, size_t TAlign, typename U, size_t UAlign> inline bool operator== (const aligned_allocator<T,TAlign>&, const aligned_allocator<U, UAlign>&) noexcept { return TAlign == UAlign; } template <typename T, size_t TAlign, typename U, size_t UAlign> inline bool operator!= (const aligned_allocator<T,TAlign>&, const aligned_allocator<U, UAlign>&) noexcept { return TAlign != UAlign; } <file_sep>#pragma once template<typename R, uintptr_t align, typename T> constexpr inline R mask_ptr(T * p) { static_assert( align && !(align & (align-1)), "power of 2" ); uintptr_t const aux = reinterpret_cast<uintptr_t>(p) & ~(align-1); return reinterpret_cast<R>(aux); } template<typename T> constexpr inline bool is_power_of_two(T n) { return (n > 0) & ( 0 == ( n & (n-1) )); }
c4f3c224837fe2d808ee175ee0bb108d04f5ce37
[ "CMake", "C++" ]
9
C++
marciso/skip_list
164d2a1a91a9b8a4d3e6bbc08b4bfbdbe4473666
8eec2c4f7a78198da49d54b79b6fb9e1ed4330d0
refs/heads/master
<repo_name>Dauta/Nebula<file_sep>/src/nebula/player/Glass.java package player; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class Glass extends JPanel implements ActionListener { /** * */ private static final long serialVersionUID = 1L; Music music; String ttl = " "; JLabel title; public Glass(Music m) { new Timer(30, this).start(); this.setLayout(new BorderLayout()); music = m; music.playButton.addActionListener(music.PlayMp3); //or play WAV music.stopButton.addActionListener(music.StopMp3); music.nextButton.addActionListener(music.nextBtnListener); music.prevButton.addActionListener(music.prevBtnListener); ImageIcon playIcon = new ImageIcon("E:\\Projects\\Nebula\\src\\Image\\playBtn2.png"); music.playButton.setBorder(BorderFactory.createEmptyBorder()); music.playButton.setContentAreaFilled(false); music.playButton.setFocusable(false); music.playButton.setIcon(playIcon); music.playButton.setSize((int)MusicPlayer.masterSize.getWidth() * 5/100, (int)MusicPlayer.masterSize.getWidth() * 5/100); music.playButton.setPreferredSize(music.playButton.getSize()); ImageIcon stopIcon = new ImageIcon("E:\\Projects\\Nebula\\src\\Image\\stopBtn2.png"); music.stopButton.setBorder(BorderFactory.createEmptyBorder()); music.stopButton.setContentAreaFilled(false); music.stopButton.setFocusable(false); music.stopButton.setIcon(stopIcon); music.stopButton.setSize((int)MusicPlayer.masterSize.getWidth() * 5/100, (int)MusicPlayer.masterSize.getWidth() * 5/100); music.stopButton.setPreferredSize(music.stopButton.getSize()); ImageIcon nextIcon = new ImageIcon("E:\\Projects\\Nebula\\src\\Image\\nextBtn.png"); music.nextButton.setBorder(BorderFactory.createEmptyBorder()); music.nextButton.setContentAreaFilled(false); music.nextButton.setFocusable(false); music.nextButton.setIcon(nextIcon); music.nextButton.setSize((int)MusicPlayer.masterSize.getWidth() * 5/100, (int)MusicPlayer.masterSize.getWidth() * 5/100); music.nextButton.setPreferredSize(music.stopButton.getSize()); ImageIcon prevIcon = new ImageIcon("E:\\Projects\\Nebula\\src\\Image\\prevBtn.png"); music.prevButton.setBorder(BorderFactory.createEmptyBorder()); music.prevButton.setContentAreaFilled(false); music.prevButton.setFocusable(false); music.prevButton.setIcon(prevIcon); music.prevButton.setSize((int)MusicPlayer.masterSize.getWidth() * 5/100, (int)MusicPlayer.masterSize.getWidth() * 5/100); music.prevButton.setPreferredSize(music.stopButton.getSize()); JPanel buttonPanel = new JPanel(); buttonPanel.setSize((int)MusicPlayer.masterSize.getWidth() * 95/100, (int)MusicPlayer.masterSize.getHeight() * 10/100 ); buttonPanel.setPreferredSize(buttonPanel.getSize()); buttonPanel.setBackground(new Color(0,0,0,0)); buttonPanel.add(music.prevButton); buttonPanel.add(music.playButton); buttonPanel.add(music.stopButton); buttonPanel.add(music.nextButton); this.add(buttonPanel, BorderLayout.NORTH); } @Override public void actionPerformed(ActionEvent arg0) { if(ttl != ClickableLabel.songName) { try { this.remove(title); } catch(Exception e) { title = new JLabel(" "); this.add(title,BorderLayout.NORTH); //e.printStackTrace(); } // System.out.println(ttl + "first"); ttl = ClickableLabel.songName; // System.out.println(ttl + "second"); title = new JLabel(ttl); title.setFont(new Font("Calibri", Font.LAYOUT_LEFT_TO_RIGHT, 25)); title.setForeground(new Color(250,250,250)); this.add(title,BorderLayout.NORTH); revalidate(); } } } <file_sep>/src/nebula/player/MenuBar.java package player; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map.Entry; @SuppressWarnings("serial") public class MenuBar extends JMenuBar { Playlist list; JMenu file, playlist; JMenuItem open, importFolder, createNewPlaylist, save, load; JFileChooser fileChooser; public File selectedFile; public ClickablePlaylist cp; JPanel panel, bigPanel; public MenuBar(Playlist pl, JPanel p, JPanel p2) { panel = p; bigPanel = p2; this.setBackground(new Color(100,200,200,20)); file = new JMenu("File"); file = new JMenu("Folder"); playlist = new JMenu("Playlist"); open = new JMenuItem("Open File..."); importFolder = new JMenuItem("Import a Folder..."); createNewPlaylist = new JMenuItem("Create new Playlist..."); save = new JMenuItem("Save Playlists..."); load = new JMenuItem("Load Playlist..."); open.addActionListener(openFileListener); createNewPlaylist.addActionListener(createNewList); save.addActionListener(saveListener); load.addActionListener(loadListener); playlist.add(createNewPlaylist); playlist.add(save); playlist.add(load); file.add(open); file.add(importFolder); this.add(playlist); this.add(file); this.setVisible(true); list = pl; } public static void infoBox(String infoMessage, String titleBar) { JOptionPane.showMessageDialog(null, infoMessage, "InfoBox: " + titleBar, JOptionPane.INFORMATION_MESSAGE); } ActionListener openFileListener = new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if(!(Playlist.name == null)) list.OpenSingleFile(); else { infoBox("Create a playlist first", "Oops"); cp = new ClickablePlaylist(panel, bigPanel, list); cp.insertPlaylist(); } } }; ActionListener playlistListener = new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(Playlist.name != null) { list.GetList(); } else { infoBox("Create a playlist first", "Oops"); cp = new ClickablePlaylist(panel, bigPanel, list); cp.insertPlaylist(); } } }; ActionListener saveListener = new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { savePlaylist(); } }; ActionListener createNewList = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { cp = new ClickablePlaylist(panel, bigPanel, list); cp.insertPlaylist(); } }; ActionListener loadListener = new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { LoadPlaylist(); } }; public void ChoosePlaylistFolder() { importFolder.addActionListener(playlistListener); } void savePlaylist() { String userName = System.getProperty("user.name"); String savePath = "C:\\Users\\"+userName+"\\Documents\\TheMusicPlayer"; File f = new File(savePath); if(f.exists() && f.isDirectory()) { File old = new File(savePath + "\\playlist.txt"); old.delete(); try{ FileWriter fstream = new FileWriter(savePath + "\\playlist.txt"); BufferedWriter out = new BufferedWriter(fstream); Iterator<Entry<String, LinkedHashMap>> it = list.mainList.entrySet().iterator(); while(it.hasNext()) { Entry<String, LinkedHashMap> currentList = it.next(); LinkedHashMap<String, String> currentMap = currentList.getValue(); out.write(currentList.getKey()+"FFFF"); out.newLine(); Iterator<Entry<String, String>> it2 = currentMap.entrySet().iterator(); while(it2.hasNext()) { Entry<String, String> thePlaylist = it2.next(); out.write(thePlaylist.getKey()+"SSSPLITTERRR"+thePlaylist.getValue()); out.newLine(); } } //out.write("Hello Java"); //Close the output stream out.close(); } catch(Exception e) { e.printStackTrace(); } } else { f.mkdir(); try{ FileWriter fstream = new FileWriter(f.getAbsolutePath()+"\\playlist.txt"); BufferedWriter out = new BufferedWriter(fstream); Iterator<Entry<String, LinkedHashMap>> it = list.mainList.entrySet().iterator(); while(it.hasNext()) { Entry<String, LinkedHashMap> currentList = it.next(); LinkedHashMap<String, String> currentMap = currentList.getValue(); out.write(currentList.getKey()); out.newLine(); Iterator<Entry<String, String>> it2 = currentMap.entrySet().iterator(); while(it2.hasNext()) { Entry<String, String> thePlaylist = it2.next(); out.write(thePlaylist.getKey()+" "+thePlaylist.getValue()); out.newLine(); } } out.close(); } catch(Exception e) { e.printStackTrace(); } } } void LoadPlaylist() { String userName = System.getProperty("user.name"); String loadPath = "C:\\Users\\"+userName+"\\Documents\\TheMusicPlayer\\playlist.txt"; BufferedReader br; File f = new File(loadPath); String tempOuterKey = null; String tempInnerKey = null; String tempInnerValue = null; LinkedHashMap<String, String> tempMap = new LinkedHashMap<String,String>(); String currentLine; String toBeName = null; if(f.exists()) { try { br = new BufferedReader(new FileReader(loadPath)); while ((currentLine = br.readLine()) != null) { // System.out.println(currentLine); if(currentLine.substring(currentLine.length() - 4).equals("FFFF")) { tempOuterKey = currentLine.substring(0, currentLine.length() - 4); toBeName = tempOuterKey; //System.out.println(tempOuterKey+" tempOuterKey"); tempMap.clear(); } else { String[] splitString = currentLine.split("SSSPLITTERRR"); tempInnerKey = splitString[0]; System.out.println(tempInnerKey); tempInnerValue = splitString[1]; System.out.println(tempInnerValue); //tempMap = new LinkedHashMap<String,String>(); tempMap.put(tempInnerKey, tempInnerValue); } //System.out.println(tempMap); LinkedHashMap<String, String> asd = new LinkedHashMap<String, String>(); asd.putAll(tempMap); list.mainList.put(tempOuterKey, asd); //tempMap.clear(); } System.out.println(list.mainList); // playlist.name = list.mainList. //System.out.println("asd"); br.close(); } catch(Exception e) { e.printStackTrace(); } } System.out.println(list.mainList); Iterator<String> it = list.mainList.keySet().iterator(); while(it.hasNext()) { String curr = it.next(); System.out.println(curr); ClickablePlaylist playlistToCreate = new ClickablePlaylist(panel, bigPanel, list, curr); playlistToCreate.autoInsertPlaylist(); } Playlist.name = toBeName; System.out.println(list.mainList); } } <file_sep>/src/nebula/player/BackGround.java package player; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; import javax.swing.JPanel; class BackGround extends JPanel //class for drawing background elements animating dots { /** * */ private static final long serialVersionUID = 1L; Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); double screenWidth = screenSize.getWidth(); double screenHeight = screenSize.getHeight(); private Random randomCoordinate = new Random(); //random number generator for initial coordinates; private int numberOfDots = (int) (screenWidth * screenHeight) / 8000; int[] x = new int[numberOfDots]; int[] y = new int[numberOfDots]; boolean[] flagX = new boolean[numberOfDots]; boolean[] flagY = new boolean[numberOfDots]; public BackGround() { for(int i = 0; i<numberOfDots; i++) { x[i] = 10 + randomCoordinate.nextInt((int)screenWidth - 10); y[i] = 10 + randomCoordinate.nextInt((int)screenHeight - 10); } } @Override protected void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; // g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, //ANTIALIASED PANEL!!!!! RenderingHints.VALUE_ANTIALIAS_ON); // super.paintComponent(g2); super.paintComponent(g); for(int j = 0; j<numberOfDots; j++) //draw circles { g.setColor(new Color(204,229,255)); g.fillOval(x[j], y[j], 4, 4); } for(int a = 0; a<numberOfDots; a++) //draw lines { for(int b=0; b<numberOfDots; b++) { if((Math.abs(x[a] - x[b]) < 50) && (Math.abs(y[a]-y[b]) < 50)) { g.setColor(new Color(204,229,255, 255)); g.drawLine(x[a], y[a], x[b], y[b]); } if((Math.abs(x[a] - x[b]) < 60) && (Math.abs(y[a]-y[b]) < 60)) { g.setColor(new Color(204,229,255, 200)); g.drawLine(x[a], y[a], x[b], y[b]); } if((Math.abs(x[a] - x[b]) < 70) && (Math.abs(y[a]-y[b]) < 70)) { g.setColor(new Color(204,229,255, 150)); g.drawLine(x[a], y[a], x[b], y[b]); } if((Math.abs(x[a] - x[b]) < 80) && (Math.abs(y[a]-y[b]) < 80)) { g.setColor(new Color(204,229,255, 100)); g.drawLine(x[a], y[a], x[b], y[b]); } if((Math.abs(x[a] - x[b]) < 90) && (Math.abs(y[a]-y[b]) < 90)) { g.setColor(new Color(204,229,255, 50)); g.drawLine(x[a], y[a], x[b], y[b]); } if((Math.abs(x[a] - x[b]) < 100) && (Math.abs(y[a]-y[b]) < 100)) { g.setColor(new Color(204,229,255, 20)); g.drawLine(x[a], y[a], x[b], y[b]); } } } } ActionListener update = new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub for(int k = 0; k < numberOfDots; k++) { if(x[k] == screenWidth) flagX[k] = true; else if(x[k] == 0) flagX[k] = false; if(y[k] == screenHeight) flagY[k] = true; else if(y[k] == 0) flagY[k] = false; //motion algorithm if(!flagX[k] && !flagY[k]) { if(k%2 == 0) { x[k] += 0.9; y[k] += 1.1; } else if(k%3 == 0) { x[k] += 1.7; y[k] += 1.8; } else if(k%5 == 0) { x[k] += 1.4; y[k] += 2.0; } else { x[k] += 1.1; y[k] += 0.9; } } else if(flagX[k] && flagY[k]) { if(k%2 == 0) { x[k] -= 0.9; y[k] -= 1.1; } else if(k%3 == 0) { x[k] -= 1.7; y[k] -= 1.8; } else if(k%5 == 0) { x[k] -= 1.4; y[k] -= 2.0; } else { x[k] -= 1.1; y[k] -= 0.9; } } else if(flagX[k] && !flagY[k]) { if(k%2 == 0) { x[k] -= 0.9; y[k] += 1.1; } else if(k%3 == 0) { x[k] -= 1.7; y[k] += 1.8; } else if(k%5 == 0) { x[k] -= 1.4; y[k] += 2.0; } else { x[k] -= 1.1; y[k] += 0.9; } } else if(!flagX[k] && flagY[k]) { if(k%2 == 0) { x[k] += 0.9; y[k] -= 1.1; } else if(k%3 == 0) { x[k] += 1.7; y[k] -= 1.8; } else if(k%5 == 0) { x[k] += 1.4; y[k] -= 2.0; } else { x[k] += 1.1; y[k] -= 0.9; } } //end motion algorithm } repaint(); } }; public void addGlass(JPanel glass) { //this.setLayout(new BorderLayout()); glass.setBackground(new Color(40,40,50,130)); //glass.setSize((int)MusicPlayer.masterSize.getWidth(), (int)MusicPlayer.masterSize.getHeight()); //glass.setPreferredSize(glass.getSize()); this.add(glass, BorderLayout.CENTER); } }<file_sep>/src/nebula/player/Music.java package player; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.util.Iterator; import java.util.Map.Entry; import javax.swing.ImageIcon; import javax.swing.JButton; import javazoom.jl.player.Player; import javazoom.jl.decoder.Equalizer; public class Music { String bufferedSong; String fileName; int songCounter = 0; Player mp3player; MenuBar menu; Playlist playlist; boolean nowPlaying = false; boolean nowPaused = false; boolean finished = true; JButton playButton = new JButton("Play"); JButton stopButton = new JButton("Stop"); JButton nextButton = new JButton("Next"); JButton prevButton = new JButton("Previous"); public BufferedInputStream buffStream; public FileInputStream stream; long audioLength = 0; long audioPaused = 0; Thread musicThread; String song; // String currentSong; public Music(MenuBar mb, Playlist pl) { menu = mb; playlist = pl; } void LoadStream() { try { song = ClickableLabel.songName; fileName = (String)playlist.mainList.get(Playlist.name).get(song); stream = new FileInputStream(fileName); audioLength = stream.available(); //get the length of a full file in bytes; buffStream = new BufferedInputStream(stream); mp3player = new Player(buffStream); } catch (Exception e) { System.out.println(e); e.printStackTrace(); } } ActionListener PlayMp3 = new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if(song == null) { playlist.OpenSingleFile(); } else { Play(); } } }; //end PlayMp3 ActionListener ActionListener StopMp3 = new ActionListener() { public void actionPerformed(ActionEvent args0) { Stop(); } }; ActionListener PauseMp3 = new ActionListener() { public void actionPerformed(ActionEvent args0) { Pause(); } }; ActionListener durationListener = new ActionListener() { @Override public void actionPerformed(ActionEvent args0) { CheckDuration(); } }; ActionListener changeListener = new ActionListener() //check this!!!!! { @Override public void actionPerformed(ActionEvent e) { if(song != ClickableLabel.songName) { Stop(); Play(); } } }; ActionListener nextBtnListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Stop(); try { //automaticly go to the next one; System.out.println("asd"); Iterator<Entry<String, String>> it = playlist.mainList.get(Playlist.name).entrySet().iterator(); while(it.hasNext()) { // System.out.println(ClickableLabel.songName + "whatever"); Entry<String, String> curr = it.next(); //System.out.println(curr.getKey()); if(curr.getKey().equals(song)) { ClickableLabel.songName = it.next().getKey(); System.out.println(ClickableLabel.songName); break; } } } catch(Exception asd) { System.out.println("no more"); } } }; ActionListener prevBtnListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { //automaticly go to the previous one Stop(); Iterator<Entry<String, String>> it = playlist.mainList.get(Playlist.name).entrySet().iterator(); while(it.hasNext()) { String[] curr = new String[100]; for(int i = 0; i<playlist.mainList.get(Playlist.name).size(); i++) { curr[i] = it.next().getKey(); if(curr[i].equals(song)) { if(i > 0) { ClickableLabel.songName = curr[i-1]; break; } } } } } catch(Exception ex) { Play(); } } }; void Play() { // LoadStream(); musicThread = new Thread() { public void run() { try { // System.out.println("New Thread"); // System.out.println(ClickableLabel.songName); mp3player.play(); // System.out.println("Thread finished"); } catch (Exception e) { System.out.println(e); e.printStackTrace(); } } }; // System.out.println( musicThread.getUncaughtExceptionHandler()); // song = ClickableLabel.songName; if(nowPlaying == false && nowPaused == false && finished == true) { //get a file path and set up streams and player LoadStream(); musicThread.start(); //start thread to play music nowPlaying = true; //nowPlaying flag set to true finished = false; } else if(nowPaused == true) { try //get a file path and set up streams and player { LoadStream(); // ClickableLabel.songName = currentSong; // System.out.println(audioLength); buffStream.skip(audioLength - audioPaused - 25000); musicThread.start(); audioPaused = 0; //reset the byte counter nowPaused = false; //reset the nowPaused flag nowPlaying = true; //set the nowPlaying flag } catch (Exception e) { System.out.println(e); e.printStackTrace(); } } else { System.out.println("Already Playing can't start another"); } ChangeButton(); } // end Play() public void Stop() { if(nowPlaying == true) { try { // System.out.println("stopped"); mp3player.close(); nowPlaying = false; nowPaused = false; audioPaused = 0; //reset the byte counter; ChangeButton(); finished = true; // System.out.println("stop finished"); musicThread.interrupt(); } catch (Exception e) { System.out.println("nothing to stop"); e.printStackTrace(); } } else if(nowPaused == true) { audioPaused = 0; nowPaused = false; nowPlaying = false; finished = true; } else { System.out.println("can't stop"); } } //end Stop(); public void Pause() { System.out.println("Paused"); try { this.audioPaused = stream.available(); // System.out.println(audioPaused); } catch (Exception e) { e.printStackTrace(); } musicThread.interrupt(); mp3player.close(); this.nowPlaying = false; this.nowPaused = true; this.finished = false; ChangeButton(); } //end Pause(); void ChangeButton() { if (nowPlaying == true) { playButton.removeActionListener(PlayMp3); playButton.addActionListener(PauseMp3); //playButton.setText("Pause"); playButton.setIcon(new ImageIcon("src\\Image\\pauseBtn2.png")); //System.out.println("1"); } else if (nowPlaying == false) { playButton.removeActionListener(PauseMp3); playButton.addActionListener(PlayMp3); playButton.setIcon(new ImageIcon("src\\Image\\playBtn2.png")); // System.out.println("2"); } else if(finished == true) { playButton.removeActionListener(PauseMp3); playButton.addActionListener(PlayMp3); playButton.setIcon(new ImageIcon("src\\Image\\playBtn2.png")); //System.out.println("2"); audioPaused = 0; } } //end ChangeButton public void CheckDuration() //works <3 { if(nowPlaying) { try{ if(!musicThread.isAlive()) { Stop(); //automaticly go to the next one; @SuppressWarnings("unchecked") Iterator<Entry<String, String>> it = playlist.mainList.get(Playlist.name).entrySet().iterator(); while(it.hasNext()) { Entry<String, String> curr = it.next(); if(curr.getKey().equals(song)) { ClickableLabel.songName = it.next().getKey(); break; } } } } catch(Exception e) { System.out.println("damn"); } } } } <file_sep>/README.md # Nebula ####alpha(centauri) __________________ Nebula is a music player (currently only supporting mp3 file format) written entirely in java. Consequently, it is cross-platform and will run on any JRE equipped system. The GUI is written in awt and swing. For the decoder I am using the [JLayer Javazoom](http://www.javazoom.net/javalayer/javalayer.html) library. This is still very much of a work in progress. __________________ ####Planned features: * Support for other codecs * flac * wav * m4a * Make the UI more liquid * Redesign the horrid looking control panel * sync files from the entire disk __________________ ####Screenshots ![picture alt](https://raw.githubusercontent.com/Dauta/Nebula/master/nebula_screen.jpg)
879f1ad15dcf09462ce40a3c8d911aa4931c2f9f
[ "Markdown", "Java" ]
5
Java
Dauta/Nebula
a56e0a026e6ddcce286d4c7640c946f65c66e9d3
8b0c416113eff6839dcc334a2eb420799694d6f9
refs/heads/master
<file_sep>Game2048.prototype = { constructor:Game2048, init:function(){ this.score = 0; this.arr = []; this.moveAble = false; $("#score").html("0"); $(".number_cell").remove(); this.creatArr(); }, creatArr:function(){ var i,j; for (i = 0; i < 4; i++) { this.arr[i] = []; for (j = 0; j < 4; j++) { this.arr[i][j] = {}; this.arr[i][j].value = 0; } } var i1,i2,j1,j2; //do{ i1=getRandom(3)//,i2=getRandom(3), j1=getRandom(3)//,j2=getRandom(3); //}while(i1==i2 && j1 == j2); this.arrValueUpdate(2,i1,j1); //this.arrValueUpdate(2,i2,j2); this.drawCell(i1,j1); //this.drawCell(i2,j2); }, drawCell:function(i,j){ var item = '<div class="number_cell pos'+i+j+'" ><a class="number_cell_con n2"><div class="span_wrap"><span>' +this.arr[i][j].value+'</span></div></a></div>'; $(".box").append(item); }, addEvent:function(){ var that = this; document.onkeydown=function(event){ var e = event || window.event || arguments.callee.caller.arguments[0]; var direction = that.direction; var keyCode = e.keyCode; switch(keyCode){ case 39: that.moveAble = false; that.moveRight(); that.checkLose(); break; case 40: that.moveAble = false; that.moveDown(); that.checkLose(); break; case 37: that.moveAble = false; that.moveLeft(); that.checkLose(); break; case 38: that.moveAble = false; that.moveUp(); that.checkLose(); break; } }; }, touchEvent:function(){ var that = this; //滑动处理 var startX, startY; document.addEventListener('touchstart',function (ev) { startX = ev.touches[0].pageX; startY = ev.touches[0].pageY; }, false); document.addEventListener('touchend',function (ev) { var endX, endY; endX = ev.changedTouches[0].pageX; endY = ev.changedTouches[0].pageY; var direction = GetSlideDirection(startX, startY, endX, endY); switch(direction) { case 0: break; case 1: that.moveAble = false; that.moveUp(); that.checkLose(); break; case 2: that.moveAble = false; that.moveDown(); that.checkLose(); break; case 3: that.moveAble = false; that.moveLeft(); that.checkLose(); break; case 4: that.moveAble = false; that.moveRight(); that.checkLose(); break; default: } }, false); }, arrValueUpdate:function(num,i,j){ this.arr[i][j].oldValue = this.arr[i][j].value; this.arr[i][j].value = num; }, newCell:function(){ var i,j,len,index; var ableArr = []; if(this.moveAble != true){ console.log('不能增加新格子,请尝试其他方向移动!'); return; } for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { if(this.arr[i][j].value == 0){ ableArr.push([i,j]); } } } len = ableArr.length; if(len > 0){ index = getRandom(len); i = ableArr[index][0]; j = ableArr[index][1]; this.arrValueUpdate(2,i,j); this.drawCell(i,j); }else{ return; } }, moveDown:function(){ var i,j,k,n; for (i = 0; i < 4; i++) { n = 3; for (j = 3; j >= 0; j--) { if(this.arr[i][j].value==0){ continue; } k = j+1; aa: while(k<=n){ if(this.arr[i][k].value == 0){ if(k == n || (this.arr[i][k+1].value!=0 && this.arr[i][k+1].value!=this.arr[i][j].value)){ this.moveCell(i,j,i,k); } k++; }else{ if(this.arr[i][k].value == this.arr[i][j].value){ this.mergeCells(i,j,i,k); n--; } break aa; } } } } this.newCell(); }, moveUp:function(){ var i,j,k,n; for (i = 0; i < 4; i++) { n=0; for (j = 0; j < 4; j++) { if(this.arr[i][j].value==0){ continue; } k = j-1; aa: while(k>=n){ if(this.arr[i][k].value == 0){ if(k == n || (this.arr[i][k-1].value!=0 && this.arr[i][k-1].value!=this.arr[i][j].value)){ this.moveCell(i,j,i,k); } k--; }else{ if(this.arr[i][k].value == this.arr[i][j].value){ this.mergeCells(i,j,i,k); n++; } break aa; } } } } this.newCell(); }, moveLeft:function(){ var i,j,k,n; for (j = 0; j < 4; j++) { n=0; for (i = 0; i < 4; i++) { if(this.arr[i][j].value==0){ continue; } k=i-1; aa: while(k>=n){ if(this.arr[k][j].value == 0){ if(k == n || (this.arr[k-1][j].value!=0 && this.arr[k-1][j].value!=this.arr[i][j].value)){ this.moveCell(i,j,k,j); } k--; }else{ if(this.arr[k][j].value == this.arr[i][j].value){ this.mergeCells(i,j,k,j); n++; } break aa; } } } } this.newCell(); }, moveRight:function(){ var i,j,k,n; for (j = 0; j < 4; j++) { n = 3; for (i = 3; i >= 0; i--) { if(this.arr[i][j].value==0){ continue; } k = i+1; aa: while(k<=n){ if(this.arr[k][j].value == 0){ if(k == n || (this.arr[k+1][j].value!=0 && this.arr[k+1][j].value!=this.arr[i][j].value)){ this.moveCell(i,j,k,j); } k++; }else{ if(this.arr[k][j].value == this.arr[i][j].value){ this.mergeCells(i,j,k,j); n--; } break aa; } } } } this.newCell(); }, mergeCells:function(i1,j1,i2,j2){ //合并 var temp =this.arr[i2][j2].value; var temp1 = temp * 2; this.moveAble = true; this.arr[i2][j2].value = temp1; this.arr[i1][j1].value = 0; $(".pos"+i2+j2).addClass('toRemove'); var theDom = $(".pos"+i1+j1).removeClass("pos"+i1+j1).addClass("pos"+i2+j2).find('.number_cell_con'); setTimeout(function(){ $(".toRemove").remove(); theDom.addClass('n'+temp1).removeClass('n'+temp).find('span').html(temp1); },200); this.score += temp1; $("#score").html(this.score); if(temp1 == 4096){ alert('人才啊!祖国的明天就靠你了^o^'); this.init(); } }, moveCell:function(i1,j1,i2,j2){ this.arr[i2][j2].value = this.arr[i1][j1].value; this.arr[i1][j1].value = 0; this.moveAble = true; $(".pos"+i1+j1).removeClass("pos"+i1+j1).addClass("pos"+i2+j2); }, checkLose:function(){ //判断游戏结束 var i,j,temp; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { temp = this.arr[i][j].value; if(temp == 0){ return false; } if(this.arr[i+1] && (this.arr[i+1][j].value==temp)){ return false; } if((this.arr[i][j+1]!=undefined) && (this.arr[i][j+1].value==temp)){ return false; } } } alert('革命尚未成功,同志仍需努力^_^'); this.init(); return true; } } //弹出自定义提示窗口 var showAlert= function(msg, url){ //弹框存在 if ( $("#alert_box").length > 0) { $('#pop_box_msg').html(msg); } else { var alertHtml = '<div id="alert_box" class="pop_box">' + '<div class="center_wrap">' + '<div class="pop_center">' + '<div class="pop_head"></div>' + '<span id="pop_box_msg">' + msg + '</span>' + '<button class="closebtn" onclick="closeAlert()">再来一次</button>' + '</div>' + '</div>' + '</div>'; $("body").append(alertHtml); } $("#alert_box").show(); if(url){ setTimeout(function(){ window.location.href = url + '?id=' + 10000*Math.random(); } , 2000 ); } } //重定义alert window.alert=showAlert; //点击遮罩关闭 function closeAlert(){ $("#alert_box").hide(); } //排行榜在这里 静静等待后台传数据 function showRanking(){ if ( $("#ranking_box").length > 0) { } else { //id名为rank_cell 的div块随用户玩获取成绩而增++ //id ranking 排名1 2 3... //id headpic 用户头像 //id name 用户名 //id score 用户成绩 // var rankingHtml = '<div id="ranking_box" class="pop_box">' + '<div class="center_wrap">' + '<div class="pop_center">' + '<div class="pop_head"><b>排行榜</b></div>' + '<div class="rank_wrap">' + '<div id="rank_cell">' + '<span id="ranking" class="ranking">1</span>' + '<img id="headpic" class="headpic">' + '<span id="name" class="name">SuperZZQ</span>' + '<span id="myscore" class="myscore"></span>' + '</div>' + '</div><div class="close" onclick="closeRanking()">+</div>' + '</div>' + '</div>' + '</div>'; $("body").append(rankingHtml); $("#myscore").html(this.score); } $("#ranking_box").show(); } function closeRanking(){ $("#ranking_box").hide(); } function GetSlideAngle(dx, dy) { return Math.atan2(dy, dx) * 180 / Math.PI; } //根据起点和终点返回方向 1:向上,2:向下,3:向左,4:向右,0:未滑动 function GetSlideDirection(startX, startY, endX, endY) { var dy = startY - endY; var dx = endX - startX; var result = 0; //滑动距离太短 if(Math.abs(dx) < 2 && Math.abs(dy) < 2) { return result; } var angle = GetSlideAngle(dx, dy); if(angle >= -45 && angle < 45) { result = 4; }else if (angle >= 45 && angle < 135) { result = 1; }else if (angle >= -135 && angle < -45) { result = 2; }else if ((angle >= 135 && angle <= 180) || (angle >= -180 && angle < -135)) { result = 3; } return result; } function getRandom(n){ return Math.floor(Math.random()*n) } function Game2048(){ this.addEvent(); this.touchEvent(); } var g = new Game2048(); g.init();
99681464a299161574de0d20fab83578136aaa1b
[ "JavaScript" ]
1
JavaScript
hao302tx/2048-
78cdac7492c4cec0152d5a1e8fcca3abb348530a
0be8f70ba0c02ebc1315af82a26529e60fba8baf
refs/heads/master
<repo_name>peterlpt/AdMonitor<file_sep>/README.md # AdMonitor 以对业务实现层最少侵入为原则,在SDK层实现对Android原生广告View的曝光监听上报、点击监听上报,做到业务层只需调用统一注册方法告知SDK层该View为广告控件,剩余功能逻辑由SDK层内部完成。 功能实现细节见:[Android原生广告曝光点击监测实现](https://ptlpt.gitee.io/android-ad-monitor/) <file_sep>/app/src/main/java/com/peter/admonitor/activity/MainActivity.java package com.peter.admonitor.activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.peter.admonitor.R; import com.peter.admonitor.manager.AdMonitorManager; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MainActivity extends AppCompatActivity { ViewPager vp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); startActivity(new Intent(MainActivity.this, ScrollingActivity.class)); } }); // ATTENTION: This was auto-generated to handle app links. Intent appLinkIntent = getIntent(); String appLinkAction = appLinkIntent.getAction(); Uri appLinkData = appLinkIntent.getData(); vp = findViewById(R.id.vp); List<View> bannerViews = new ArrayList<>(); AdInfo adInfo1 = new AdInfo(); adInfo1.adImgRes = R.mipmap.banner_ad_1; adInfo1.tvTitle = "横幅广告1"; adInfo1.landingUrl = "https://devework.com/"; adInfo1.showRptUrls = Arrays.asList("https://m.banner1.com/show1", "https://m.banner1.com/show2"); adInfo1.clickRptUrls = Arrays.asList("https://m.banner1.com/click1", "https://m.banner1.com/click2"); bannerViews.add(genBannerView(adInfo1, 1)); AdInfo adInfo2 = new AdInfo(); adInfo2.adImgRes = R.mipmap.banner_ad_2; adInfo2.tvTitle = "横幅广告2"; adInfo2.landingUrl = "https://www.jiawin.com/"; adInfo2.showRptUrls = Arrays.asList("https://m.banner2.com/show1", "https://m.banner2.com/show2"); adInfo2.clickRptUrls = Arrays.asList("https://m.banner2.com/click1", "https://m.banner2.com/click2"); bannerViews.add(genBannerView(adInfo2, 2)); AdInfo adInfo3 = new AdInfo(); adInfo3.adImgRes = R.mipmap.banner_ad_3; adInfo3.tvTitle = "横幅广告3"; adInfo3.landingUrl = "https://www.cmhello.com/"; adInfo3.showRptUrls = Arrays.asList("https://m.banner3.com/show1", "https://m.banner3.com/show2"); adInfo3.clickRptUrls = Arrays.asList("https://m.banner3.com/click1", "https://m.banner3.com/click2"); bannerViews.add(genBannerView(adInfo3, 3)); AdInfo adInfo4 = new AdInfo(); adInfo4.adImgRes = R.mipmap.banner_ad_4; adInfo4.tvTitle = "横幅广告4"; adInfo4.landingUrl = "https://peterlpt.github.io/"; adInfo4.showRptUrls = Arrays.asList("https://m.banner4.com/show1", "https://m.banner4.com/show2"); adInfo4.clickRptUrls = Arrays.asList("https://m.banner4.com/click1", "https://m.banner4.com/click2"); bannerViews.add(genBannerView(adInfo4, 4)); vp.setAdapter(new VpAdapter(bannerViews)); vp.setCurrentItem(0); AdMonitorManager.regAdView(findViewById(R.id.iv_ad), new AdMonitorManager.AdMonitorAttr() .setPlaceEventId("position_single_ad") .setAdTag("图片广告") .setIndexInfo("0") .setShowRptUrls(Arrays.asList("https://m.imgad.com/show1", "https://m.imgad.com/show2")) .setClickRptUrls(Arrays.asList("https://m.imgad.com/click1", "https://m.imgad.com/click2"))); } private View genBannerView(AdInfo adInfo, int index) { View view = LayoutInflater.from(this).inflate(R.layout.content_banner_page, null); TextView tv = view.findViewById(R.id.tv_banner_ad_title); tv.setText(adInfo.tvTitle); ImageView iv = view.findViewById(R.id.iv_banner); iv.setImageResource(adInfo.adImgRes); iv.setTag(adInfo.landingUrl); AdMonitorManager.regAdView(iv, new AdMonitorManager.AdMonitorAttr() .setPlaceEventId("position_banner") .setAdTag(adInfo.tvTitle) .setIndexInfo(String.valueOf(index)) .setShowRptUrls(adInfo.showRptUrls) .setClickRptUrls(adInfo.clickRptUrls)); return view; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void onClick(View view) { String url = "https://c7sky.com/"; switch (view.getId()) { case R.id.iv_ad: url = "https://c7sky.com/"; break; case R.id.iv_banner: url = String.valueOf(view.getTag()); break; default: break; } AdMonitorManager.onAdClick(view); Intent intent = new Intent(MainActivity.this, AdLandingActivity.class); intent.putExtra(AdLandingActivity.URL, url); startActivity(intent); } class VpAdapter extends PagerAdapter { private List<View> mViewList; public VpAdapter(List<View> mViewList) { this.mViewList = mViewList; } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { container.removeView(mViewList.get(position)); } @Override @NonNull public Object instantiateItem(ViewGroup container, int position) { container.addView(mViewList.get(position)); return (mViewList.get(position)); } @Override public int getCount() { if (mViewList == null) return 0; return mViewList.size(); } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object o) { return view == o; } } class AdInfo { @DrawableRes int adImgRes; String tvTitle; String landingUrl; List<String> showRptUrls; List<String> clickRptUrls; } }
f6d80283ff6a79982e3f6e0dab26c92fd225ae94
[ "Markdown", "Java" ]
2
Markdown
peterlpt/AdMonitor
9ecc305e4ea6bb446b37c25ae4ed3b8d3760d87c
8d832e94d01aed0cd3cd802d16dd9ef2f8255e24
refs/heads/master
<file_sep>package com.slamtheham.slampackage.commands; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; import com.slamtheham.slampackage.utils.Utils; public class MainCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (sender instanceof ConsoleCommandSender) { return true; } if (label.equalsIgnoreCase("slampackage")||(label.equalsIgnoreCase("sp"))){ String permission = "slampackage.admin"; sender.sendMessage(Utils.cc("")); } return true; } } <file_sep>package com.slamtheham.slampackage.enchants; import java.util.ArrayList; import java.util.List; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import com.slamtheham.slampackage.utils.Utils; public class Books { public static ItemStack simpleBook = new ItemStack(Material.BOOK, 1); public static ItemStack uniqueBook = new ItemStack(Material.BOOK, 1); public static ItemStack eliteBook = new ItemStack(Material.BOOK, 1); public static ItemStack ultimateBook = new ItemStack(Material.BOOK, 1); public static ItemStack legendaryBook = new ItemStack(Material.BOOK, 1); ItemMeta simpleBookMeta = simpleBook.getItemMeta(); ItemMeta uniqueBookMeta = uniqueBook.getItemMeta(); ItemMeta eliteBookMeta = eliteBook.getItemMeta(); ItemMeta ultimateBookMeta = ultimateBook.getItemMeta(); ItemMeta legendaryBookMeta = legendaryBook.getItemMeta(); public void createItems() { List<String> lore1 = new ArrayList<String>(); List<String> lore2 = new ArrayList<String>(); List<String> lore3 = new ArrayList<String>(); List<String> lore4 = new ArrayList<String>(); List<String> lore5 = new ArrayList<String>(); simpleBookMeta.setDisplayName(Utils.cc("&f&lSimple Enchantment Book &7(Right Click)")); uniqueBookMeta.setDisplayName(Utils.cc("&a&lUnique Enchantment Book &7(Right Click)")); eliteBookMeta.setDisplayName(Utils.cc("&b&lElite Enchantment Book &7(Right Click)")); ultimateBookMeta.setDisplayName(Utils.cc("&e&lUltimate Enchantment Book &7(Right Click)")); legendaryBookMeta.setDisplayName(Utils.cc("&6&lLegendary Enchantment Book &7(Right Click)")); lore1.add(Utils.cc("&7Examine to recive a random")); lore1.add(Utils.cc("&fsimple &7enchantment book.")); lore2.add(Utils.cc("&7Examine to recive a random")); lore2.add(Utils.cc("&aunique &7enchantment book.")); lore3.add(Utils.cc("&7Examine to recive a random")); lore3.add(Utils.cc("&belite &7enchantment book.")); lore4.add(Utils.cc("&7Examine to recive a random")); lore4.add(Utils.cc("&eultimate &7enchantment book.")); lore5.add(Utils.cc("&7Examine to recive a random")); lore5.add(Utils.cc("&6&llegendary &7enchantment book.")); simpleBookMeta.setLore(lore1); uniqueBookMeta.setLore(lore2); eliteBookMeta.setLore(lore3); ultimateBookMeta.setLore(lore4); legendaryBookMeta.setLore(lore5); simpleBook.setItemMeta(simpleBookMeta); uniqueBook.setItemMeta(uniqueBookMeta); eliteBook.setItemMeta(eliteBookMeta); ultimateBook.setItemMeta(ultimateBookMeta); legendaryBook.setItemMeta(legendaryBookMeta); } }
4f6eaf2a61cc6a889b73588bf777f991c559f172
[ "Java" ]
2
Java
IamWTbro/SlamPackage
92e20ef0a868bc9d04ec2d311ed3b73f52fdb661
330df0002a13863b9a31aeff880a9582efb1b901
refs/heads/master
<file_sep>#include<stdio.h> int main(){ int i,n; int large,secondLarge; int arr[20]; printf("Enter Size of Array :\n"); scanf("%d",&n); printf("Elements are : \n"); for (i = 0; i < n; i++){ scanf("%d",&arr[i]); } for(i=0;i<n;i++){ printf("Elements Are Arra[%d] = %d\n",i,arr[i]); } large = arr[0]; for(i=0;i<n;i++){ if(large < arr[i]){ large = arr[i]; } } secondLarge = arr[1]; for(i=0;i<n;i++){ if(arr[i] != large){ if (secondLarge < arr[i]){ secondLarge = arr[i]; } } } printf("Large Number is : %d\n",large); printf("Second Large Number is : %d\n",secondLarge); return 0; }<file_sep>#include <stdio.h> #include<stdlib.h> struct node{ int data; struct node* link; }; struct node* root = NULL; int len; void append(); void insert(); void display(); void delete(); int length(); void main(){ int ch; while (1) { printf("Single linked list operation:\n"); printf("1.Append :\n"); printf("2.Insert :\n"); printf("3.length :\n"); printf("4.Display :\n"); printf("5.Delete :\n"); printf("6.quite :\n"); printf("Enter your Choice :\n"); scanf("%d",&ch); switch(ch){ case 1 : append(); break; case 2 : insert(); break; case 3 : len =length(); printf("Length is : %d\n\n",len); break; case 4 : display(); break; case 5 : delete(); break; case 6 : exit(1); default : printf("invlid Choice :"); } } } void append(){ struct node* temp; temp = (struct node*)malloc(sizeof(struct node)); printf("Enter node data :"); scanf("%d",&temp->data); temp->link = NULL; if (root == NULL){ root = temp; }else{ struct node* p; p = root; while (p->link !=NULL){ p = p->link; } p->link = temp; } } int length(){ int count = 0; struct node* temp; temp = root; while (temp != NULL){ count++; temp = temp->link; } return count; } void insert(){ struct node* temp,*p; int loc; int i=1; printf("Enter location :"); scanf("%d",&loc); if(loc > length()){ printf("invalid length!!\n"); printf("Available length is : %d",len); } else{ p =root; while(i < loc){ p = p->link; i++; } temp = (struct node*)malloc(sizeof(struct node)); printf("Enter the node :"); scanf("%d",&temp->data); temp->link = p->link; p->link = temp; } } void delete(){ struct node* temp; int loc = 0; printf("Enter the Location :\n"); scanf("%d",&loc); if (loc > length()){ printf("Invalid location !"); } else if (loc == 1){ temp = root; root = temp->link; temp->link = NULL; free(temp); } else{ struct node* p = root; struct node* q; int i=1; while (i < loc-1){ p = p->link; i++; } q = p->link; p->link = q->link; q->link = NULL; free(q); } } void display(){ struct node* temp; temp = root; if (temp == NULL){ printf("Empty\n"); } else{ while(temp != NULL){ printf("%d-->",temp->data); temp = temp->link; } printf("\n\n"); } } <file_sep>#include <stdio.h> #include <stdlib.h> #define CAPACITY 5 // macro prefrocer int stack[CAPACITY],top= -1; void push(int); int pop(void); int peek(void); int traverse(void); int isEmpty(void); int isFull(void); void main(){ while(1){ int ch; int item; printf("1.PUSH\n"); printf("2.POP\n"); printf("3.PEEK\n"); printf("4.TRAVERSE\n"); printf("5.Exit\n"); printf("Enter Your Choice :"); scanf("%d",&ch); switch(ch){ case 1: printf("Enter Element :"); scanf("%d",&item); push(item); break; case 2: item = pop(); if(item == 0){ printf("Stack is UnderFlow\n"); }else{ printf("Poped Item is : %d\n",item); } break; case 3: peek(); break; case 4: traverse(); break; case 5: exit(0); break; default: printf("Invalid Input!!!!\n"); } } } void push(int item){ if (isFull()){ printf("Stack is OverFlow\n"); } else{ top++; stack[top] = item; printf("Push Element %d\n",item); } } int isFull(){ if (top == CAPACITY - 1 ){ return 1; } else{ return 0; } } int pop(){ if (isEmpty()){ return 0; } else{ return stack[top--]; } } int isEmpty(){ if (top == -1) { return 1; }else { return 0; } } int peek(){ if(isEmpty()){ printf("Stack UnderFlow\n"); }else{ printf("Peek is %d\n",stack[top]); } } int traverse(){ if(isEmpty()){ printf("Stack is overFlow\n"); }else{ int i; for(i=0;i<=top;i++){ printf("Elements are %d\n",stack[i]); } } }<file_sep>#include<stdio.h> int main(){ int i,n; int arr[20]; int total = 0; float avg = 0; printf("Enter size of Array : "); scanf("%d",&n); printf("Enter Elements :\n"); for(i=0;i<n;i++){ printf("ARRAY[%d] = ",i); scanf("%d",&arr[i]); } printf("Elements are :\n"); for(i=0;i<n;i++){ printf("Array[%d] = %d\n",i,arr[i]); } for(i=0;i<n;i++){ total = total + arr[i]; } avg = (float)total/n; printf("Total is %d\n",total); printf("Average is %f\n",avg); return 0; } <file_sep>#include <stdio.h> int main(){ int i,n,loc; int arr[20]; printf("Enter Size of Array :"); scanf("%d",&n); printf("Enter the Elements :\n"); for(i=0;i<n;i++){ printf("Array[%d] =",i); scanf("%d",&arr[i]); } printf("Enter location to Delete :"); scanf("%d",&loc); for(i=loc;i<n-1;i++){ arr[i] = arr[i+1]; } for(i=0;i<n-1;i++){ printf("Array[%d] = %d\n",i,arr[i]); } return 0; }<file_sep>#include<stdio.h> int stack[10]; int top = -1; int arr[10]; void push(int); int pop(); void main(){ int n,i,val; printf("Enter size Of Array :\n"); scanf("%d",&n); printf("Enter the Array Elements:\n"); for(i=0;i<n;i++){ printf("Array[%d] :",i); scanf("%d",&arr[i]); } for(i=0;i<n;i++){ push(arr[i]); } for(i=0;i<n;i++){ val = pop(); arr[i] = val; } printf("Reverse Array is :\n"); for(i=0;i<n;i++){ printf("%d\n",arr[i]); } } void push(int val){ stack[++top] = val; } int pop(){ return stack[top--]; }<file_sep>#include<stdio.h> int main(){ int n,i; int arr[20]; int smallest,pos; printf("Enter Size of Array :\n"); scanf("%d",&n); printf("Enter Elements :\n"); for(i=0;i<n;i++){ printf("Array[%d] =",i); scanf("%d",&arr[i]); } pos = 0; smallest = arr[0]; for(i=0;i<n;i++){ if(smallest > arr[i]){ smallest=arr[i]; pos = i; } } printf("Smallest is = %d\n",smallest); printf("Position is %d\n",pos); return 0; }<file_sep>#include <stdio.h> int main(){ int arr[100]; int i,n; printf("Enter the Size of element : "); scanf("%d",&n); for(i=0;i<n;i++){ printf("%d Element ",i); scanf("%d",&arr[i]); } for(i=0;i<n;i++){ printf("%d Element is %d\n",i,arr[i]); } return 0; }<file_sep>#include <stdio.h> int main(){ int i,n,m,loc; int a[20]; int b[20]; printf("Enter the Size First Array :\n"); scanf("%d",&n); printf("Enter First Array Element :\n"); for(i=0;i<n;i++){ scanf("%d",&a[i]); } for(i=0;i<n;i++){ printf("Array[%d] = %d\n",i,a[i]); } printf("Enter the Size second Array :\n"); scanf("%d",&m); printf("Enter Second Array Element :\n"); for(i=0;i<m;i++){ scanf("%d",&b[i]); } for(i=0;i<m;i++){ printf("Array[%d] = %d\n",i,b[i]); } printf("ENTER LOCATION :\n"); scanf("%d",&loc); for(i=n-1;i>=loc;i--){ a[i+m]=a[i]; } for(i=0;i<m;i++){ a[loc+i] = b[i]; } printf("New Elements is :\n"); for(i=0;i<n+m;i++){ printf("%d\n",a[i]); } }<file_sep>#include<stdio.h> #include<stdlib.h> struct node{ int data; struct node* right; struct node* left; }; struct node* root = NULL; void append(void); int length(void); void display(void); void addAtBegin(void); void addAtAfter(void); void delete(void); void main(){ int ch,len; while(1){ printf("Operation of Double linked list\n"); printf("1.Append\n"); printf("2.Add at Begin\n"); printf("3.length\n"); printf("4.Display\n"); printf("5.Add at after\n"); printf("6.Delete\n"); printf("7.Exit\n\n"); printf("Enter your Choice :\n"); scanf("%d",&ch); switch(ch){ case 1: append(); break; case 2: addAtBegin(); break; case 3: len = length(); printf("Length is : %d\n\n",len); break; case 4: display(); break; case 5: addAtAfter(); break; case 6: delete(); break; case 7: exit(1); default: printf("Invalid choice.....\n\n"); } } } void append(){ struct node* temp; temp = (struct node*)malloc(sizeof(struct node)); printf("Enter node data :\n"); scanf("%d",&temp->data); temp->left = NULL; temp->right = NULL; if(root == NULL){ root = temp; }else{ struct node* p; p = root; while(p->right != NULL){ p = p->right; } p->right = temp; temp->left = p; } } void addAtBegin(){ struct node* temp; temp = (struct node*)malloc(sizeof(struct node)); printf("Enter Node Data :\n"); scanf("%d",&temp->data); temp->left = NULL; temp->right=NULL; if(root == NULL){ root = temp; }else{ temp->right = root; root->left = temp; root = temp; } } int length(){ struct node* temp; int count = 0; temp = root; while(temp != NULL){ count++; temp = temp->right; } return count; } void display(){ struct node* temp; temp =root; if(temp == NULL){ printf("Empty List....\n"); }else{ while(temp != NULL){ printf("%d-->",temp->data); temp =temp->right; } printf("\n\n"); } } void addAtAfter(){ int loc,i=1; struct node* temp,*p; printf("Enter location :\n"); scanf("%d",&loc); if(loc > length()){ printf("Invalid location\n"); }else{ struct node* temp; temp = (struct node*)malloc(sizeof(struct node)); printf("Enter node Data :\n"); scanf("%d",&temp->data); temp->right = NULL; temp->left = NULL; p =root; while(loc > i){ p = p->right; i++; } temp->right = p->right; p->right->left = temp; temp->left = p; p->right = temp; } } void delete(){ struct node* temp; int loc; printf("Enter Location :\n"); scanf("%d",&loc); if(loc > length()){ printf("Invalid location\n"); }else if(loc == 1){ temp = root; root = temp->right; temp->right->left = root; temp->left = NULL; temp->right = NULL; free(temp); }else{ int i = 1; struct node* p,*r; p =root; while(i < loc - 1){ p = p->right; i++; } r = p->right; p->right = r->right; r->right->left = p; r->left = NULL; r->right = NULL; free(r); } }<file_sep>#include<stdio.h> #include<stdlib.h> struct node{ int data; struct node* link; }; struct node* root = NULL; void append(); void addatbegin(); void addatafter(); void delete(); void display(); int length(); int len; void main(){ int ch; while (1){ printf("Linked list operations\n\n"); printf("1.Append :\n"); printf("2.Add the Begginin :\n"); printf("3.Add After choice :\n"); printf("4.Display :\n"); printf("5.Delete :\n"); printf("6.length :\n"); printf("7.Exit \n"); printf("Enter your Choice :\n"); scanf("%d",&ch); switch (ch) { case 1: append(); break; case 2: addatbegin(); break; case 3: addatafter(); break; case 4: display(); break; case 5: delete(); break; case 6: len = length(); printf("length is :%d\n",len); break; case 7: exit(1); default: printf("Invalid choice :\n"); } } } void append(){ struct node* temp; temp = (struct node*)malloc(sizeof(struct node)); printf("Enter the Node Data :"); scanf("%d",&temp->data); temp->link = NULL; if (root == NULL){ root = temp; }else{ struct node* p; p = root; while (p->link != NULL){ p = p->link; } p->link = temp; } } int length(){ int count = 0; struct node* temp; temp = root; while(temp != NULL){ count++; temp = temp->link; } return count; } void display(){ struct node* temp; temp = root; if (temp == NULL){ printf("Empty list \n"); }else{ while (temp != NULL){ printf("%d-->",temp->data); temp= temp->link; } printf("\n\n"); } } void addatbegin(){ struct node* temp; temp = (struct node*)malloc(sizeof(struct node)); printf("Enter the data "); scanf("%d",&temp->data); temp->link = NULL; if (root == NULL) { root = temp; }else{ temp->link = root; root = temp; } } void addatafter(){ int i=1; int loc; struct node* temp,*p; printf("Enter location :"); scanf("%d",&loc); if (loc > length()){ printf("Invalid Locaton \n"); printf("Length is : %d\n",len); } else{ p = root; while(i < loc){ p = p->link; i++; } temp = (struct node*)malloc(sizeof(struct node)); printf("Enter node data :\n"); scanf("%d",&temp->data); temp->link = p->link; p->link = temp; } } void delete(){ int loc = 0; struct node* temp; printf("Enter the location :"); scanf("%d",&loc); if(loc > length()){ printf("Invalid Location \n"); } else if(loc == 1){ temp = root; root = temp->link; temp->link = NULL; free(temp); } else{ struct node* p = root; struct node* q; int i = 1; while(i < loc-1){ p = p->link; i++; } q = p->link; p->link = q->link; q->link = NULL; free(q); } }<file_sep>#include <stdio.h> #include<stdlib.h> #define CAPACITY 5 int queue[CAPACITY]; int front = 0; int rear = 0; void push(void); void pop(void); void traverse(void); void main(){ int ch; while(1){ printf("Queue operations !!!!\n"); printf("1.Push\n"); printf("2.Pop\n"); printf("3.Traverse\n"); printf("4.Exit\n"); printf("Enter your choice :\n"); scanf("%d",&ch); switch(ch){ case 1: push(); break; case 2: pop(); break; case 3: traverse(); break; case 4: exit(1); break; default: printf("Invalid choice!!\n"); } } } void push(){ if(CAPACITY == rear){ printf("List Full...\n"); }else{ int ele; printf("Enter data :\n"); scanf("%d",&ele); queue[rear] = ele; rear++; } } void pop(){ if(rear == front){ printf("Empty list...\n"); }else{ printf("Delete data is : %d\n",queue[front]); for(int i = 0;i<rear;i++){ queue[i] = queue[i+1]; } rear--; } } void traverse(){ if(rear == front){ printf("Empty List...\n"); }else{ printf("Queues Elements :\n"); for(int i=front;i < rear;i++){ printf("%d\n",queue[i]); } } }<file_sep>#include<stdio.h> #include<stdlib.h> struct node { int data; struct node* link; }; struct node* root = NULL; void main(){ struct node* temp; temp = (struct node*)malloc(sizeof(struct node)); printf("Enter the Data: "); scanf("%d",&temp->data); temp->link =root; if (root == NULL) { root = temp; }else { struct node* p; p = root; while (p->link != NULL) { p = p->link; } p->link =temp; } } <file_sep>#include<stdio.h> #include<stdlib.h> struct node{ int data; struct node* link; }; struct node* root = NULL; void add(void); void swap(void); void display(void); void main(){ int ch; while(1){ printf("Swaping using Link list\n\n"); printf("1.Add\n"); printf("2.Swap\n"); printf("3.Display\n"); printf("4.Exit\n"); printf("Enter your choice :"); scanf("%d",&ch); switch(ch){ case 1: add(); break; case 2: swap(); break; case 3: display(); break; case 4: exit(1); default: printf("Invalid choice !!1\n"); } } } void add(){ struct node* temp; temp = (struct node*)malloc(sizeof(struct node)); printf("Enter the Node data :\n"); scanf("%d",&temp->data); temp->link = NULL; if(root == NULL){ root =temp; }else{ struct node* p; p = root; while(p->link != NULL){ p = p->link; } p->link=temp; } } void swap(){ int loc,i=1; struct node* p,*r,*q; printf("Enter location to swap :\n"); scanf("%d",&loc); p =root; while(i < loc-1){ p = p->link; i++; } q = p->link; r = q->link; q->link = r->link; r->link = q; p->link = r; } void display(){ struct node* temp; temp =root; if(temp == NULL){ printf("Empty List\n"); }else{ while(temp != NULL){ printf("%d-->",temp->data); temp= temp->link; } printf("\n\n"); } }<file_sep>#include <stdio.h> int main(){ int n,i,loc,key; int arr[20]; printf("Enter Size Of Array :"); scanf("%d",&n); printf("Enter Element :\n"); for(i=0;i<n;i++){ scanf("%d",&arr[i]); } printf("Enter location To Add :"); scanf("%d",&loc); printf("Enter Element to Add :"); scanf("%d",&key); for(i=n-1;i>=loc;i--){ arr[i+1] = arr[i]; } arr[loc]=key; for(i=0;i<n;i++){ printf("%d\n",arr[i]); } }<file_sep>#include<stdio.h> #include<stdlib.h> struct node{ int data; struct node* link; }; struct node* top = NULL; void push(void); void pop(void); void display(void); void main(){ int ch; while(1){ printf("Single Linked list using Stack\n\n"); printf("1.PUSH\n"); printf("2.POP\n"); printf("3.DISPLAY\n"); printf("4.exit\n\n"); printf("Enter your Choice :"); scanf("%d",&ch); switch(ch){ case 1: push(); break; case 2: pop(); break; case 3: display(); break; default: printf("Invalid choice\n\n"); } } } void push(){ struct node* temp; temp = (struct node*)malloc(sizeof(struct node)); printf("Enter node Data :"); scanf("%d",&temp->data); temp->link = top; top = temp; } void display(){ struct node* temp; if(top==NULL){ printf("Stack is empty\n"); }else{ temp = top; while(temp != NULL){ printf("%d\n",temp->data); temp = temp->link; } } } void pop(){ struct node* temp; if (top == NULL){ printf("No ELIMENT\n"); }else{ temp = top ; printf("Delete : %d\n",temp->data); top = top->link ; temp->link = NULL; free(temp); } }
e21950367b1da7d13e51ff8f53ae686bed881a12
[ "C" ]
16
C
udamadu11/DATA_STRUCRURES_ALGORITHM_TUTORIAL
744bbd0217911842978236724a8876a075ec4de7
23fbe8cc8a1846a95b2e42023bebc62d32392481
refs/heads/master
<file_sep>// // test.swift // test // // Created by TTOzzi on 2020/01/08. // Copyright © 2020 TTOzzi. All rights reserved. // @testable import Problem2 import XCTest class test: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. measure { // Put the code you want to measure the time of here. } } func testCase1() { XCTAssertTrue(reverse(123) == 321) } func testCase2() { XCTAssertTrue(reverse(-123) == -321) } func testCase3() { XCTAssertTrue(reverse(120) == 21) } } <file_sep>func solution(participant: [String], completion: [String]) -> String { var participant = participant var completion = completion var index = 0 for player in participant { if completion.contains(player) { completion.remove(at: completion.firstIndex(of: player)!) participant.remove(at: index) index -= 1 } index += 1 } return participant[0] } <file_sep>func reverse(_ x: Int) -> Int { var number = x >= 0 ? x : -x var arr = [Int]() var ret = 0 var digits = 1 while number > 0 { arr.append(number % 10) number = number/10 } arr.reverse() if x >= 0 { arr.forEach { ret += $0 * digits digits *= 10 } } else { digits = -1 arr.forEach { ret += $0 * digits digits *= 10 } } return ret > 2147483647 || ret < -2147483648 ? 0 : ret }
aa977ea1c3a26142027ef7ce1a543f00f459057f
[ "Swift" ]
3
Swift
TTOzzi/Algorithm
953108f558d90d4f13ca674b8c52fecfd3c2b4bd
3bf11e71cba88780c46772f28c98805bef683eec
refs/heads/master
<repo_name>cdla/dockerfiles<file_sep>/gollum-wiki/Dockerfile From ubuntu:18.04 MAINTAINER <NAME> <<EMAIL>> ENV DEBIAN_FRONTEND noninteractive #update and upgrade RUN apt-get update RUN apt-get upgrade -y #install dependencies RUN apt-get install -y -q build-essential ruby-dev python python-docutils ruby-bundler libicu-dev libreadline-dev libssl-dev zlib1g-dev git-core # Install gollum RUN gem install gollum redcarpet github-markdown #clean up install RUN apt-get clean RUN rm -rf /var/cache/apt/archives/* /var/lib/apt/lists/* EXPOSE 4567 ENTRYPOINT ["gollum", "/docs"] <file_sep>/README.md # dockerfiles compilation of dockerfiles <file_sep>/mkdocs-wiki/docker_wrapper.sh #!/bin/bash #Wrapper script that builds the docker image and runs it. docker build -t wiki . docker run -p 8000:8000 -v docs:/docs:rw wiki serve & sleep 3; open http://localhost:8000 <file_sep>/gollum-wiki/docker_wrapper.sh #!/bin/bash #Wrapper script that builds the docker image and runs it. docker build -t neurowiki . git clone <EMAIL>:cdla/neurowiki-docs docs/ docker run -p 4567:4567 -v docs:/docs:rw neurowiki & open http://localhost:4567<file_sep>/mkdocs-wiki/Dockerfile From python:2.7-alpine RUN pip install mkdocs mkdocs-material WORKDIR /wiki ENTRYPOINT ["mkdocs"]
ae9e6ab9da5d50c0dc3d525fb2757d00ccbbea7c
[ "Markdown", "Dockerfile", "Shell" ]
5
Dockerfile
cdla/dockerfiles
54ebea4c0ca3e572a3bb45146f286bc6916ce4e7
bf58b1c15cec27cf6beb0f11b9c56866aced1731
refs/heads/main
<repo_name>iyazici94/Comp437<file_sep>/SmartAlarm/app/src/main/java/com/example/smartalarm/MorningActivity.java package com.example.smartalarm; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; public class MorningActivity extends AppCompatActivity { public Button back_button; public ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_morning); back_button = findViewById(R.id.back_btn); imageView = (ImageView) findViewById(R.id.imageView2); imageView.setImageBitmap(MyBitmapKeeper.instance.bitmap); } public void BackButton(View view) { Intent intent = new Intent(MorningActivity.this,MainActivity.class); startActivity(intent); } }<file_sep>/AlarmApp/app/src/main/java/helpers/CreateAlarmFragment.java package helpers; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TimePicker; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProviders; import androidx.navigation.Navigation; import com.learntodroid.simplealarmclock.R; import com.learntodroid.simplealarmclock.data.Alarm; import java.util.Random; import butterknife.BindView; import butterknife.ButterKnife; public class CreateAlarmFragment extends Fragment { } <file_sep>/AlarmApp/app/src/main/java/helpers/TimePickerHelper.java package helpers; // Imports import android.os.Build; import android.widget.TimePicker; public final class TimePickerHelper { public static int GetTimePickerHour(TimePicker timePicker) { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return timePicker.getHour(); } else { // For now does nothing return timePicker.getHour(); } } public static int GetTimePickerMinute(TimePicker timePicker) { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return timePicker.getMinute(); } else { return timePicker.getMinute(); } } } <file_sep>/SmartAlarm/app/src/main/java/com/example/smartalarm/MainActivity.java package com.example.smartalarm; import androidx.appcompat.app.AppCompatActivity; import android.app.TimePickerDialog; import android.content.Intent; import android.media.Ringtone; import android.media.RingtoneManager; import android.nfc.Tag; import android.os.Bundle; import android.text.format.DateFormat; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Timer; import java.util.TimerTask; import java.util.Date; public class MainActivity extends AppCompatActivity { //Initialize variables // Time picker related TextView tvTimer1; int t1Hour,t1Minute; TimePickerDialog timePickerDialog; Button stop_alarm_button; Ringtone r; MyRingToneHelper ringToneHelper; MyBitmapKeeper bitmapKeeper; // Booleans boolean isPoseSelected; protected boolean switched_to_ring_act; protected boolean switched_to_main_act; public MyPoseKeeper poseKeeper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Ringtone r = RingtoneManager.getRingtone(getApplicationContext(),RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM)); ringToneHelper = new MyRingToneHelper(r); CreateTimePickerDialog(); AlarmTimer(); if(MyPoseKeeper.instance == null) { poseKeeper = new MyPoseKeeper(); } else { poseKeeper = MyPoseKeeper.instance; } if(MyBitmapKeeper.instance == null) { bitmapKeeper = new MyBitmapKeeper(); } else { bitmapKeeper = MyBitmapKeeper.instance; } // SET BOOLEANS } // Creates the time picker dialog protected void CreateTimePickerDialog() { //Assigning variables tvTimer1 = findViewById(R.id.set_timer2); stop_alarm_button = findViewById((R.id.stopButton)); tvTimer1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(poseKeeper.isPoseSelected) { //Initialize time picker dialog timePickerDialog = new TimePickerDialog( MainActivity.this, 2, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { //Initialize hour and minute t1Hour = hourOfDay; t1Minute= minute; //Initialize calendar Calendar calendar = Calendar.getInstance(); //Set hour and minute calendar.set(0,0,0,t1Hour,t1Minute); //Set selected time on text view tvTimer1.setText(DateFormat.format("hh:mm aa",calendar)); } },12,0,false ); //Displayed previous selected time timePickerDialog.updateTime(t1Hour,t1Minute); //Show dialog timePickerDialog.show(); } else { Toast.makeText(MainActivity.this, "SELECT A POSE FIRST", Toast.LENGTH_SHORT).show(); } } }); } // Checks whether time has come for alarm public void AlarmTimer() { Timer t = new Timer(); t.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if(ReturnCurrentTime().equals(AlarmTime()) ||ringToneHelper.canPlay) { if(!ringToneHelper.isDeactivated) { ringToneHelper.canPlay = true; } ringToneHelper.MyRingtonePlay(); SwitchToRingActivity(); } else { ringToneHelper.MyRingtoneStop(); } } },0,1000); // Will check it every second } // Returns the alarm time public String AlarmTime() { String alarm_time_string = tvTimer1.getText().toString(); return alarm_time_string; } public String ReturnCurrentTime() { String current_time = DateFormat.format("hh:mm aa",Calendar.getInstance().getTime()).toString(); return current_time; } // OnClickListener for out button public void ListButton(View view) { /* r.stop(); isStopped = true; */ Intent intent = new Intent(MainActivity.this,ListActivity.class); startActivity(intent); } public void SwitchToRingActivity() { if(!switched_to_ring_act) { Intent intent = new Intent(MainActivity.this,RingActivity.class); startActivity(intent); switched_to_ring_act = true; } } public void SwitchToListActivity() { Intent intent = new Intent(MainActivity.this,ListActivity.class); startActivity(intent); } }<file_sep>/SmartAlarm/app/src/main/java/com/example/smartalarm/MyRingToneHelper.java package com.example.smartalarm; import android.media.Ringtone; public class MyRingToneHelper { public static MyRingToneHelper instance; public Ringtone r; public boolean canPlay; public boolean isDeactivated; public MyRingToneHelper(Ringtone r) { this.r = r; instance = this; } public void MyRingtonePlay() { if(canPlay) r.play(); else { r.stop(); } } public void MyRingtoneStop() { r.stop(); } } <file_sep>/SmartAlarm/app/src/main/java/com/example/smartalarm/MyPoseKeeper.java package com.example.smartalarm; public class MyPoseKeeper { public static MyPoseKeeper instance; public boolean isPoseSelected; public boolean isSmile; public boolean isHandOnChin; public boolean isThumbsUp; public boolean isWristShoulder; public MyPoseKeeper() { instance = this; isPoseSelected = false; } } <file_sep>/SmartAlarm/app/src/main/java/com/example/smartalarm/MyBitmapKeeper.java package com.example.smartalarm; import android.graphics.Bitmap; public class MyBitmapKeeper { public static MyBitmapKeeper instance; public Bitmap bitmap; public MyBitmapKeeper() { instance = this; } }
b7fd2191462ca6eef6d03daf64044d65eb30ec6d
[ "Java" ]
7
Java
iyazici94/Comp437
f003c82d1581e25abcb9fe6c6c9189f82dcbe6d2
a08bf8ee9a3324a5bbda60dbc57246527fd2858c
refs/heads/master
<file_sep><?php /** * Class definition update migrations scenario actions **/ class ws_m_1607327729_perenos_opisaniya_tovara_iz_mnozhestvennogo_svoystva_v_detalnoe_opisanie extends \WS\ReduceMigrations\Scenario\ScriptScenario { /** * Name of scenario **/ static public function name() { return "Перенос описания товара из множественного свойства в детальное описание"; } /** * Priority of scenario **/ static public function priority() { return self::PRIORITY_HIGH; } /** * @return string hash */ static public function hash() { return "23cd7b6e4801f8c20941b583a7cf24eec72e43b9"; } /** * @return int approximately time in seconds */ static public function approximatelyTime() { return 0; } /** * Write action by apply scenario. Use method `setData` for save need rollback data **/ public function commit() { CModule::IncludeModule("iblock"); $start = microtime(true); $startMemory = 0; $arSelect = [ "ID", "IBLOCK_ID", "PROPERTY_TEXTS" ]; $arFilter = [ "IBLOCK_ID" => $this->getIblockId(), "!PROPERTY_TEXTS" => false ]; $res = CIBlockElement::GetList(array(), $arFilter, false, false, $arSelect); fwrite(STDOUT, sprintf('найдено %d элементов', $res->SelectedRowsCount()) . "\r\n"); $generator = $this->makeGenerator($res, 10); $el = new CIBlockElement; fwrite(STDOUT, 'старт обновления' . "\r\n"); $cnt = 1; $ids = []; try { foreach ($generator as $request) { fwrite(STDOUT, sprintf('страница номер %d', $cnt) . "\r\n"); $cnt++; while ($res = $request->Fetch()) { if (!$res || !$res['ID']) { continue; } fwrite(STDOUT, sprintf('обновляется элемент %d', $res['ID']) . "\r\n"); $ids[$res['ID']] = $res['ID']; $el->Update( $res["ID"], [ "DETAIL_TEXT" => $res['PROPERTY_TEXTS_VALUE']['TEXT'], ] ); fwrite(STDOUT, sprintf('элемент с id:%s обновлен', $res["ID"]) . "\r\n"); } } } catch (Exception $exception) { fwrite(STDOUT, $exception->getMessage() . "\r\n"); } $this->setData(['IDS' => $ids]); $startMemory = memory_get_usage(); $time = microtime(true) - $start; fwrite(STDOUT, sprintf('время выполнения скрипта:%d', $time) . "\r\n"); fwrite(STDOUT, sprintf('потребление памяти:%d', $startMemory / (1024 * 1024) . "\r\n")); } /** * Write action by rollback scenario. Use method `getData` for getting commit saved data **/ public function rollback() { CModule::IncludeModule("iblock"); $start = microtime(true); $startMemory = 0; $data = $this->getData(); $elementsId = $data['IDS']; $el = new CIBlockElement; $arLoadProductArray = array( "DETAIL_TEXT" => "", ); try { foreach ($elementsId as $id) { $res = $el->Update($id, $arLoadProductArray); if ($res) { fwrite(STDOUT, sprintf('элемент с id:%s обновлен', $id) . "\r\n"); } else { fwrite(STDOUT, sprintf('элемент с id:%s не обновлен по причинес:%s', $id, $el->LAST_ERROR) . "\r\n"); } } } catch (Exception $exception) { fwrite(STDOUT, $exception->getMessage() . "\r\n"); } $startMemory = memory_get_usage(); $time = microtime(true) - $start; fwrite(STDOUT, sprintf('время выполнения скрипта:%d', $time) . "\r\n"); fwrite(STDOUT, sprintf('потребление памяти:%d', $startMemory / (1024 * 1024) . "\r\n")); } private function makeGenerator($selectRequest, $chunkSize) { $pageNumber = 1; $totalPages = ceil($selectRequest->SelectedRowsCount() / $chunkSize); while ($pageNumber <= $totalPages) { $selectRequest->NavStart($chunkSize, false, $pageNumber); yield $selectRequest; $pageNumber++; } } private function getIblockId() { $dbIblock = CIBlock::GetList([], ['NAME' => 'Основной каталог товаров'], false)->Fetch(); return $dbIblock['ID']; } }
bfc9b654a51fa0349319c7e14fbd9369881a5916
[ "PHP" ]
1
PHP
Skyoll/migration
eb3785edd1b9e961edc18531ab7e01439e994ea6
4a0ea4df2035bcbe9e6494198432920700b2d050
refs/heads/main
<repo_name>aramiku/iniZappts<file_sep>/README.md 4/1/21 - Projeto iniciado sem nenhum arquivo 5/1/21 - Readme.md criado. <file_sep>/AppDelegate.swift AppDelegate.swift -Alteração na ferramenta de edição do github. -Segunda alteração no arquivo. -Terceira alteração feita no macbook 13
dac4cf621384d46a1c0b33ee609b1777d459154d
[ "Markdown", "Swift" ]
2
Markdown
aramiku/iniZappts
22ac007e8bb2e5e08e4d010de67801e0a1027d34
caca235a1f40dc6c918caf2f2ba93c2599cd3033
refs/heads/master
<repo_name>ins-amu/cluster<file_sep>/matlab-to-update/compile.sh #!/bin/bash if [[ -z "$MATLAB" ]] then MATLAB=/soft/matlab2015a fi mainscript=$1 if [[ -z "$mainscript" ]] then echo "please provide a script to compile." exit 1 fi echo "starting MATLAB.." $MATLAB/bin/matlab -nojvm <<EOF fprintf('compiling $1..\n'); mcc -m $1 fprintf('compilation complete. MCR installer for this version is here:\n'); mcrinstallerfile EOF <file_sep>/ssh.md # SSH SSH is the protocol usually used to access the cluster. It allows access to a command line and optionally to run graphical programs on the cluster, with the GUI showing on your computer. ## Connecting The first step in using the cluster is connecting. How to connect depends on your operating system. ### Windows First download [PuTTY](http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html) Then fill the cluster IP address `192.168.127.12` followed by your username and password. ### Mac OS X ```bash ssh [email protected] ``` ### Linux ```bash ssh [email protected] ``` ## Tips for Mac/Linux To make things faster when logging in, you can use the following tricks with SSH: ### Define cluster host in `~/.ssh/config` To avoid typing `[email protected]` all the time, you can add an entry to the `.ssh/config` file (create the file if it doesn't exist): ``` Host cluster HostName 192.168.127.12 User user ``` Now you simply type `ssh cluster` and bingo you're in. ### Setup an authorized key Set up an SSH key if you don't already have one: ```bash mycomputer $ ssh-keygen ...... ``` This will set up a private-public key pair. Next, put the public key in the `.ssh/authorized_keys` file on the cluster. ```bash mycomputer $ cat .ssh/id_rsa.pub | ssh [email protected] 'cat - >> ~/.ssh/authorized_keys' <enter password> ``` Now, `ssh [email protected]` should not require password. NB: this is the same key you copy onto GitHub to automate access to your repositories there (if you use GitHub). <file_sep>/matlab-to-update/oarsub.sh #!/bin/bash # submit jobs to OAR # build params file rm -f params.txt for i in $(seq 1 10); do # these are args to mymain.m echo 100 1.5 >> params.txt done # submit oarsub -l walltime=00:05:00 --array-param-file params.txt ./oarjob.sh <file_sep>/matlab-to-update/oarjob.sh #!/bin/bash mcr=/soft/matlab-r2015a-mcr/v85 bash run_mymain.sh $mcr $@ <file_sep>/README.md # ins-amu cluster This repo contains documentation and examples for using the cluster. <file_sep>/matlab-to-update/README.md # Using MATLAB on the cluster MATLAB can be used on the cluster by first compiling your main script and then running it with the MATLAB Compiler Runtime (MCR). This folder contains a working demo of how to do this: - `mymain.m` - main MATLAB script for this example - `params.txt` - list of parameter values per job to run `mymain.m` with - `compile.sh` - Bash script which compiles your main MATLAB script - `oarjob.sh` - Bash script to run a single job - `oarsub.sh` - Bash script to submit all jobs When you have modified `mymain.m`, you need to run `compile.sh`. When the compilation is done, you can run `oarsub.sh` to submit your jobs.
485a571f4976ca2f1d831ba3e5df96c894dcc7b3
[ "Markdown", "Shell" ]
6
Shell
ins-amu/cluster
ba873a357dece073e716f38a49b8d907589d5e63
30b277d7e4cf3ad79d2510693bc8a6b3b1a96303
refs/heads/master
<file_sep># mouse_embryonic_miRNAs The miRNA-mRNA analysis during mouse embryonic development <file_sep> # reading the expression data and the cluster info miRNAclusters = read.delim("miRNA_clusters_16.txt",header = FALSE, stringsAsFactors = FALSE) colnames(miRNAclusters) = c("Symbol","cluster.number") mRNAclusters = read.delim("mRNA_clusters_30.txt",stringsAsFactors = FALSE,header = FALSE) # these clusters are with stringTie ids: MSTRG# colnames(mRNAclusters) = c("Symbol","cluster.number") mRNAtpms <- read.table("gene.tpm.modified.txt", header=T, row.names = "Symbol") miRNAtpms <- read.csv("CPMs.TMMnormalized.modified.csv", header=T, row.names = "Symbol") miRNAtpms <- miRNAtpms + 0.1 miRNAtpms[,colnames(miRNAtpms) %in% paste0("t",seq(1,48))] = NA # Reading the design matrix and sample file edesignfile <- read.csv("miRNA.maSigPro.design.csv", header=TRUE, stringsAsFactors = F) samples <- read.csv("miRNA_samples.all.modified.csv", header=TRUE, stringsAsFactors = F) colors = cbind(c("forebrain","#800000"),c("midbrain","#B22222"),c("hindbrain","#DC143C"),c("neural.tube","#FF8C00"),c("cranioface","gold"),c("liver", "#9370DB"),c("heart","#31a354"),c("kidney","#0000FF"),c("lung","green2"),c("intestine","#1E90FF"),c("stomach","#40E0D0"),c("limb","#EE82EE")) colnames(colors) = colors[1,] #averaging the expressions for each cluster over each sample point miRNA.tpms = matrix(0, ncol = 16,nrow = 96) for(i in 1:length(unique(miRNAclusters$cluster.number))){ for(j in 1:96){ miRNA.tpms[j,i] = median(apply(miRNAtpms[miRNAclusters[which(miRNAclusters$cluster.number == i),1],(2*j-1):(2*j)],1,function(x) mean(as.numeric(x))),na.rm = TRUE) } } mRNA.tpms = matrix(0, ncol = 30,nrow = 96) for(i in 1:30){ for(j in 1:96){ mRNA.tpms[j,i] = median(apply(mRNAtpms[mRNAclusters[which(mRNAclusters$cluster.number == i),1],(2*j-1):(2*j)],1,function(x) mean(as.numeric(x))),na.rm = TRUE) } } #calculating the standard deviations for each cluster across different stages tissues = unique(edesignfile$tissue) stdevMat = as.data.frame(matrix(0, max(miRNAclusters$cluster.number),length(tissues)),colnames = tissues) for(i in 1:length(unique(miRNAclusters$cluster.number))){ for(j in 1:length(tissues)){ s = (which(samples$tissue == tissues[j])) s = round((s[seq(1,length(s),2)]+1)/2) stdevMat[i,j] = sd(miRNA.tpms[s,i],na.rm = TRUE) } } # drawing the tissue specificity heatmap library("gplots") png("tissueSpecificity.png", width=5, height=5, units="in", res=300) heatmap.2(apply(stdevMat,2,function(x) as.numeric(x)),scale = "row",Rowv = FALSE, Colv = FALSE,colsep = 1:12,rowsep = 1:max(miRNAclusters$cluster.number),ColSideColors = c(colors[2,as.character(unique(tissues))]), sepwidth = c(0.02,0.05), sepcolor = "purple",na.color = "grey",margin=c(8, 4),xlab = "Tissues", ylab = "Clusters",main = "Tissue specificity matrix",col = bluered,tracecol = NA,key = FALSE,labCol = as.character(unique(tissues))) dev.off() # defining tissue specificity matrix scaled_stdev = scale(t(stdevMat),center = TRUE) scaled_stdev[scaled_stdev>=0]<- 1 scaled_stdev[scaled_stdev<0] <- 0 tissue.specificity = c() for(i in 1:12){ tissue.specificity = c(tissue.specificity, rep(scaled_stdev[i,],8)) } tissue.specificity = matrix(tissue.specificity,nrow =8*12,ncol = length(unique(miRNAclusters$cluster.number)),byrow = TRUE) # calculating the partial correlations between miRNA clusters and mRNA clusters tissue.specificity[tissue.specificity == 1] = TRUE tissue.specificity[is.na(tissue.specificity)] = FALSE corMat = matrix(0, ncol = 30,nrow = length(unique(miRNAclusters$cluster.number))) for(i in 1:length(unique(miRNAclusters$cluster.number))){ X = miRNA.tpms[as.logical(tissue.specificity[,i]),i] corMat[i,] = cor(X,mRNA.tpms[as.logical(tissue.specificity[,i]),],use = "pairwise.complete.obs") } # drawing the heatmap for the partial correlation matrix png("SelectiveCorrelation.png", width=9, height=6, units="in", res=300) heatmap.2(apply(corMat,2,function(x) as.numeric(x)),margins = c(5,5),Rowv = FALSE, Colv = FALSE,trace="none",dendrogram = 'none',density.info = "none",colsep = 1:30,rowsep = 1:length(unique(miRNAclusters$cluster.number)), sepwidth = c(0.02,0.05), sepcolor = "black",na.color = "grey",xlab = "mRNA Clusters", ylab = "miRNA Clusters",col = colorpanel(5,"#f03b20","#bcbddc","#dadaeb"),tracecol = NA,main = "Partial correlation of miRNA-mRNA clusters",labCol = paste0("gC",1:30),labRow = paste0("miC",1:length(unique(miRNAclusters$cluster.number))),key = TRUE,keysize = 1,key.par=list(mar=c(3.5,0,3,0)),key.xtickfun=function() { breaks <- parent.frame()$breaks return(list( at=parent.frame()$scale01(c(breaks[1], breaks[length(breaks)])), labels=c(as.character(breaks[1]), as.character(breaks[length(breaks)])) )) },key.xlab = "Correlation Coefficient",key.title = "Pearson Correlation") dev.off() save(tissue.specificity,corMat,miRNA.tpms,mRNA.tpms,file = "correlations_16miRC.RData") <file_sep># miRNAtap compiles the predicted targets of the miRNAs for library(miRNAtap) library(gplots) #reading the mRNA and miRNA clusters miRNAclusters = read.delim("miRNA_clusters_16.txt",header = FALSE, stringsAsFactors = FALSE) colnames(miRNAclusters) = c("Symbol","cluster.number") mRNAclusters = read.delim("mRNA_clusters_30.txt",stringsAsFactors = FALSE,header = FALSE) colnames(mRNAclusters) = c("Symbol","cluster.number") # Reading the Ensembl to ID mapping file entrezMap = read.delim("gencode.vM10.metadata.EntrezGene",stringsAsFactors = FALSE,header = FALSE) colnames(entrezMap) = c("Symbol","Entrez.ID") # geneMap has the Ensambl ids for the mRNAs geneMap = read.delim("StringTie_geneNames_CommonNames.txt",stringsAsFactors = FALSE,header = FALSE) colnames(geneMap) = c("Symbol","Ensambl","Name") z = merge(mRNAclusters,geneMap, by = "Symbol") mRNAclusters = merge(z,entrezMap, by.x = 3,by.y = 1) # targets is a list with the size of miC# x gC which holds the target list for each miCxgC interaction targets = list() for (i in 1:length(unique(miRNAclusters$cluster.number))){ targets[[i]] = list() for (l in 1:length(unique(mRNAclusters$cluster.number))){ targets[[i]][[l]] = data.frame(matrix(ncol = 8)) colnames(targets[[i]][[l]]) = c("Entrez.ID", "miR.Symbol", "rank_product","rank_final","Ensambl","Symbol","cluster.number","Name") } # going through the miRNAs in each cluster to get the predicted targets and compile them for (mirna in miRNAclusters[miRNAclusters$cluster.number == i,1]) { # miRNAtap uses 5 different resources for target prediction p <- getPredictedTargets(mirna, species = 'mmu',method = 'geom',min_src = 3,synonyms = TRUE) if(is.null(p)){ print(paste("jumping for no prediction for:",mirna)) next } p = as.data.frame(p) p$rank_final = p$rank_final/max(p$rank_final) r = cbind(rownames(p),mirna,p[,c("rank_product","rank_final")]) colnames(r) = c("Entrez.ID", "miR.Symbol","rank_product","rank_final") # distributing the targets of each miRNA between different mRNA clusters for (j in 1:length(unique(mRNAclusters$cluster.number))){ mRNAcluster = mRNAclusters[mRNAclusters$cluster.number == j,] c = merge(r,mRNAcluster,by = "Entrez.ID") if(!all(isEmpty(c))){ targets[[i]][[j]] = rbind(targets[[i]][[j]], c) } } } } # counting the unique number of target mRNAs in each interactions mRNAt = data.frame(matrix(ncol = length(unique(mRNAclusters$cluster.number)),nrow = length(unique(miRNAclusters$cluster.number)))) mRNAn = c() for (i in 1:length(unique(miRNAclusters$cluster.number))){ for (j in 1:length(unique(mRNAclusters$cluster.number))){ mRNAn[j] = length(mRNAclusters[mRNAclusters$cluster.number == j,1]) mRNAt[i,j] = length(unique(targets[[i]][[j]]$Entrez.ID)) } } # calculating the contingency table and the PValues for the Chi-square test PVals = data.frame(matrix(ncol = length(unique(mRNAclusters$cluster.number)),nrow = length(unique(miRNAclusters$cluster.number)))) for (i in 1:length(unique(miRNAclusters$cluster.number))){ for (j in 1:length(unique(mRNAclusters$cluster.number))){ contigencyTable = rbind(c(mRNAt[i,j],sum(mRNAt[i,])-mRNAt[i,j]),c(mRNAn[j]-mRNAt[i,j],sum(mRNAn[-j])-sum(mRNAt[i,])+mRNAt[i,j])) test = chisq.test(contigencyTable) PVals[i,j] = test$p.value } } # plotting the -log10 of the P-value x = apply(-log10(PVals),2,function(x) as.numeric(as.character(x))) breaks = c(0,4.2,6,8,10,12) png("chisq-Pvals.png", width=9, height=6, units="in", res=300) par(mar=c(4,4,1,1)) rownames(x) = paste0("miC",1:length(unique(miRNAclusters$cluster.number))) colnames(x) = paste0("gC",1:length(unique(mRNAclusters$cluster.number))) heatmap.2(x,Rowv = NA,Colv = NA,trace="none",dendrogram = 'none',density.info = "none",colsep = 0:length(unique(mRNAclusters$cluster.number)),rowsep = 0:length(unique(miRNAclusters$cluster.number)),sepcolor = "black", col = colorpanel(5,"#dadaeb","#9e9ac8","#54278f"),key = TRUE,xlab = "mRNA Clusters", ylab = "miRNA Clusters",key.ylab = "P-Values(-log10)",keysize = 1,key.par=list(mar=c(3.5,0,3,0)),key.xtickfun=function() { breaks <- parent.frame()$breaks return(list( at=parent.frame()$scale01(c(breaks[1], breaks[length(breaks)])), labels=c(as.character(breaks[1]), as.character(breaks[length(breaks)])) )) },key.xlab = "P-Values",main = "Target Enrichment (Chi-sq)") dev.off() save(targets,mRNAt,mRNAt,PVals,file = "predictionTargets.RData") <file_sep># Running maSigPro on miRNAs in hpc library(maSigPro) library(ggplot2) edesignfile <- read.csv("mRNA.maSigPro.design.csv", header=TRUE, stringsAsFactors = F) ## make experimental design time <- edesignfile$time replicates <- edesignfile$reps forebrain <- edesignfile$forebrain midbrain <- edesignfile$midbrain hindbrain <- edesignfile$hindbrain cranioface <- edesignfile$cranioface neural.tube <- edesignfile$neural.tube liver <- edesignfile$liver heart <- edesignfile$heart limb <- edesignfile$limb stomach <- edesignfile$stomach intestine <- edesignfile$intestine kidney <- edesignfile$kidney lung <- edesignfile$lung samples <- edesignfile$Sample ss.edesign <- cbind(time,replicates,forebrain, midbrain, hindbrain, cranioface, neural.tube, liver, heart , limb, stomach, intestine, kidney, lung) rownames(ss.edesign) <- paste(edesignfile$Sample) design <- make.design.matrix(ss.edesign, degree=3) ## read the miRNA file and filter the miRNAs with zero variation across the experiments data.counts = read.delim("gene.counts.txt", row.names="Symbol") # remove the spike ins data.counts = data.counts[,colnames(data.counts) %in% edesignfile$Sample] data.filtered = data.counts[apply(data.counts,1,var,na.rm = TRUE) != 0,] data.t <- data.filtered + 0.1 datap <- p.vector(data.t, design = design, counts = FALSE) # find the significant genes datat <- T.fit(datap, alfa = 0.01) # find the significant differences # saving the maSigpro regressed data save(datat,file = "mRNA_maSigPro_TMM.RData") get<-get.siggenes(datat,rsq=0.7, vars="all") # get the list of significant genes x <- see.genes(get$sig.genes,k=30)$cut y <- data.frame(x) write.table(y,"mRNA_clusters_30.txt", sep="\t", quote=FALSE, col.names=FALSE) colors = cbind(c("forebrain","#800000"),c("midbrain","#B22222"),c("hindbrain","#DC143C"),c("neural.tube","#FF8C00"),c("cranioface","gold"),c("liver", "#9370DB"),c("heart","#31a354"),c("kidney","#0000FF"),c("lung","green2"),c("intestine","#1E90FF"),c("stomach","#40E0D0"),c("limb","#EE82EE")) colors = t(colors) rownames(colors) = colors[,1] samples <- read.csv("mRNA_samples.all.modified.csv", header=TRUE, stringsAsFactors = F) tpms <- read.delim("gene.tpm.modified.txt", header=T, row.names = "Symbol") tpms <- tpms + 0.1 tpms[,colnames(tpms) %in% paste0("t",seq(1,48))] = NA # plotting the miRNA cluster profiles for (clust in 1:30){ cluster <- rownames(y)[y$x == clust] cluster.data <- tpms[cluster,] med <- apply(cluster.data, 2, median) tissues <- c() medians <- c() std.err <- c() for (tissue in unique(edesignfile$tissue)){ tissue.medians <- med[samples$tissue == tissue] list.split <- split(tissue.medians, ceiling(seq_along(tissue.medians)/2)) f.d <- c() se <- c() for (i in list.split){ f.d <- c(f.d, mean(i)) se <- c(se, sd(i)/sqrt(2)) } tissues <- c(tissues , rep(tissue,8)) medians <- c(medians, f.d) std.err <- c(std.err, se) } Tissues <- Tissue <- factor(tissues, levels=c("forebrain","midbrain","hindbrain","neural.tube", "cranioface","liver", "heart","kidney","lung","intestine" ,"stomach","limb")) df <- data.frame(tissue = Tissues, time=rep(c(10.5,11.5,12.5,13.5,14.5,15.5,16.5,18.5),12), medians = medians, se = std.err) df <- na.omit(df) clust.name <- plot_num <- paste("cluster",clust,": ",length(cluster), " genes",sep = "") p <- ggplot(df, aes(x=time, y=medians, group=tissue, color = tissue)) + geom_line() + geom_point()+ geom_errorbar(aes(ymin=medians-se, ymax=medians+se), width=.8, position=position_dodge(0.0))+ #labs(y="",x="",title = clust.name) labs(y="Median profile (TPM)",x="Developmental stage",title = clust.name) p <- p + theme(text = element_text(size = 20)) #p <- p + geom_line(aes(size = 0)) #p <- p + theme_bw() p <- p + theme_bw() p <- p + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.line = element_line(colour = "black")) p <- p + scale_color_manual(values = as.character(colors[unique(df$tissue),2]), guide = F) p <- p + theme(axis.text=element_text(size=20), axis.title=element_text(size=20, face = "bold"),plot.title = element_text(size=25) ) p <- p + scale_x_discrete(limit = c(10.5,11.5, 12.5, 13.5, 14.5, 15.5, 16.5,18.5), labels = c("e10.5","e11.5","e12.5", "e13.5", "e14.5", "e15.5", "e16.5","P0"), expand = c(0.05, 0.05)) print(p) plot_num <- paste("cluster",clust,".pdf",sep="") assign(paste("fig",clust,sep=""),p) } require(gridExtra) grid.arrange(fig1,fig2,fig3,fig4,fig5,fig6,fig7,fig8,fig9,fig10,fig11,fig12, fig13,fig14,fig15,fig16,fig17,fig18,fig19,fig20,fig21,fig22,fig23, fig24,fig25,fig26,fig27,fig28,fig29,fig30, ncol=4) dev.print(pdf, paste0('miRNA_clusters_',16,'.pdf'),width = 50, height = 60) <file_sep> library(ggplot2) require(gridExtra) #reading the gene and miRNA clusters with parsing to match the targetfinding method miRNAclusters = read.delim("miRNA_clusters_16.txt",header = FALSE, stringsAsFactors = FALSE) colnames(miRNAclusters) = c("Symbol","cluster.number") mRNAclusters = read.delim("mRNA_clusters_30.txt",stringsAsFactors = FALSE,header = FALSE) colnames(mRNAclusters) = c("Symbol","cluster.number") mRNAtpms <- read.table("gene.tpm.modified.txt", header=T, row.names = "Symbol") miRNAtpms <- read.csv("CPMs.TMMnormalized.modified.csv", header=T, row.names = "Symbol") miRNAtpms <- miRNAtpms + 0.1 # pseudo counts miRNAtpms[,colnames(miRNAtpms) %in% paste0("t",seq(1,48))] = NA # dealing with the missing data labeled as t1 to t48 # averaging the experessions for each cluster at each of the time-stage points miRNA.tpms = matrix(0, ncol = 16,nrow = 96) for(i in 1:length(unique(miRNAclusters$cluster.number))){ for(j in 1:96){ miRNA.tpms[j,i] = median(apply(miRNAtpms[miRNAclusters[which(miRNAclusters$cluster.number == i),1],(2*j-1):(2*j)],1,function(x) mean(as.numeric(x))),na.rm = TRUE) } } mRNA.tpms = matrix(0, ncol = 30,nrow = 96) for(i in 1:30){ for(j in 1:96){ mRNA.tpms[j,i] = median(apply(mRNAtpms[mRNAclusters[which(mRNAclusters$cluster.number == i),1],(2*j-1):(2*j)],1,function(x) mean(as.numeric(x))),na.rm = TRUE) } } # loading the correlation matrix (corMat), tissue specificity (tissue.specificity) and the cluster means of mRNA and miRNA expressions (mRNA.tpms and miRNA.tpms) load("~/Documents/MortazaviLab/Integration/FinalCodes/correlations_16miRC.RData") #loading the target prediction matrix (PVals and targets) load("~/Documents/MortazaviLab/Integration/FinalCodes/predictionTargets.RData") # selecting the interaction with significant enrichment sigInteractions = arrayInd(which(PVals < 0.05/30/length(unique(miRNAclusters$cluster.number))),c(length(unique(miRNAclusters$cluster.number)),30)) samples <- read.csv("miRNA_samples.all.modified.csv", header=TRUE, stringsAsFactors = F) Tissues <- factor(samples$tissue[seq(1,192,2)],levels=c("forebrain","midbrain","hindbrain","neural.tube", "cranioface","liver", "heart","kidney","lung","intestine" ,"stomach","limb")) Stages <- rep(c(10.5,11.5,12.5,13.5,14.5,15.5,16.5,18.5),12) colors = cbind(c("forebrain","#800000"),c("midbrain","#B22222"),c("hindbrain","#DC143C"),c("neural.tube","#FF8C00"),c("cranioface","gold"),c("liver", "#9370DB"),c("heart","#31a354"),c("kidney","#0000FF"),c("lung","green2"),c("intestine","#1E90FF"),c("stomach","#40E0D0"),c("limb","#EE82EE")) colnames(colors) = colors[1,] colors = colors[,unique(Tissues)] # iterating through the significant interactions with negative correlation to plot the miRNA-mRNA expression side-by-side for(i in 1:length(unique(miRNAclusters$cluster.number))){ for(j in 1:length(unique(mRNAclusters$cluster.number))){ if(PVals[i,j]<0.05/30/length(unique(miRNAclusters$cluster.number)) && corMat[i,j]<0){ df <- data.frame(tissue = Tissues, time= Stages,miRNA = miRNA.tpms[,i],mRNA = mRNA.tpms[,j]) df <- na.omit(df) p <- ggplot(df, aes(x=time, y=miRNA, group=tissue, color=tissue)) + geom_line() + geom_line(data = df[df$tissue %in% Tissues[tissue.specificity[,i]==1],],size = 1.5) + scale_y_log10()+ labs(y="Median profile (logCPM)",x="Developmental stage",title = paste0("miRNA Cluster",i," (",length(unique(miRNAclusters[miRNAclusters$cluster.number == i,1])) ," miRNAs)")) p <- p + theme(text = element_text(size = 20)) p <- p + theme_bw() p <- p + scale_color_manual(values = colors[2,], guide = F) p <- p + theme(axis.text=element_text(size=9), axis.title=element_text(size=12),plot.title = element_text(size=12) ) p <- p + scale_x_discrete(limit = c(10.5,11.5, 12.5, 13.5, 14.5, 15.5, 16.5,18.5), labels = c("e10.5","e11.5","e12.5", "e13.5", "e14.5", "e15.5", "e16.5","P0"), expand = c(0.05, 0.05)) print(p) assign("mifig1",p) p <- ggplot(df, aes(x=time, y=mRNA, group=tissue, color=tissue)) + geom_line() + geom_line(data = df[df$tissue %in% Tissues[tissue.specificity[,i]==1],],size = 1.5)+ scale_y_log10()+ labs(y="Median profile (logCPM)",x="Developmental stage",title = paste0("mRNA Cluster",j," (",length(unique(mRNAclusters[mRNAclusters$cluster.number == j,1])) ," genes)")) p <- p + theme(text = element_text(size = 20)) p <- p + theme_bw() p <- p + scale_color_manual(values = colors[2,], guide = F) p <- p + theme(axis.text=element_text(size=9), axis.title=element_text(size=12),plot.title = element_text(size=12) ) p <- p + scale_x_discrete(limit = c(10.5,11.5, 12.5, 13.5, 14.5, 15.5, 16.5,18.5), labels = c("e10.5","e11.5","e12.5", "e13.5", "e14.5", "e15.5", "e16.5","P0"), expand = c(0.05, 0.05)) print(p) assign("mfig1",p) grid.arrange(mifig1,mfig1, ncol=2) dev.print(pdf, paste0('miR',i,'-','gene',j,'_log.pdf'),width = 7.5, height = 3) } } } ######################### GO analysis geneMap = read.delim("StringTie_geneNames_CommonNames.txt",stringsAsFactors = FALSE,header = FALSE) colnames(geneMap) = c("Symbol","Ensambl","Name") # writting the input files for the metascape analysis at "http://metascape.org/gp/index.html#/main/step1" for(n in 1:dim(sigInteractions)[1]){ targetlist = targets[[sigInteractions[n,1]]][[sigInteractions[n,2]]][-1,] mRNAs = unique(targetlist$Symbol) write.table(unique(geneMap[which(geneMap$Symbol %in% mRNAs),3]),paste0("target",sigInteractions[n,1],"-",sigInteractions[n,2],".csv"),sep = ",",quote = FALSE,row.names = FALSE,col.names = FALSE) } # Once the GO analysis was run on the Metascape server the result table was saved with the following format and read for enrichment analysis # "miC#-gC#_metascape_result.xlsx" library(readxl) # using the output of the Metascape analysis to plot the enriched terms for(n in 1:dim(sigInteractions)[1]){ miR = sigInteractions[n,1] gene = sigInteractions[n,2] test = read_excel(paste0(miR,"-",gene,"_metascape_result.xlsx"), sheet = 2) test = test[!duplicated(test$Description),] test = test[order(test$LogP,decreasing = TRUE),] test$Description = factor(test$Description,levels = test$Description) test = test[order(test$LogP,decreasing = FALSE),] test$colors[test$LogP < -4] = "#dadaeb" test$colors[test$LogP < -6] = "#9e9ac8" test$colors[test$LogP < -12] = "#54278f" png(paste0(miR,"-",gene,"_metascape_GO1.png"), width=9, height=6, units="in", res=300) ggplot(test[1:15,], aes(x=Description, y=-LogP)) + geom_bar(stat='identity',fill = rev(test$colors[1:15]),color="black") + scale_y_continuous(limits=c(0,17))+ coord_flip()+ theme(axis.text = element_text(size = 10),axis.title=element_text(size=12)) dev.off() }
a9ee7fdfc4c263d3cd6a6dbf763f45930f29d543
[ "Markdown", "R" ]
5
Markdown
sorenar/mouse_embryonic_miRNAs
eb2dc92f512377d04c4faf26a599f21e134d9b8c
2d0afb3c884abe4c75a9a308596f13ca2f8eb2e3
refs/heads/master
<repo_name>bomzlab/study_go<file_sep>/src/model/comms/Interfaces.go package comms import () type GetMap interface { Get(s string) string } <file_sep>/src/main/Test6.go package main import ( "fmt" m "parsetest" ) func main6() { v := m.ToInt("3") fmt.Println("toInt :: ", v) s := m.ToString(33) fmt.Println("toString :: ", s) } <file_sep>/src/main/TestIntMap.go package main import ( "fmt" mp "model/maps" ) func maina() { fmt.Println("intMap test") m := mp.NewIntMap() m.Add(3, "good") key := 3 fmt.Println("key ", key, " , value = ", m.Get(key)) } <file_sep>/src/main/Test16.go package main import ( "fmt" bmap "model/maps" ) func main16() { // m := bmap.NewSyncMap() // fmt.Println("count %d", m.Count()) // // m.Set("king", "kong") // fmt.Println("count %d", m.Count()) m := bmap.NewBomzStyleMapInstance() printMap(m) m.Add("good", "bye") printMap(m) fmt.Println("get :: ", m.Get("good")) fmt.Println("get :: ", m.Get("good1")) } func printMap(m bmap.BomzMap) { fmt.Println(m, " , count : ", m.Count()) } <file_sep>/src/model/maps/BomzSyncMap.go package maps import () const ( set = iota get remove count ) type syncMap struct { m map[string]interface{} c chan command } type command struct { key string value interface{} action int result chan<- interface{} } func NewSyncMap() syncMap { m := syncMap{ m: make(map[string]interface{}), c: make(chan command), } go m.run() return m } func (m syncMap) run() { for cmd := range m.c { switch cmd.action { case set: m.m[cmd.key] = cmd.value case get: v, ok := m.m[cmd.key] cmd.result <- [2]interface{}{v, ok} case remove: delete(m.m, cmd.key) case count: cmd.result <- len(m.m) } } } func (m syncMap) Set(k string, v interface{}) { m.c <- command{action: set, key: k, value: v} } func (m syncMap) Get(k string) (interface{}, bool) { callback := make(chan interface{}) m.c <- command{action: get, key: k, result: callback} result := (<-callback).([2]interface{}) return result[0], result[1].(bool) } func (m syncMap) Remove(k string) { m.c <- command{action: remove, key: k} } func (m syncMap) Count() int { callback := make(chan interface{}) m.c <- command{action: count, result: callback} return (<-callback).(int) } <file_sep>/src/model/sets/Sets.go package sets import () type BomzSet interface { Add(interface{}) Contains(interface{}) bool Count() int Values() []interface{} Remove(interface{}) } <file_sep>/src/model/sets/BomzNonSyncSet.go package sets import () type bomzNonSyncSet struct { m map[interface{}]bool } func NewNonSyncSet() bomzNonSyncSet { set := bomzNonSyncSet{ m: make(map[interface{}]bool), } return set } func (set bomzNonSyncSet) Add(v interface{}) { set.m[v] = true } func (set bomzNonSyncSet) Contains(v interface{}) bool { r := set.m[v] return r } func (set bomzNonSyncSet) Count() int { return len(set.m) } func (set bomzNonSyncSet) Values() []interface{} { var result []interface{} for k, _ := range set.m { result = append(result, k) } return result } func (set bomzNonSyncSet) Remove(v interface{}) { delete(set.m, v) } <file_sep>/src/main/Test18Sub.go package main import ( "bufio" "fmt" "net" "time" ) func handleClient(client net.Conn) { defer func() { client.Close() fmt.Println("client call close") }() reader := bufio.NewReader(client) var data []byte = make([]byte, 300) for { // size, err := client.Read(data) size, err := reader.Read(data) fmt.Println("client read size :: ", size, " <<>> ", len(data)) if err != nil { fmt.Println("client close. ", err) break } if size < 0 { fmt.Println("client read size error : ", size) break } if size == 0 { time.Sleep(500 * time.Millisecond) continue } fmt.Println("read size :: ", size, " , data :: ", string(data[:size])) } } <file_sep>/src/main/Test14.go package main import ( "fmt" "runtime" "sync" "sync/atomic" ) const MAX_LOOP = 1000 type counter struct { i int64 lock sync.Mutex once sync.Once } func (c *counter) increment() { // 1번만 실행하는 락 c.once.Do(func() { fmt.Println("once call") }) atomic.AddInt64(&c.i, 1) // 해당 처리가 될때는 시간당 cpu 분할 처리를 하지 않는다 // sync.Mutex 를 이용한 방법 // c.lock.Lock() // c.i += 1 // c.lock.Unlock() } func (c *counter) display() { fmt.Println("display :: ", c.i) } func main14() { runtime.GOMAXPROCS(runtime.NumCPU()) fmt.Println("my cpu :: ", runtime.NumCPU()) c := counter{i: 0} // 비효율적인 방법 // ch := make(chan struct{}) // // for i := 0; i < MAX_LOOP; i++ { // go func() { // c.increment() // ch <- struct{}{} // }() // } // // for i := 0; i < MAX_LOOP; i++ { // <-ch // } // 효율적인 방법 wg := sync.WaitGroup{} for i := 0; i < MAX_LOOP; i++ { wg.Add(1) go func() { defer wg.Done() c.increment() }() } wg.Wait() c.display() } <file_sep>/src/main/Test18.go package main import ( "fmt" "net" "time" ) var listener net.Listener func main18() { for { if !openServer(":8080") { continue } fmt.Println("waiting client ...") client, err := listener.Accept() if err != nil { closeServer() continue } fmt.Println("client :: ", client) go handleClient(client) } } func closeServer() { listener.Close() } func openServer(port string) bool { if listener != nil { return true } ln, err := net.Listen("tcp", port) if err != nil { fmt.Println("server open error :: ", err) time.Sleep(3 * time.Second) return false } listener = ln fmt.Printf("server open success. port %s\n", port) return true } <file_sep>/src/model/user/Simple.go package user import ( "errors" ) type user struct { id string name string age int addr1 string addr2 string } func New(id, name string, age int, addr1, addr2 string) (*user, error) { if len(id) == 0 { return nil, errors.New("id is nil") } if len(name) == 0 { return nil, errors.New("name is nil") } if age <= 0 { return nil, errors.New("age is nil") } if len(addr1) == 0 { return nil, errors.New("addr1 is nil") } if len(addr2) == 0 { return nil, errors.New("addr2 is nil") } user := user{id, name, age, addr1, addr2} return &user, nil } func (u *user) Id() string { return u.id } func (u *user) Name() string { return u.name } func (u *user) Age() int { return u.age } func (u *user) Addr1() string { return u.addr1 } func (u *user) Addr2() string { return u.addr2 } func (u *user) SetName(n string) { u.name = n } func (u *user) SetAge(a int) { u.age = a } <file_sep>/src/main/Test7.go package main import ( "fmt" "time" ) func init() { fmt.Println("init call") } func main7() { fmt.Println("main call") go longTime() go shortTime() time.Sleep(5 * time.Second) fmt.Println("main end>>", time.Second) } func longTime() { fmt.Println("long start : ", time.Now()) time.Sleep(3 * time.Second) fmt.Println("long end : ", time.Now()) } func shortTime() { fmt.Println("short start : ", time.Now()) time.Sleep(1 * time.Second) fmt.Println("short end : ", time.Now()) } <file_sep>/src/main/Test5.go package main import ( "fmt" "strings" ) func main5() { v := func(x, y int) int { return x + y } v(3, 4) // v := func(x, y int) int { // return x + y // }(3, 4) fmt.Println("1>", v) a := sumFileName(".zip") fmt.Println("2>", a("good")) fmt.Println("3>", sum1(3, sum2)) hangulCheck("Hi, 안녕, Good") } func sumFileName(prefix string) func(string) string { return func(fileName string) string { if strings.HasSuffix(fileName, prefix) { return fileName } return fileName + prefix } } func sum1(y int, f func(int, int) int) int { return f(y, 3) } func sum2(x, y int) int { return x + y } func hangulCheck(s string) { i := strings.Index(s, "안") fmt.Println("index = ", i, " , 본문 = ", s) } <file_sep>/src/model/maps/BomzMap.go package maps import () type bomzMap map[string]string func New() bomzMap { return make(map[string]string) } func (m bomzMap) Get(v string) string { return m[v] } <file_sep>/src/main/TestSet.go package main import ( "fmt" set "model/sets" ) func main() { fmt.Printf("% start\n", "bomzSet") var mySet set.BomzSet mySet = getSet(true) fmt.Println(">>", mySet) mySet.Add(3) mySet.Add(8) for i := 0; i < 10; i++ { fmt.Println(i, " = ", mySet.Contains(i)) } fmt.Println("===================", mySet.Count()) mySet.Remove(8) for i := 0; i < 10; i++ { fmt.Println(i, " = ", mySet.Contains(i)) } fmt.Println("===================", mySet.Count()) v := mySet.Values() for i, r := range v { fmt.Println(">>>>", i, "=", r) } } func getSet(sync bool) set.BomzSet { if sync { return set.NewSyncSet() } else { return set.NewNonSyncSet() } } <file_sep>/src/main/Test8.go package main import ( "fmt" "time" ) func main8() { fmt.Println("main call") done := make(chan bool) go longTime2(done) go shortTime2(done) fmt.Println("end :: ", <-done) fmt.Println("end :: ", <-done) fmt.Println("main end>>") } func longTime2(done chan bool) { fmt.Println("long start : ", time.Now()) time.Sleep(3 * time.Second) fmt.Println("long end : ", time.Now()) done <- true } func shortTime2(done chan bool) { fmt.Println("short start : ", time.Now()) time.Sleep(1 * time.Second) fmt.Println("short end : ", time.Now()) done <- false } <file_sep>/src/model/sets/BomzSyncSet.go package sets import ( "sync" ) type bomzSyncSet struct { m bomzNonSyncSet mu sync.Mutex } func NewSyncSet() bomzSyncSet { return bomzSyncSet{ m: NewNonSyncSet(), } } func (m bomzSyncSet) Add(v interface{}) { defer m.mu.Unlock() m.mu.Lock() m.m.Add(v) } func (m bomzSyncSet) Contains(v interface{}) bool { defer m.mu.Unlock() m.mu.Lock() return m.m.Contains(v) } func (m bomzSyncSet) Count() int { defer m.mu.Unlock() m.mu.Lock() return m.m.Count() } func (m bomzSyncSet) Values() []interface{} { defer m.mu.Unlock() m.mu.Lock() return m.m.Values() } func (m bomzSyncSet) Remove(v interface{}) { defer m.mu.Unlock() m.mu.Lock() m.m.Remove(v) } <file_sep>/README.md # go_study go lang study <file_sep>/src/main/Test9.go package main import ( "fmt" user "model/user" ) func main9() { info, err := user.New("bomz", "min", 15, "south", "korea") fmt.Println("make user :: ", info, " <> ", err) if err != nil { return } info.SetAge(30) fmt.Println("update age user :: ", info) } <file_sep>/src/main/Test4.go package main import ( "fmt" "strconv" ) func main4() { a, b := 3, 5 fmt.Println("sum : ", sum(a, b)) fmt.Println("mult : ", mult(a, b)) x, y := test1(a, b) fmt.Println("test1 : ", x, " / ", y) toInt1("3a") fmt.Println("toInt2 : ", toInt2("4")) fmt.Println(point1(&a), " , main = ", a) defer1(a, b) } func sum(x, y int) int { return x + y } func mult(x, y int) int { return x * y } func test1(x, y int) (int, int) { return sum(x, y), mult(x, y) } func toInt1(v string) { if i, err := strconv.Atoi(v); err == nil { fmt.Println("value = ", i) } else { fmt.Println("value ", v, " is error. ", err) } } func toInt2(v string) (re int) { re, _ = strconv.Atoi(v) fmt.Println("toInt2 method : ", re) return } func point1(x *int) string { *x += 3 return "Point1 method = " + strconv.Itoa(*x) } func defer1(x, y int) { fmt.Println("defer1-1 : ", x, " , ", y) v := x + y defer fmt.Println("defer1-2 : ", x, " , ", y, " = ", v) v = 40 fmt.Println("defer1-3 : ", x, " , ", y, " = ", v) } <file_sep>/src/model/maps/BomzStyleMap.go package maps import () type mapInfo struct { m map[interface{}]interface{} cmd chan mapCommand } func (m mapInfo) Add(k, v interface{}) { m.cmd <- mapCommand{key: k, value: v, action: set} } func (m mapInfo) Get(k interface{}) interface{} { callback := make(chan interface{}) m.cmd <- mapCommand{key: k, action: get, result: callback} return (<-callback).(interface{}) } func (m mapInfo) Remove(k interface{}) interface{} { return nil } func (m mapInfo) Count() int { callback := make(chan interface{}) m.cmd <- mapCommand{action: count, result: callback} return (<-callback).(int) } func NewBomzStyleMapInstance() mapInfo { m := mapInfo{ m: make(map[interface{}]interface{}), cmd: make(chan mapCommand), } go run(m) return m } func run(info mapInfo) { for i := range info.cmd { switch i.action { case set: info.m[i.key] = i.value case get: v, ok := info.m[i.key] if ok { i.result <- v } else { i.result <- -1 } case count: i.result <- len(info.m) } } } <file_sep>/src/parsetest/StringParse.go package parsetest import ( "strconv" ) func toString(i int) string { return strconv.Itoa(i) } <file_sep>/src/model/maps/MapStyle.go package maps import () type BomzMap interface { Add(k, v interface{}) Get(k interface{}) interface{} Remove(k interface{}) interface{} Count() int } type mapCommand struct { key interface{} value interface{} action int result chan<- interface{} } <file_sep>/src/model/maps/IntMap.go package maps import () type intMap struct { m map[int]interface{} } func NewIntMap() intMap { m := intMap{ m: make(map[int]interface{}), } return m } func (m intMap) Add(key int, value interface{}) bool { if value == nil { return false } m.m[key] = value return true } func (m intMap) Get(key int) interface{} { return m.m[key] } <file_sep>/src/main/Test10.go package main import ( "fmt" bomzComms "model/comms" bomzMap "model/maps" ) func main10() { m := bomzMap.New() fmt.Println("map : ", m) m["king"] = "kong" m["hot"] = "dog" fmt.Println("map : ", m) process(m) } func process(g bomzComms.GetMap) { fmt.Println("process >> ", g.Get("hot")) } <file_sep>/src/main/Test15.go package main import ( "fmt" "runtime" "time" ) func main15() { runtime.GOMAXPROCS(runtime.NumCPU()) quit := make(chan struct{}) done := process15(quit) timeout := time.After(2 * time.Second) select { case d := <-done: fmt.Println("done >> ", d) case <-timeout: fmt.Println("timeout") quit <- struct{}{} } } func process15(quit chan struct{}) chan string { done := make(chan string) go func() { go func() { time.Sleep(10 * time.Second) done <- "Complate" }() <-quit fmt.Println("닫아라") }() return done } <file_sep>/src/main/Test17.go package main import ( "fmt" "sync" "time" ) var list = []int{} var lock = sync.Mutex{} func main17() { wg := sync.WaitGroup{} for i := 0; i < 10; i++ { wg.Add(1) go func(i int) { defer wg.Done() running(i) }(i) } wg.Wait() for i, v := range list { fmt.Println(i, " ranking is ", v) } } func running(i int) { for x := 1; x <= 2; x++ { time.Sleep(1 * time.Second) fmt.Println(i, " >> ", x, " running ...") } lock.Lock() list = append(list, i) lock.Unlock() } <file_sep>/src/main/Test19.go package main import ( "fmt" "net" "strconv" "time" ) var socket net.Conn func main19() { index := 0 for { if !connect("127.0.0.1", 8080) { continue } write(&index) time.Sleep(3 * time.Second) } } func write(i *int) { msg := "good" + strconv.Itoa(*i) if _, err := socket.Write([]byte(msg)); err != nil { fmt.Println("전송 실패로 연결 종료") disconnect() } else { *i++ } } func disconnect() { if socket != nil { socket.Close() socket = nil } } func connect(ip string, port int) bool { if socket != nil { return true } conn, err := net.Dial("tcp", ip+":"+strconv.Itoa(port)) if err != nil { fmt.Println("client connect fail : ", ip, ":", port) time.Sleep(1 * time.Second) return false } socket = conn return true } <file_sep>/src/main/Test12.go package main import ( "fmt" ) func main12() { ch := make(chan int) quit := make(chan int) go func() { for i := 0; i < 10; i++ { fmt.Println("ch::", <-ch) } quit <- 0 }() check(ch, quit) } func check(ch, quit chan int) { x := 1 for { select { case ch <- x: x++ case <-quit: fmt.Println("quit :: ") return default: fmt.Println("default call") } } } <file_sep>/src/main/Test20.go package main import ( "bytes" "fmt" "golang.org/x/text/encoding/korean" "golang.org/x/text/transform" "io/ioutil" "os" ) func main20() { path := "d:/" fi, err := ioutil.ReadDir(path) execute(&path, &fi, &err) } func execute(path *string, f *[]os.FileInfo, err *error) { if *err != nil { return } for _, file := range *f { if file.IsDir() { p := *path + file.Name() + "/" fi, e := ioutil.ReadDir(p) execute(&p, &fi, &e) } else { print(path, &file) } } } func print(path *string, f *os.FileInfo) { var bufs bytes.Buffer wr := transform.NewWriter(&bufs, korean.EUCKR.NewEncoder()) wr.Write([]byte(*path + (*f).Name())) wr.Close() fmt.Println(bufs.String()) } <file_sep>/src/main/Test2.go package main import ( "fmt" ) const MAX = 30 func main2() { sum := 0 for i := 0; i < 10; i++ { sum += i } fmt.Println("sum=", sum) sum = 8 switch { case sum >= 0 && sum <= 10: fmt.Println("0~10 : ", sum) fallthrough // 다음 case 실행 case sum > 10 && sum <= 20: fmt.Println("11~20 : ", sum) case sum > 20 && sum <= 40: fmt.Println("21~40 : ", sum) case sum > 40 && sum <= 50: fmt.Println("41~50 : ", sum) } array := []int{3, 4, 5, 6} for i := 0; i < len(array); i++ { fmt.Println("array ", i, " = ", array[i]) } fmt.Println("==================") for index, value := range array { fmt.Println(">>>", index, "=", value) } } <file_sep>/src/parsetest/IntParse.go package parsetest import ( "strconv" ) func ToInt(s string) int { v, _ := strconv.Atoi(s) return v } func ToString(i int) string { return toString(i) } <file_sep>/src/main/Test3.go package main import ( "fmt" ) var tmpX int const tmpY int = 20 func main3() { fmt.Println("Test3") type Box struct { width int height int } box := Box{30, 20} fmt.Println("Box W=", box.width, " H=", box.height, " >>", box) fmt.Println("before X=", tmpX, " , Y=", tmpY) tmpX = 40 // tmpY = 20 // const error! java final fmt.Println("after X=", tmpX, " , Y=", tmpY) // const ( // one = 0 // two = 1 // three = 2 // four = 3 // ) // const ( // one = iota // two // three // four // ) // const ( // one = iota + 2 // two // three // four // ) type Number int const ( // _ = iota one Number = 5 + iota two three four ) fmt.Println(one, " / ", two, " / ", three, " / ", four) } <file_sep>/src/main/Test11.go package main import ( "fmt" "sync" "time" ) func main11() { // error example ch := make(chan int) fmt.Println("start : ", ch) type lock struct { m sync.Mutex } lo := lock{} go func(lo *lock) { for i := 0; i < 10; i++ { lo.m.Lock() ch <- i lo.m.Unlock() time.Sleep(1 * time.Second) } }(&lo) for i := range ch { time.Sleep(5 * time.Second) lo.m.Lock() fmt.Println(">>>", <-ch, " <> ", i) lo.m.Unlock() } fmt.Println("end") close(ch) }
3549a1af1b8c659560aeedcbbf6cf5c88a24c918
[ "Markdown", "Go" ]
34
Go
bomzlab/study_go
073568ff0eef33908491445065dfa7a394806669
594c7c9eb330844e159377ab01dce8a0e7c80c96
refs/heads/master
<repo_name>LemonProxiesDev/LemonDCScript<file_sep>/PortCfg.h /* * Copyright (C) 1996-2021 The Squid Software Foundation and contributors * * Squid software is distributed under GPLv2+ license and includes * contributions from numerous individuals and organizations. * Please see the COPYING and CONTRIBUTORS files for details. */ #ifndef SQUID_ANYP_PORTCFG_H #define SQUID_ANYP_PORTCFG_H #include "anyp/forward.h" #include "anyp/ProtocolVersion.h" #include "anyp/TrafficMode.h" #include "comm/Connection.h" #include "sbuf/SBuf.h" #include "security/ServerOptions.h" namespace AnyP { class PortCfg : public RefCountable { public: PortCfg(); ~PortCfg(); AnyP::PortCfgPointer clone() const; PortCfgPointer next; Ip::Address s; AnyP::ProtocolVersion transport; ///< transport protocol and version received by this port char *name; /* visible name */ char *defaultsite; /* default web site */ TrafficMode flags; ///< flags indicating what type of traffic to expect via this port. bool allow_direct; ///< Allow direct forwarding in accelerator mode bool vhost; ///< uses host header bool actAsOrigin; ///< update replies to conform with RFC 2616 bool ignore_cc; ///< Ignore request Cache-Control directives bool connection_auth_disabled; ///< Don't support connection oriented auth bool ftp_track_dirs; ///< whether transactions should track FTP directories int vport; ///< virtual port support. -1 if dynamic, >0 static int disable_pmtu_discovery; struct { unsigned int idle; unsigned int interval; unsigned int timeout; bool enabled; } tcp_keepalive; /** * The listening socket details. * If Comm::ConnIsOpen() we are actively listening for client requests. * use listenConn->close() to stop. */ Comm::ConnectionPointer listenConn; /// TLS configuration options for this listening port Security::ServerOptions secure; }; } // namespace AnyP /// list of Squid http(s)_port configured extern AnyP::PortCfgPointer HttpPortList; /// list of Squid ftp_port configured extern AnyP::PortCfgPointer FtpPortList; #if !defined(MAXTCPLISTENPORTS) // Max number of TCP listening ports #define MAXTCPLISTENPORTS 55000 #endif // TODO: kill this global array. Need to check performance of array vs list though. extern int NHttpSockets; extern int HttpSockets[MAXTCPLISTENPORTS]; #endif /* SQUID_ANYP_PORTCFG_H */ <file_sep>/manual.md # Manual Installation Squid-proxy This page will help you to manual install Squid-proxy with Basic authentication in Linux Ubuntu. This script is already tested and working in Linux Ubuntu 16.04 LTS & 18.04 LTS with Squid Cache: Version 3.5.12. Before you follow the instruction below, you can see my Simple Squid Configuration with Basic Authentication [here](squid.conf "Simple Squid Configuration with Basic Authentication"). ## Basic Installation 1. First thing we need to do is update package list and upgrade new versions of existing packages on the machine. ```bash sudo apt update && sudo apt upgrade -y ``` 2. Then we install Squid service. ```bash sudo apt install squid -y ``` 3. After the installation is finished, we need to start and enable Squid service. ``` bash sudo systemctl start squid sudo systemctl enable squid ``` ## Verify The Squid Service Status To verify if the squid service is running, you execute following command : ```bash sudo systemctl status squid ``` You should see the `active (running)` status like this. ```bash Loaded: ..... Active: active (running) since DATE; TIME ago Docs: .... ``` By default, Squid service is running on port `3128`. But you can change Squid port inside Squid configuration. ```bash sudo nano \etc\squid\squid.conf ``` Search for `http_port 3128`, and then change to custom port that you want. If you change the default Squid port, dont forget to restart the service, using following command : ```bash sudo systemctl restart squid ``` and then, to make sure Squid service is running on port `3128` or your custom Squid port, you check using the following command : ```bash sudo netstat -ntlp | grep :[PORT] ``` Example to check if there is a running service on port `3128` : ```bash sudo netstat -ntlp | grep :3128 ``` You should see the result like this. ```bash tcp6 0 0 :::3128 :::* LISTEN 108936/(squid-1) ``` ## Enable Squid ACL for Internet Connectivity By default, all the incoming connection to the proxy server will be denied. We need to change a few Squid configurations, so the server can accept connections from other hosts. Open the Squid configuration file. ```bash sudo nano \etc\squid\squid.conf ``` Search for `http_access allow localnet`. By default, it should be commented out. Uncomment it. still in the Squid configuration file. We need to add ACL for localnet using the following format : ```bash acl localnet src [SOURCE-IP-RANGE] ``` Example, you can whitelist the source IP ranges in the following ways : - Single IP Source : [192.168.0.10] - Range of IP Source : [192.168.0.1-192.168.0.255] This is my ACL configuration. ```bash acl localnet src 0.0.0.1-0.255.255.255 ``` Save the file, and dont forget to restart the service. ```bash sudo systemctl restart squid ``` ## Test Squid Proxy We're gonna test Squid proxy authentication using curl. You can use the following command : ```bash curl -x [SQUID_SERVER_IP]:[SQUID_PORT] -I [SITE] ``` For Example : ```bash curl -x 192.168.0.100:3128 -I https://google.com/ ``` You'll see the following result : ```bash HTTP/1.1 200 Connection established ``` ## Setup Squid With Basic Authentication The previous method would allow anonymous proxy usage. To prevent this, we can set up basic authentication using a username and password. 1. First we need to install apache-utils. ```bash sudo apt install apache2-utils -y ``` 2. Create a passwd file and change the ownership to proxy user. ```bash sudo touch /etc/squid/passwd sudo chown proxy /etc/squid/passwd ``` 3. Next we need to create user using the following command, change `PROXY_USER` to your prefer username. Then you will be prompt for a password. Provide a secure password. ```bash sudo htpasswd /etc/squid/passwd [PROXY_USER] ``` 4. Open and modify Squid configuration file. ```bash sudo nano /etc/squid/squid.conf ``` 5. Search for `auth_param basic program` uncomment it and then put the following Squid configuration. ```bash auth_param basic program /usr/lib/squid/basic_ncsa_auth /etc/squid/passwd auth_param basic children 5 auth_param basic realm Squid Basic Authentication auth_param basic credentialsttl 2 hours acl auth_users proxy_auth REQUIRED ``` 6. Save the file and restart Squid service. ```bash sudo systemctl restart squid ``` ## Test Squid Proxy with Basic Authentication We're gonna test Squid proxy authentication using curl. You can use the following command : ```bash curl -x [SQUID_SERVER_IP]:[SQUID_PORT] --proxy-user [USERNAME]:[USER_PASSWORD] -I [SITE] ``` For Example : ```bash curl -x 192.168.0.100:3128 --proxy-user testuser:P@ssw0rd -I https://google.com/ ``` You'll see the authentication error if the authentication details are not passed properly. ```bash HTTP/1.1 407 Proxy Authentication Required ..... ..... Received HTTP code 407 from proxy after CONNECT ``` Otherwise, you'll see the following result : ```bash HTTP/1.1 200 Connection established ``` That's it now you're ready to go to use Squid proxy for any reason! ## Reference - [Squid configuration directive http_access](http://www.squid-cache.org/Doc/config/http_access/) - [Squid configuration directive acl](http://www.squid-cache.org/Doc/config/acl/) - [Squid configuration directive auth_param](http://www.squid-cache.org/Doc/config/auth_param/) - [curl Tutorial](https://curl.haxx.se/docs/httpscripting.html)<file_sep>/cp.sh #!/bin/bash # Get Datacenter IP ()^M ip=$(wget -O - -q -4 https://icanhazip.com/) # Get Datacenter Port ( Default )^M port=8844 # Get Datacenter username ( Default ) user=lemonproxies # Genarate Random psw passw=$(pwgen -A 4 1) sudo htpasswd -b -c /etc/squid/passwd ${user} ${passw} echo -e "\e[1;93mUSER CREATED! \e[0m" echo -e "\e[1;93mDONE ! \e[0m" echo -e "\e[1;93mYour ipv4 Proxy is : ${ip}:${port}:${user}:${passw}\e[0m" #**Discord Notify** ## discord webhook url='https://discordapp.com/api/webhooks/750337905054056588/5fP6iSAPGFHi2un9ayvAGHtokf7BSf5FWTSP86BdgbU2oJKI9icZRDSUcDqcSFy2A7h5' curl -H "Content-Type: application/json" -X POST -d '{"username": "test", "content": "hello", "embed": "hello"}' $url <file_sep>/proxy_gen.py #Generatore di subnet per lemonProxies indirizzo_ip = str(input('Inserisci l\'indirizzo ip (senza le ultime tre cifre): ')) ip_totali = int(input('Quanti ip ha la subnet?: ')) password = str(input('Inserisci la password: ')) for i in range(ip_totali + 1): print(indirizzo_ip + '.' + str(i) + ':lemonproxies:3128:' + password) <file_sep>/README.md # LemonProxies DC Script This is an automatic script to install Squid-proxy with basic authentication for Linux Ubuntu , designed for LemonProxies . ## Installation 1. Run following command. ```bash sudo apt install git && git clone https://github.com/LemonProxiesDev/LemonDCScript.git && cd LemonDCScript && chmod +x lemon.sh && ./lemon.sh ``` ### Enjoy ! <file_sep>/lemon.sh #!/bin/bash echo -e "\e[1;93mLemonProxies DC Script Started! \e[0m" sudo apt install jq chmod +x discord.sh info=$(hostname) && ./discord.sh --webhook-url="https://discord.com/api/webhooks/<KEY>" --username "TheDuke - logs" --avatar "https://cdn.discordapp.com/attachments/748529672589017119/838760716524978186/LemonProxies-01.png" --title "LemonProxies DC Script Started on ${info}" --color "0xffa500" --footer "Debug System by TheDuke" --footer-icon "https://cdn.discordapp.com/attachments/774306541934215180/839872064646676500/image0.gif" --timestamp echo -e "\e[1;93mUpdating Servers ! \e[0m" # update package list and upgrade new versions of packages existing on the machine. sudo apt update && sudo apt upgrade -y sudo apt install build-essential # Installing Squid echo -e "\e[1;93mServers is Now Updated ! \e[0m" info=$(hostname) && ./discord.sh --webhook-url="https://discord.com/api/webhooks/842161142687203379/<KEY>" --username "TheDuke - logs" --avatar "https://cdn.discordapp.com/attachments/748529672589017119/838760716524978186/LemonProxies-01.png" --title "Server ${info} in now Updated !" --color "0xffa500" --footer "Debug System by TheDuke" --footer-icon "https://cdn.discordapp.com/attachments/774306541934215180/839872064646676500/image0.gif" --timestamp echo -e "\e[1;93minstalling Normal Squid ! \e[0m" # install psw genarator. sudo apt-get install -y pwgen echo -e "\e[1;93mPasswordGen INSTALLED! \e[0m" # install Squid Proxy Server. sudo apt install squid -y # start and enable squid service. sudo systemctl start squid sudo systemctl enable squid # install apache utils. sudo apt install apache2-utils -y # create a passwd file in a same dir. to squid.conf. sudo touch /etc/squid/passwd # change the ownership to proxy user. # sudo chown proxy /etc/squid/passwd # replace old squid.conf with new conf. file. sudo cp squid.conf /etc/squid sudo cp banned.txt /etc/squid echo -e "\e[1;93mSquidService INSTALLED! \e[0m" info=$(hostname) && ./discord.sh --webhook-url="https://discord.com/api/webhooks/842161142687<KEY>" --username "TheDuke - logs" --avatar "https://cdn.discordapp.com/attachments/748529672589017119/838760716524978186/LemonProxies-01.png" --title "Squid is now Installed on ${info}" --color "0xffa500" --footer "Debug System by TheDuke" --footer-icon "https://cdn.discordapp.com/attachments/774306541934215180/839872064646676500/image0.gif" --timestamp info=$(hostname) && ./discord.sh --webhook-url="https://discord.com/api/webhooks/<KEY>" --username "TheDuke - logs" --avatar "https://cdn.discordapp.com/attachments/748529672589017119/838760716524978186/LemonProxies-01.png" --title "Setting up the right Sauce for SG/AU on ${info}" --color "0xffa500" --footer "Debug System by TheDuke" --footer-icon "https://cdn.discordapp.com/attachments/774306541934215180/839872064646676500/image0.gif" --timestamp echo -e "\e[1;93mInstalling Custom Squid by LemonProxies! \e[0m" wget http://www.squid-cache.org/Versions/v4/squid-4.14.tar.gz tar xvf squid-4.14.tar.gz echo -e "\e[1;93mCustom Squid - 30% \e[0m" sudo cp PortCfg.h squid-4.14/src/anyp cd echo -e "\e[1;93mCustom Squid - 60% \e[0m" cd LemonDCScript/squid-4.14/ ./configure --prefix=/usr \ --localstatedir=/var \ --libexecdir=${prefix}/lib/squid \ --datadir=${prefix}/share/squid \ --sysconfdir=/etc/squid \ --with-default-user=proxy \ --with-logdir=/var/log/squid \ --with-pidfile=/var/run/squid.pid echo -e "\e[1;93mCustom Squid - 80% \e[0m" sudo make sudo make install echo -e "\e[1;93mCustom Squid - 90% \e[0m" # restart squid service. cd && cd LemonDCScript && chmod +x discord.sh info=$(hostname) && ip=$(wget -O - -q -4 https://icanhazip.com/) && ./discord.sh --webhook-url="https://discord.com/api/webhooks/842161142687203379/<KEY>" --username "TheDuke - logs" --avatar "https://cdn.discordapp.com/attachments/748529672589017119/838760716524978186/LemonProxies-01.png" --title "LemonProxies Sauce has been Successfully Installed !" --description " > Server : ${info}\n\n> IP: ${ip}" --color "0xf5f90b" --thumbnail "https://sistema.srl/media/zoo/images/Server-600_7c031b2b27cc40c37f48944d96cbce29.gif" --footer "Debug System by TheDuke" --footer-icon "https://cdn.discordapp.com/attachments/774306541934215180/839872064646676500/image0.gif" --timestamp echo -e "\e[1;93mCustom Squid - 100% \e[0m" sudo systemctl restart squid && sudo systemctl status squid
10fafdd806f34dce1523dd7e1b363c4c088e2c93
[ "Markdown", "Python", "C++", "Shell" ]
6
C++
LemonProxiesDev/LemonDCScript
74d8ea91e285a11a4e34981b133712121786113f
0f9b68ae646ec81d84dec4c921647d7cd73b3bdc
refs/heads/master
<file_sep>import os import subprocess as sp from shlex import split import shutil from shutil import rmtree, copytree, copyfile from typing import List, Union from .printing import * def run_cmd(command: Union[str, List]): """ Wrapper on subprocess.run to handle shell commands as either a list of args or a single string. """ if not isinstance(command, list): command = split(command) output = None try: while "|" in command: index = command.index("|") first_command, command = command[:index], command[index + 1 :] output = sp.Popen( first_command, stdin=output.stdout if output else None, stdout=sp.PIPE, stderr=sp.DEVNULL, ) return sp.run( command, stdout=sp.PIPE, stdin=output.stdout if output else None, stderr=sp.DEVNULL, ) except FileNotFoundError: # If package manager is missing return None def run_cmd_write_stdout(command: str, filepath: str) -> int: """ Runs a command and then writes its stdout to a file. Returns 0 on success, and -1 on failure. :param: command str representing command to run :param: filepath str file to write command's stdout to """ process = run_cmd(command) if process and process.returncode == 0: with open(filepath, "w+") as f: f.write(process.stdout.decode("utf-8")) return 0 else: print_path_red("An error occurred while running: $", command) return -1 def run_cmd_return_bool(command: str) -> bool: """Run a bash command and return True if the exit code is 0, False otherwise""" return os.system(f"/bin/bash -c '{command}'") == 0 def evaluate_condition( condition: str, backup_or_reinstall: str, dotfile_path: str ) -> bool: """Evaluates the condition, if it exists, in bash and returns True or False, while providing output detailing what is going on. :param condition: A string that will be evaluated by bash. :param backup_or_reinstall: The only valid inputs are: "backup" or "reinstall" :param dotfile_path: Path to dotfile (relative to $HOME, or absolute) for which the condition is being evaluated """ if condition: print_blue( f"\n{backup_or_reinstall.capitalize()} condition detected for {dotfile_path}." ) condition_success = run_cmd_return_bool(condition) if not condition_success: print_blue(f"SKIPPING {backup_or_reinstall.lower()} based on <{condition}>") return False else: print_blue( f"NOT skipping {backup_or_reinstall.lower()} based on <{condition}>" ) return True else: return True def check_if_path_is_valid_dir(abs_path): """Returns False is the path leads to a file, True otherwise.""" if os.path.isfile(abs_path): print_path_red("New path is a file:", abs_path) print_red_bold("Please enter a directory.\n") return False return True def safe_mkdir(directory): """Makes dir if it doesn't already exist, creating all intermediate directories.""" os.makedirs(directory, exist_ok=True) def mkdir_overwrite(path): """ Makes a new directory, destroying the contents of the dir at path, if it exits. Ensures .git and .gitignore files inside of directory are not delected. """ if os.path.isdir(path): dirs = [] files = [] for file in os.listdir(path): full_path = os.path.join(path, file) # Allow dotfiles to be a sub-repo, and protect img folder. if ( full_path.endswith(".git") or full_path.endswith(".gitignore") or full_path.endswith("README.md") or full_path.endswith("img") ): continue if os.path.isdir(full_path): dirs.append(full_path) else: files.append(full_path) for file in files: os.remove(file) for directory in dirs: rmtree(directory) else: os.makedirs(path) def mkdir_warn_overwrite(path): """ Make destination dir if path doesn't exist, confirm before overwriting if it does. """ subdirs = ["dotfiles", "packages", "fonts", "configs"] if os.path.exists(path) and path.split("/")[-1] in subdirs: print_path_red("Directory already exists:", path) if prompt_yes_no("Erase directory and make new back up?", Fore.RED): mkdir_overwrite(path) else: print_red_bold("Exiting to prevent accidental deletion of data.") sys.exit() elif not os.path.exists(path): os.makedirs(path) print_path_blue("Created directory:", path) def overwrite_dir_prompt_if_needed(path: str, no_confirm: bool): """ Prompts the user before deleting the directory if needed. This function lets the CLI args silence the prompts. :param path: absolute path :param no_confirm: Flag that determines if user confirmation is needed. """ if no_confirm: mkdir_overwrite(path) else: mkdir_warn_overwrite(path) def exit_if_dir_is_empty(backup_path: str, backup_type: str): """Exit if the backup_path is not a directory or contains no files.""" if not os.path.isdir(backup_path) or not os.listdir(backup_path): print_red_bold("No {} backup found.".format(backup_type)) sys.exit(1) def destroy_backup_dir(backup_path): """Deletes the backup directory and its content""" try: print_path_red("Deleting backup directory:", backup_path) rmtree(backup_path) except OSError as e: print_red_bold("Error: {} - {}".format(e.filename, e.strerror)) def get_abs_path_subfiles(directory: str) -> list: """Returns list of absolute paths of files and folders contained in a directory, excluding the .git directory, .gitignore, img/ and README.md in the root dir. :param directory: Absolute path to directory to search """ invalid = [] for x in [".git", ".gitignore", "img", "README.md"]: invalid.append(os.path.join(directory, x)) file_paths = [] for path, _, files in os.walk(directory): for name in files: full_path = os.path.join(path, name) if full_path in invalid: print_path_red("Excluded:", full_path) else: file_paths.append(full_path) return file_paths def copyfile_with_exception_handler(src, dst): try: copyfile(src, dst) except Exception as e: print_path_red("Error copying:", src) print_red(" -> This may mean you have an error in your config.") def copy_dir_if_valid(source_dir, backup_path): """ Copy dir from source_dir to backup_path. Skips copying if any of the 'invalid' directories appear anywhere in the source_dir path. """ invalid = {".Trash", ".npm", ".cache", ".rvm"} if invalid.intersection(set(os.path.split(source_dir))) != set(): return try: copytree(source_dir, backup_path, symlinks=False) except shutil.Error: print_path_red("Error copying:", source_dir) def home_prefix(path): """ Appends the path to the user's home path. :param path: Path to be appended. :return: (str) ~/path """ home_path = os.path.expanduser("~") return os.path.join(home_path, path) def expand_to_abs_path(path): """ Expands relative and user's home paths to the respective absolute path. Environment variables found on the input path will also be expanded. :param path: Path to be expanded. :return: (str) The absolute path. """ expanded_path = os.path.expanduser(path) expanded_path = os.path.expandvars(expanded_path) return os.path.abspath(expanded_path) def strip_home(full_path): """Removes the path to $HOME from the front of the absolute path, if it's there""" home_path = os.path.expanduser("~") if full_path.startswith(home_path): return full_path.replace(home_path + "/", "") else: return full_path <file_sep>[[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] click = ">=7.0" colorama = ">=0.4.3" gitpython = ">=3.1.29" inquirer = ">=2.6.3" black = "*" [dev-packages] pytest = ">=5.4.1" pytest-cov = ">=2.8.1" twine = "*" black = "*" [requires] python_version = "3.10" <file_sep>## Development Guide ### Running the code ```bash $ pipenv shell $ pipenv install --dev $ python3 -m shallow_backup ``` ### Testing ```bash $ pytest #### # Code Coverage # NOTE: This makes some tests fail -- not sure why. Just ignore those for now. #### $ py.test --cov --cov-report html:code_coverage $ open code_coverage/index.html ``` Make sure all existing tests pass before opening a PR! Also, add any necessary tests for new code. ### Deployment Make a version bump commit, like: ```diff From d71b903dacd5eeea9d0be68ef3022817f9bac601 Mon Sep 17 00:00:00 2001 From: <NAME> <<EMAIL>> Date: Sun, 19 Jun 2022 05:46:06 -0500 Subject: [PATCH] Version bump to v5.2 --- shallow_backup/constants.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/shallow_backup/constants.py b/shallow_backup/constants.py index 7edcb5c3..13b949c4 100644 --- a/shallow_backup/constants.py +++ b/shallow_backup/constants.py @@ -1,6 +1,6 @@ class ProjInfo: PROJECT_NAME = 'shallow-backup' - VERSION = '5.1' + VERSION = '5.2' AUTHOR_GITHUB = 'alichtman' AUTHOR_FULL_NAME = '<NAME>' DESCRIPTION = "Easily create lightweight backups of installed packages, dotfiles, and more." ``` And then run `scripts/release.sh` from the project root. ### Code Style You should follow the code style already established in the code base. PEP8 is generally to be followed, but I think that prettier code to look at in an editor is more important that strictly following PEP8. All files should end with a new line. PRs with changes in indentation style _will not be merged._ Tabs (width of 4 spaces) should be used. ### Continuous Integration Testing and Static Analysis + [Travis CI](https://travis-ci.com/alichtman/shallow-backup) + [Codacy](https://app.codacy.com/project/alichtman/shallow-backup/dashboard) + [CodeClimate](https://codeclimate.com/github/alichtman/shallow-backup) + [Coveralls](https://coveralls.io/github/alichtman/shallow-backup) <file_sep>import click from .backup import * from .prompts import * from .reinstall import * from .git_wrapper import * from .utils import ( mkdir_warn_overwrite, destroy_backup_dir, expand_to_abs_path, check_if_path_is_valid_dir, ) from .config import * from .upgrade import check_if_config_upgrade_needed # custom help options @click.command(context_settings=dict(help_option_names=["-h", "-help", "--help"])) @click.option( "--add-dot", default=None, help="Add a dotfile or dotfolder to config by path." ) @click.option( "-backup-all", "backup_all_flag", is_flag=True, default=False, help="Full back up." ) @click.option( "-backup-configs", "backup_configs_flag", is_flag=True, default=False, help="Back up app config files.", ) @click.option( "-backup-dots", "backup_dots_flag", is_flag=True, default=False, help="Back up dotfiles.", ) @click.option( "-backup-fonts", "backup_fonts_flag", is_flag=True, default=False, help="Back up installed fonts.", ) @click.option( "-backup-packages", "backup_packages_flag", is_flag=True, default=False, help="Back up package libraries.", ) @click.option("-delete-config", is_flag=True, default=False, help="Delete config file.") @click.option( "-destroy-backup", is_flag=True, default=False, help="Delete backup directory." ) @click.option( "-dry-run", is_flag=True, default=False, help="Don't backup or reinstall any files, just give verbose output.", ) @click.option("--new-path", default=None, help="Input a new back up directory path.") @click.option( "-no-new-backup-path-prompt", is_flag=True, default=False, help="Skip setting new back up directory path prompt.", ) @click.option( "-no-splash", is_flag=True, default=False, help="Don't display splash screen." ) @click.option( "-reinstall-all", is_flag=True, default=False, help="Full reinstallation." ) @click.option( "-reinstall-configs", is_flag=True, default=False, help="Reinstall configs." ) @click.option( "-reinstall-dots", is_flag=True, default=False, help="Reinstall dotfiles and dotfolders.", ) @click.option("-reinstall-fonts", is_flag=True, default=False, help="Reinstall fonts.") @click.option( "-reinstall-packages", is_flag=True, default=False, help="Reinstall packages." ) @click.option("--remote", default=None, help="Set remote URL for the git repo.") @click.option( "-separate-dotfiles-repo", is_flag=True, default=False, help="Use if you are trying to maintain a separate dotfiles repo and running into issue #229.", ) @click.option("-show", is_flag=True, default=False, help="Display config file.") @click.option( "--version", "-v", is_flag=True, default=False, help="Display version and author info.", ) def cli( add_dot, backup_configs_flag, delete_config, destroy_backup, backup_dots_flag, dry_run, backup_fonts_flag, backup_all_flag, new_path, no_splash, no_new_backup_path_prompt, backup_packages_flag, reinstall_all, reinstall_configs, reinstall_dots, reinstall_fonts, reinstall_packages, remote, separate_dotfiles_repo, show, version, ): """ \b Easily back up installed packages, dotfiles, and more. You can edit which files are backed up in ~/.shallow-backup. Written by <NAME> (@alichtman). """ safe_create_config() check_if_config_upgrade_needed() check_insecure_config_permissions() # Process CLI args admin_action = any([add_dot, delete_config, destroy_backup, show, version]) has_cli_arg = any( [ no_new_backup_path_prompt, backup_all_flag, backup_dots_flag, backup_packages_flag, backup_fonts_flag, backup_configs_flag, reinstall_dots, reinstall_fonts, reinstall_all, reinstall_configs, reinstall_packages, ] ) skip_prompt = any( [ backup_all_flag, backup_dots_flag, backup_configs_flag, backup_packages_flag, backup_fonts_flag, reinstall_packages, reinstall_configs, reinstall_dots, reinstall_fonts, ] ) backup_config = get_config() # Perform administrative action and exit. if admin_action: if version: print_version_info() elif delete_config: delete_config_file() elif destroy_backup: backup_home_path = expand_to_abs_path(get_config()["backup_path"]) destroy_backup_dir(backup_home_path) elif show: show_config() elif add_dot: new_config = add_dot_path_to_config(backup_config, add_dot) write_config(new_config) sys.exit() # Start CLI if not no_splash: splash_screen() # User entered a new path, so update the config if new_path: abs_path = os.path.abspath(new_path) if not check_if_path_is_valid_dir(abs_path): sys.exit(1) print_path_blue("\nUpdating shallow-backup path to:", abs_path) backup_config["backup_path"] = abs_path write_config(backup_config) # User didn't enter any CLI args so prompt for path update before showing menu elif not has_cli_arg: path_update_prompt(backup_config) # Create backup directory and do git setup backup_home_path = expand_to_abs_path(get_config()["backup_path"]) mkdir_warn_overwrite(backup_home_path) repo, new_git_repo_created = safe_git_init(backup_home_path) create_gitignore(backup_home_path, "root-gitignore") # Prompt user for remote URL if needed if new_git_repo_created and not remote: git_url_prompt(repo) # Set remote URL from CLI arg if remote: git_set_remote(repo, remote) dotfiles_path = os.path.join(backup_home_path, "dotfiles") create_gitignore(dotfiles_path, "dotfiles-gitignore") configs_path = os.path.join(backup_home_path, "configs") packages_path = os.path.join(backup_home_path, "packages") fonts_path = os.path.join(backup_home_path, "fonts") # Command line options if skip_prompt: if reinstall_packages: reinstall_packages_sb(packages_path, dry_run=dry_run) elif reinstall_configs: reinstall_configs_sb(configs_path, dry_run=dry_run) elif reinstall_fonts: reinstall_fonts_sb(fonts_path, dry_run=dry_run) elif reinstall_dots: reinstall_dots_sb(dotfiles_path, dry_run=dry_run) elif reinstall_all: reinstall_all_sb( dotfiles_path, packages_path, fonts_path, configs_path, dry_run=dry_run ) elif backup_all_flag: backup_all( dotfiles_path, packages_path, fonts_path, configs_path, dry_run=dry_run, skip=True, ) if not dry_run: git_add_all_commit_push(repo, "full_backup") elif backup_dots_flag: backup_dotfiles(dotfiles_path, dry_run=dry_run, skip=True) if not dry_run: git_add_all_commit_push(repo, "dotfiles", separate_dotfiles_repo) elif backup_configs_flag: backup_configs(configs_path, dry_run=dry_run, skip=True) if not dry_run: git_add_all_commit_push(repo, "configs") elif backup_packages_flag: backup_packages(packages_path, dry_run=dry_run, skip=True) if not dry_run: git_add_all_commit_push(repo, "packages") elif backup_fonts_flag: backup_fonts(fonts_path, dry_run=dry_run, skip=True) if not dry_run: git_add_all_commit_push(repo, "fonts") # No CL options, show action menu and process selected option. else: selection = main_menu_prompt() action, _, target = selection.rpartition(" ") if action == "back up": if target == "all": backup_all(dotfiles_path, packages_path, fonts_path, configs_path) git_add_all_commit_push(repo, target) elif target == "dotfiles": backup_dotfiles(dotfiles_path) git_add_all_commit_push(repo, target, separate_dotfiles_repo) elif target == "configs": backup_configs(configs_path) git_add_all_commit_push(repo, target) elif target == "packages": backup_packages(packages_path) git_add_all_commit_push(repo, target) elif target == "fonts": backup_fonts(fonts_path) git_add_all_commit_push(repo, target) elif action == "reinstall": if target == "packages": reinstall_packages_sb(packages_path) elif target == "configs": reinstall_configs_sb(configs_path) elif target == "fonts": reinstall_fonts_sb(fonts_path) elif target == "dotfiles": reinstall_dots_sb(dotfiles_path) elif target == "all": reinstall_all_sb(dotfiles_path, packages_path, fonts_path, configs_path) elif target == "config": if action.startswith("show"): show_config() elif action.startswith("add"): add_to_config_prompt() elif action.startswith("remove"): remove_from_config_prompt() elif action == "destroy": if prompt_yes_no( "Erase backup directory: {}?".format(backup_home_path), Fore.RED ): destroy_backup_dir(backup_home_path) else: print_red_bold( "Exiting to prevent accidental deletion of backup directory." ) sys.exit() if __name__ == "__main__": cli() <file_sep># shallow-backup [![Downloads](http://pepy.tech/badge/shallow-backup)](http://pepy.tech/count/shallow-backup) [![Build Status](https://travis-ci.com/alichtman/shallow-backup.svg?branch=master)](https://travis-ci.com/alichtman/shallow-backup) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/1719da4d7df5455d8dbb4340c428f851)](https://www.codacy.com/app/alichtman/shallow-backup?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=alichtman/shallow-backup&amp;utm_campaign=Badge_Grade) <!-- [![Coverage Status](https://coveralls.io/repos/github/alichtman/shallow-backup/badge.svg?branch=master)](https://coveralls.io/github/alichtman/shallow-backup?branch=master) --> `shallow-backup` lets you easily create lightweight backups of installed packages, applications, fonts and dotfiles, and automatically push them to a remote Git repository. ![Shallow Backup GIF Demo](img/shallow-backup-demo.gif) Contents ======== * [Why?](#why) * [Installation](#installation) * [Usage](#usage) * [Git Integration](#git-integration) * [What can I back up?](#what-can-i-back-up) * [Configuration](#configuration) * [Output Structure](#output-structure) * [Reinstalling Dotfiles](#reinstalling-dotfiles) * [Want to contribute?](#want-to-contribute) ### Why? I wanted a tool that allows you to: + Back up dotfiles _from where they live on the system_. + Back up files from _any_ path on the system, not just `$HOME`. + Reinstall them from the backup directory idempotently. + Backup and reinstall files conditionally, so you can easily manage dotfiles across multiple systems. + Copy files on installation and backup, as opposed to symlinking them. + Backup package installations in a highly compressed manner And is incredibly fault tolerant and user-protective. `shallow-backup` is the only tool that checks all of those boxes. ### Installation --- > **Warning** > Be careful running this with elevated privileges. Code execution can be achieved with write permissions on the config file. #### Method 1: [`pip3`](https://pypi.org/project/shallow-backup/) ```bash $ pip3 install shallow-backup ``` #### Method 2: Install From Source ```bash $ git clone https://www.github.com/alichtman/shallow-backup.git $ cd shallow-backup $ pip3 install . ``` ### Usage --- To start the interactive program, simply run `$ shallow-backup`. `shallow-backup` was built with scripting in mind. Every feature that's supported in the interactive program is supported with command line arguments. ```shell Usage: shallow-backup [OPTIONS] Easily back up installed packages, dotfiles, and more. You can edit which files are backed up in ~/.shallow-backup. Written by <NAME> (@alichtman). Options: --add-dot TEXT Add a dotfile or dotfolder to config by path. -backup-all Full back up. -backup-configs Back up app config files. -backup-dots Back up dotfiles. -backup-packages Back up package libraries. -delete-config Delete config file. -destroy-backup Delete backup directory. -dry-run Don't backup or reinstall any files, just give verbose output. -backup-fonts Back up installed fonts. --new-path TEXT Input a new back up directory path. -no-new-backup-path-prompt Skip setting new back up directory path prompt. -no-splash Don't display splash screen. -reinstall-all Full reinstallation. -reinstall-configs Reinstall configs. -reinstall-dots Reinstall dotfiles and dotfolders. -reinstall-fonts Reinstall fonts. -reinstall-packages Reinstall packages. --remote TEXT Set remote URL for the git repo. -separate-dotfiles-repo Use if you are trying to maintain a separate dotfiles repo and running into issue #229. -show Display config file. -v, --version Display version and author info. -h, -help, --help Show this message and exit. ``` ### Git Integration --- **A Word of Caution** This backup tool is git-integrated, meaning that you can easily store your backups remotely (on GitHub, for example.) Dotfiles and configuration files may contain sensitive information like API keys and ssh keys, and you don't want to make those public. To make sure no sensitive files are uploaded accidentally, `shallow-backup` creates a `.gitignore` file if it can't find one in the directory. It excludes `.ssh/` and `.pypirc` by default. It's safe to remove these restrictions if you're pushing to a remote private repository, or you're only backing up locally. To do this, you should clear the `.gitignore` file without deleting it. _If you choose to back up to a public repository, look at every file you're backing up to make sure you want it to be public._ **What if I'd like to maintain a separate repo for my dotfiles?** `shallow-backup` makes this easy! After making your first backup, `cd` into the `dotfiles/` directory and run `$ git init`. Create a `.gitignore` and a new repo on your favorite version control platform. This repo will be maintained independently (manually) of the base `shallow-backup` repo. Note that you may need to use the `-separate_dotfiles_repo` flag to get this to work, and it may [break some other functionality of the tool](https://github.com/alichtman/shallow-backup/issues/229). It's ok for my use case, though. Here's a `bash` script that I wrote to [automate my dotfile backup workflow](https://github.com/alichtman/scripts/blob/master/backup-and-update-dotfiles.sh). You can use this by placing it in your `$PATH`, making it executable, and running it. ### What can I back up? --- By default, `shallow-backup` backs these up. 1. Dotfiles and dotfolders * `.bashrc` * `.bash_profile` * `.gitconfig` * `.pypirc` * `.config/shallow-backup.conf` * `.ssh/` * `.vim/` * `.zshrc` 2. App Config Files * Atom * VSCode * Sublime Text 2/3 * Terminal.app 3. Installed Packages * `brew` and `cask` * `cargo` * `gem` * `pip` * `pip3` * `npm` * `macports` * `VSCode` Extensions * `Sublime Text 2/3` Packages * System Applications 4. User installed `fonts`. ### Configuration If you'd like to modify which files are backed up, you have to edit the `JSON` config file, located at `~/.config/shallow-backup.conf`. There are two ways to do this. 1. Select the appropriate option in the CLI and follow the prompts. 2. Open the file in a text editor and make your changes. Editing the file in a text editor will give you more control and be faster. #### Conditional Backup and Reinstallation > **Warning** > This feature allows code execution (by design). If untrusted users can write to your config, they can achieve code execution next time you invoke `shallow-backup` _backup_ or _reinstall_ functions. Starting in `v5.2`, the config file will have default permissions of `644`, and a warning will be printed if others can write to the config. Every key under dotfiles has two optional subkeys: `backup_condition` and `reinstall_condition`. Both of these accept expressions that will be evaluated with `bash`. An empty string (`""`) is the default value, and is considered to be `True`. If the return value of the expression is `0`, this is considered `True`. Otherwise, it is `False`. This lets you do simple things like preventing backup with: ```javascript // Because `$ false` returns 1 "backup_condition": "false" ``` And also more complicated things like only backing up certain files if an environment variable is set: ```javascript "backup_condition": "[[ -n \"$ENV_VAR\" ]]" ``` Here's an example config based on my [dotfiles](https://www.github.com/alichtman/dotfiles): ```json { "backup_path": "~/shallow-backup", "lowest_supported_version": "5.0.0a", "dotfiles": { ".config/agignore": { "backup_condition": "uname -a | grep Darwin", "reinstall_conditon": "uname -a | grep Darwin" }, ".config/git/gitignore_global": { }, ".config/jrnl/jrnl.yaml": { }, ".config/kitty": { }, ".config/nvim": { }, ".config/pycodestyle": { }, ... ".zshenv": { } }, "root-gitignore": [ ".DS_Store", "dotfiles/.config/nvim/.netrwhist", "dotfiles/.config/nvim/spell/en.utf-8.add", "dotfiles/.config/ranger/plugins/ranger_devicons", "dotfiles/.config/zsh/.zcompdump*", "dotfiles/.pypirc", "dotfiles/.ssh" ], "dotfiles-gitignore": [ ".DS_Store", ".config/nvim/.netrwhist", ".config/nvim/spell/en.utf-8.add*", ".config/ranger/plugins/*", ".config/zsh/.zcompdump*", ".config/zsh/.zinit", ".config/tmux/plugins", ".config/tmux/resurrect", ".pypirc", ".ssh/*" ], "config_mapping": { "/Users/alichtman/Library/Application Support/Sublime Text 2": "sublime2", "/Users/alichtman/Library/Application Support/Sublime Text 3": "sublime3", "/Users/alichtman/Library/Application Support/Code/User/settings.json": "vscode/settings", "/Users/alichtman/Library/Application Support/Code/User/Snippets": "vscode/Snippets", "/Users/alichtman/Library/Application Support/Code/User/keybindings.json": "vscode/keybindings", "/Users/alichtman/.atom": "atom", "/Users/alichtman/Library/Preferences/com.apple.Terminal.plist": "terminal_plist" } } ``` #### .gitignore As of `v4.0`, any `.gitignore` changes should be made in the `shallow-backup` config file. `.gitignore` changes that are meant to apply to all directories should be under the `root-gitignore` key. Dotfile specific gitignores should be placed under the `dotfiles-gitignore` key. The original `default-gitignore` key in the config is still supported for backwards compatibility, however, converting to the new config format is strongly encouraged. #### Output Structure --- ```shell backup_dir/ ├── configs │   ├── plist │   │   └── com.apple.Terminal.plist │   ├── sublime_2 │   │   └── ... │   └── sublime_3 │   └── ... ├── dotfiles │ ├── .bash_profile │ ├── .bashrc │ ├── .gitconfig │ ├── .pypirc │ ├── ... │ ├── .shallow-backup │   ├── .ssh/ │   │   └── known_hosts │   ├── .vim/ │ └── .zshrc ├── fonts │   ├── AllerDisplay.ttf │   ├── Aller_Bd.ttf │   ├── ... │   ├── Ubuntu Mono derivative Powerline Italic.ttf │   └── Ubuntu Mono derivative Powerline.ttf └── packages ├── brew-cask_list.txt ├── brew_list.txt ├── cargo_list.txt ├── gem_list.txt ├── installed_apps_list.txt ├── npm_list.txt ├── macports_list.txt ├── pip_list.txt └── sublime3_list.txt ``` ### Reinstalling Dotfiles ---- To reinstall your dotfiles, clone your dotfiles repo and make sure your shallow-backup config path can be found at either `~/.config/shallow-backup.conf` or `$XDG_CONFIG_HOME/.shallow_backup.conf`. Set the `backup-path` key in the config to the path of your cloned dotfiles. Then run `$ shallow-backup -reinstall-dots`. When reinstalling your dotfiles, the top level `.git/`, `.gitignore`, `img/` and `README.md` files and directories are ignored. ### Want to Contribute? --- Check out `CONTRIBUTING.md` and the `docs` directory. <file_sep>import os import sys from pathlib import Path from .testing_utility_functions import ( BACKUP_DEST_DIR, FAKE_HOME_DIR, DOTFILES, setup_dirs_and_env_vars_and_create_config, clean_up_dirs_and_env_vars, ) sys.path.insert(0, "../shallow_backup") from shallow_backup.backup import backup_dotfiles from shallow_backup.utils import safe_mkdir from shallow_backup.config import get_config, write_config TEST_TEXT_CONTENT = "THIS IS TEST CONTENT FOR THE DOTFILES" class TestBackupMethods: """Test the backup methods.""" @staticmethod def setup_method(): setup_dirs_and_env_vars_and_create_config() # Create all dotfiles and dotfolders for file in DOTFILES: if not file.endswith("/"): print(f"Creating file: {file}") os.makedirs(Path(file).parent, exist_ok=True) with open(file, "w+") as f: f.write(TEST_TEXT_CONTENT) else: directory = file print(f"Creating dir: {directory}") safe_mkdir(directory) for file_2 in ["test1", "test2"]: with open(os.path.join(directory, file_2), "w+") as f: f.write(TEST_TEXT_CONTENT) @staticmethod def teardown_method(): clean_up_dirs_and_env_vars() def test_backup_dotfiles(self): """Test backing up dotfiles and dotfolders.""" backup_dest_path = os.path.join(BACKUP_DEST_DIR, "dotfiles") backup_dotfiles( backup_dest_path, dry_run=False, home_path=FAKE_HOME_DIR, skip=True ) assert os.path.isdir(backup_dest_path) for path in DOTFILES: print( f"\nBACKUP DESTINATION DIRECTORY: ({backup_dest_path}) CONTENTS:", os.listdir(backup_dest_path), "", ) print(path + " should already be backed up.") backed_up_dot = os.path.join( backup_dest_path, path.replace(FAKE_HOME_DIR + "/", "") ) print(f"Backed up dot: {backed_up_dot}\n") assert os.path.isfile(backed_up_dot) or os.path.isdir(backed_up_dot) def test_conditions(self): """Test backing up files based on conditions""" # Set false backup condition of all files. config = get_config() print(config["dotfiles"]) for dot, _ in config["dotfiles"].items(): config["dotfiles"][dot][ "backup_condition" ] = "[[ $(uname -s) == 'Made Up OS' ]]" write_config(config) backup_dest_path = os.path.join(BACKUP_DEST_DIR, "dotfiles") backup_dotfiles( backup_dest_path, dry_run=False, home_path=FAKE_HOME_DIR, skip=True ) assert os.path.isdir(backup_dest_path) for path in DOTFILES: print( f"\nBACKUP DESTINATION DIRECTORY: ({backup_dest_path}) CONTENTS:", os.listdir(backup_dest_path), "", ) print(path + " should not be backed up.") backed_up_dot = os.path.join( backup_dest_path, path.replace(FAKE_HOME_DIR + "/", "") ) assert not (os.path.isfile(backed_up_dot) or os.path.isdir(backed_up_dot)) <file_sep>import os import sys import json import stat from os import path, environ, chmod from .printing import * from .compatibility import * from .utils import safe_mkdir, strip_home from .constants import ProjInfo def get_xdg_config_path() -> str: """Returns path to $XDG_CONFIG_HOME, or ~/.config, if it doesn't exist.""" return environ.get("XDG_CONFIG_HOME") or path.join(path.expanduser("~"), ".config") def get_config_path() -> str: """ Detects if in testing or prod env, and returns the right config path. :return: Path to config. """ test_config_path = environ.get("SHALLOW_BACKUP_TEST_CONFIG_PATH", None) if test_config_path: return test_config_path else: return path.join(get_xdg_config_path(), "shallow-backup.conf") def get_config() -> dict: """ :return Config. """ config_path = get_config_path() with open(config_path) as file: try: config = json.load(file) except json.decoder.JSONDecodeError: print_red_bold(f"ERROR: Invalid syntax in {config_path}") sys.exit(1) return config def write_config(config) -> None: """ Write to config file """ with open(get_config_path(), "w") as file: json.dump(config, file, indent=4) def get_default_config() -> dict: """Returns a default, platform specific config.""" return { "backup_path": "~/shallow-backup", "dotfiles": { ".bash_profile": { "backup_condition": "", "reinstall_condition": "", }, ".bashrc": {}, ".config/git": {}, ".config/nvim/init.vim": {}, ".config/tmux": {}, ".config/zsh": {}, ".profile": {}, ".pypirc": {}, ".ssh": {}, ".zshenv": {}, f"{strip_home(get_config_path())}": {}, }, "root-gitignore": ["dotfiles/.ssh", "dotfiles/.pypirc", ".DS_Store"], "dotfiles-gitignore": [ ".ssh", ".pypirc", ".DS_Store", ], "config_mapping": get_config_paths(), "lowest_supported_version": ProjInfo.VERSION, } def safe_create_config() -> None: """ Creates config file (with 644 permissions) if it doesn't exist already. Prompts to update it if an outdated version is detected. """ backup_config_path = get_config_path() # If it doesn't exist, create it. if not os.path.exists(backup_config_path): print_path_blue("Creating config file at:", backup_config_path) backup_config = get_default_config() safe_mkdir(os.path.split(backup_config_path)[0]) write_config(backup_config) # $ chmod 644 config_file chmod( get_config_path(), stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH ) def check_insecure_config_permissions() -> bool: """Checks to see if group/others can write to config file. Returns: True if they can, False otherwise.""" config_path = get_config_path() mode = os.stat(config_path).st_mode if mode & stat.S_IWOTH or mode & stat.S_IWGRP: print_red_bold( f"WARNING: {config_path} is writable by group/others and vulnerable to attack. To resolve, run: \n\t$ chmod 644 {config_path}" ) return True else: return False def delete_config_file() -> None: """Delete config file.""" config_path = get_config_path() if os.path.isfile(config_path): print_red_bold("Deleting config file.") os.remove(config_path) else: print_red_bold("ERROR: No config file found.") def add_dot_path_to_config(backup_config: dict, file_path: str) -> dict: """ Add dotfile to config with default reinstall and backup conditions. Exit if the file_path parameter is invalid. :backup_config: dict representing current config :file_path: str relative or absolute path of file to add to config :return new backup config """ abs_path = path.abspath(file_path) if not path.exists(abs_path): print_path_red("Invalid file path:", abs_path) return backup_config else: stripped_home_path = strip_home(abs_path) print_path_blue("Added:", stripped_home_path) backup_config["dotfiles"][stripped_home_path] = {} return backup_config def show_config(): """ Print the config. Colorize section titles and indent contents. """ print_section_header("SHALLOW BACKUP CONFIG", Fore.RED) for section, contents in get_config().items(): # Print backup path on same line if section == "backup_path": print_path_red("Backup Path:", contents) elif section == "config_mapping": print_red_bold("\nConfigs:") for config_path, dest in contents.items(): print(f" {config_path} -> {dest}") # Print section header and contents. (Dotfiles) elif section == "dotfiles": print_path_red( "\nDotfiles:", "(Backup and Reinstall conditions will be shown if they exist)", ) for dotfile, options in contents.items(): backup_condition = options.get("backup_condition", "") reinstall_condition = options.get("reinstall_condition", "") if backup_condition or reinstall_condition: print(f" {dotfile} ->") print(f'\t\tbackup_condition: "{backup_condition}"') print(f'\t\treinstall_condition: "{reinstall_condition}"') else: print(f" {dotfile}") elif section == "lowest_supported_version": print_path_red(f"{section.replace('_', ' ').capitalize()}:", contents) else: print_red_bold(f"\n{section.replace('-', ' ').capitalize()}: ") for item in contents: print(f" {item}") <file_sep>import os import json from shlex import quote from colorama import Fore import multiprocessing as mp from pathlib import Path from shutil import copyfile from .utils import * from .printing import * from .compatibility import * from .config import get_config def backup_dotfiles( backup_dest_path, dry_run=False, home_path=os.path.expanduser("~"), skip=False ): """ Create `dotfiles` dir and makes copies of dotfiles and dotfolders. Assumes that dotfiles are stored in the home directory. :param skip: Boolean flag to skip prompting for overwrite. Used for scripting. :param backup_dest_path: Destination path for dotfiles. Like, ~/shallow-backup/dotfiles. Used in tests. :param home_path: Path where dotfiles will be found. $HOME by default. :param dry_run: Flag for determining if debug info should be shown or copying should occur. """ print_section_header("DOTFILES", Fore.BLUE) if not dry_run: overwrite_dir_prompt_if_needed(backup_dest_path, skip) # get dotfolders and dotfiles config = get_config()["dotfiles"] # Aggregate pairs of [(Installed dotfile path, backup dest path)] in a list to be sorted into # dotfiles and dotfolders later dot_path_pairs = [] for dotfile_path_from_config, options in config.items(): # Evaluate condition, if specified. Skip if the command doesn't return true. condition_success = evaluate_condition( condition=options.get("backup_condition", ""), backup_or_reinstall="backup", dotfile_path=dotfile_path_from_config, ) if not condition_success: continue # If a file path in the config starts with /, it's a full path like /etc/ssh/ if dotfile_path_from_config.startswith("/"): installed_dotfile_path = dotfile_path_from_config installed_dotfile_path = quote(":" + installed_dotfile_path[1:]) backup_dotfile_path = quote( os.path.join(backup_dest_path, installed_dotfile_path) ) dot_path_pairs.append((dotfile_path_from_config, backup_dotfile_path)) else: # Dotfile living in $HOME installed_dotfile_path = quote( os.path.join(home_path, dotfile_path_from_config) ) backup_dotfile_path = quote( os.path.join(backup_dest_path, dotfile_path_from_config) ) dot_path_pairs.append((installed_dotfile_path, backup_dotfile_path)) # Separate dotfiles and dotfolders dotfolders_mp_in = [] dotfiles_mp_in = [] for path_pair in dot_path_pairs: installed_path = path_pair[0] if os.path.isdir(installed_path): dotfolders_mp_in.append(path_pair) else: dotfiles_mp_in.append(path_pair) # Print source -> dest and skip the copying step if dry_run: print_yellow_bold("Dotfiles:") for source, dest in dotfiles_mp_in: print_dry_run_copy_info(source, dest) print_yellow_bold("\nDotfolders:") for source, dest in dotfolders_mp_in: print_dry_run_copy_info(source, dest) return # Fix https://github.com/alichtman/shallow-backup/issues/230 for dest_path in [path_pair[1] for path_pair in dotfiles_mp_in + dotfolders_mp_in]: print(f"Creating: {os.path.split(dest_path)[0]}") safe_mkdir(os.path.split(dest_path)[0]) with mp.Pool(mp.cpu_count()): print_blue_bold("Backing up dotfolders...") for x in dotfolders_mp_in: p = mp.Process( target=copy_dir_if_valid, args=( x[0], x[1], ), ) p.start() p.join() print_blue_bold("Backing up dotfiles...") for x in dotfiles_mp_in: p = mp.Process( target=copyfile_with_exception_handler, args=( x[0], x[1], ), ) p.start() p.join() def backup_configs(backup_path, dry_run: bool = False, skip=False): """ Creates `configs` directory and places config backups there. Configs are application settings, generally. .plist files count. In the config file, the value of the configs dictionary is the dest path relative to the configs/ directory. """ print_section_header("CONFIGS", Fore.BLUE) # Don't clear any directories if this is a dry run if not dry_run: overwrite_dir_prompt_if_needed(backup_path, skip) config = get_config() print_blue_bold("Backing up configs...") # backup config files + dirs in backup_path/<target>/ for config_path, target in config["config_mapping"].items(): dest = os.path.join(backup_path, target) if dry_run: print_dry_run_copy_info(config_path, dest) continue quoted_dest = quote(dest) if os.path.isdir(config_path): copytree(config_path, quoted_dest, symlinks=True) elif os.path.isfile(config_path): parent_dir = Path(dest).parent safe_mkdir(parent_dir) copyfile(config_path, quoted_dest) def backup_packages(backup_path, dry_run: bool = False, skip=False): """ Creates `packages` directory and places install list text files there. """ def run_cmd_if_no_dry_run(command, dest, dry_run) -> int: if dry_run: print_dry_run_copy_info(f"$ {command}", dest) # Return -1 for any processes depending on chained successful commands (npm) return -1 else: return run_cmd_write_stdout(command, dest) print_section_header("PACKAGES", Fore.BLUE) if not dry_run: overwrite_dir_prompt_if_needed(backup_path, skip) # brew print_pkg_mgr_backup("brew") command = f"brew bundle dump --file {backup_path}/brew_list.txt" dest = f"{backup_path}/brew_list.txt" if not dry_run: if not run_cmd(command): print_yellow("brew package manager not found.") # ruby print_pkg_mgr_backup("gem") command = r"gem list | tail -n+1 | sed -E 's/\((default: )?(.*)\)/--version \2/'" dest = f"{backup_path}/gem_list.txt" run_cmd_if_no_dry_run(command, dest, dry_run) # cargo print_pkg_mgr_backup("cargo") command = ( r"cargo install --list | grep '^\w.*:$' | sed -E 's/ v(.*):$/ --version \1/'" ) dest = f"{backup_path}/cargo_list.txt" run_cmd_if_no_dry_run(command, dest, dry_run) # pip print_pkg_mgr_backup("pip") command = "pip list --format=freeze" dest = f"{backup_path}/pip_list.txt" run_cmd_if_no_dry_run(command, dest, dry_run) # pip3 print_pkg_mgr_backup("pip3") command = "pip3 list --format=freeze" dest = f"{backup_path}/pip3_list.txt" run_cmd_if_no_dry_run(command, dest, dry_run) # npm print_pkg_mgr_backup("npm") command = "npm ls --global --json=true --depth=0" temp_file_path = f"{backup_path}/npm_temp_list.json" # If command is successful, go to the next parsing step. npm_backup_cmd_success = ( run_cmd_if_no_dry_run(command, temp_file_path, dry_run) == 0 ) if npm_backup_cmd_success: npm_dest_file = f"{backup_path}/npm_list.txt" with open(temp_file_path, "r") as temp_file: npm_packages = json.load(temp_file).get("dependencies").keys() if len(npm_packages) >= 1: with open(npm_dest_file, "w") as dest: [dest.write(f"{package}\n") for package in npm_packages] os.remove(temp_file_path) # vscode extensions print_pkg_mgr_backup("VSCode") command = "code --list-extensions --show-versions" dest = f"{backup_path}/vscode_list.txt" run_cmd_if_no_dry_run(command, dest, dry_run) # macports print_pkg_mgr_backup("macports") command = "port installed requested" dest = f"{backup_path}/macports_list.txt" run_cmd_if_no_dry_run(command, dest, dry_run) # system installs print_pkg_mgr_backup("System Applications") applications_path = get_applications_dir() command = "ls {}".format(applications_path) dest = f"{backup_path}/system_apps_list.txt" run_cmd_if_no_dry_run(command, dest, dry_run) def backup_fonts(backup_path: str, dry_run: bool = False, skip: bool = False): """Copies all .ttf and .otf files in the to backup/fonts/""" print_section_header("FONTS", Fore.BLUE) if not dry_run: overwrite_dir_prompt_if_needed(backup_path, skip) print_blue("Copying '.otf' and '.ttf' fonts...") fonts_path = get_fonts_dir() if os.path.isdir(fonts_path): fonts = [ quote(os.path.join(fonts_path, font)) for font in os.listdir(fonts_path) if font.endswith(".otf") or font.endswith(".ttf") ] for font in fonts: dest = os.path.join(backup_path, font.split("/")[-1]) if os.path.exists(font): if dry_run: print_dry_run_copy_info(font, dest) else: copyfile(font, dest) else: print_red("Skipping fonts backup. No fonts directory found.") def backup_all( dotfiles_path, packages_path, fonts_path, configs_path, dry_run=False, skip=False ): """Complete backup procedure.""" backup_dotfiles(dotfiles_path, dry_run=dry_run, skip=skip) backup_packages(packages_path, dry_run=dry_run, skip=skip) backup_fonts(fonts_path, dry_run=dry_run, skip=skip) backup_configs(configs_path, dry_run=dry_run, skip=skip) # vim: autoindent noexpandtab tabstop=4 shiftwidth=4 <file_sep>import os import sys from .testing_utility_functions import ( setup_dirs_and_env_vars_and_create_config, clean_up_dirs_and_env_vars, FAKE_HOME_DIR, ) sys.path.insert(0, "../shallow_backup") from shallow_backup.config import ( get_config, get_config_path, add_dot_path_to_config, check_insecure_config_permissions, ) from shallow_backup.utils import strip_home class TestConfigMethods: """Test the config methods.""" @staticmethod def setup_method(): setup_dirs_and_env_vars_and_create_config() @staticmethod def teardown_method(): clean_up_dirs_and_env_vars() def test_add_path(self): config = get_config() home_path = os.path.expanduser("~") invalid_path = "some_random_nonexistent_path" path_to_add = os.path.join(home_path, invalid_path) new_config = add_dot_path_to_config(config, path_to_add) assert strip_home(invalid_path) not in new_config["dotfiles"] valid_path = "valid" path_to_add = os.path.join(FAKE_HOME_DIR, valid_path) os.mkdir(path_to_add) new_config = add_dot_path_to_config(config, path_to_add) from pprint import pprint pprint(new_config) stripped_home_path = strip_home(path_to_add) assert stripped_home_path in new_config["dotfiles"] assert isinstance(new_config["dotfiles"][stripped_home_path], dict) def test_detect_insecure_config_permissions(self): print(f"Testing config path: {get_config_path()}") os.chmod(get_config_path(), 0o777) assert check_insecure_config_permissions() == True def test_secure_config_created_by_default(self): print(f"Testing config path: {get_config_path()}") assert check_insecure_config_permissions() == False <file_sep>import os import sys import inquirer from colorama import Fore, Style from .constants import ProjInfo def print_blue(text): print(Fore.BLUE + text + Style.RESET_ALL) def print_red(text): print(Fore.RED + text + Style.RESET_ALL) def print_yellow(text): print(Fore.YELLOW + text + Style.RESET_ALL) def print_green(text): print(Fore.GREEN + text + Style.RESET_ALL) def print_blue_bold(text): print(Fore.BLUE + Style.BRIGHT + text + Style.RESET_ALL) def print_red_bold(text): print(Fore.RED + Style.BRIGHT + text + Style.RESET_ALL) def print_yellow_bold(text): print(Fore.YELLOW + Style.BRIGHT + text + Style.RESET_ALL) def print_green_bold(text): print(Fore.GREEN + Style.BRIGHT + text + Style.RESET_ALL) def print_path_blue(text, path): print(Fore.BLUE + Style.BRIGHT + text, Style.NORMAL + path + Style.RESET_ALL) def print_path_red(text, path): print(Fore.RED + Style.BRIGHT + text, Style.NORMAL + path + Style.RESET_ALL) def print_path_yellow(text, path): print(Fore.YELLOW + Style.BRIGHT + text, Style.NORMAL + path + Style.RESET_ALL) def print_path_green(text, path): print(Fore.GREEN + Style.BRIGHT + text, Style.NORMAL + path + Style.RESET_ALL) def print_dry_run_copy_info(source, dest): """Show source -> dest copy. Replaces expanded ~ with ~ if it's at the beginning of paths. source and dest are trimmed in the middle if needed. Removed characters will be replaced by ... :param source: Can be of type str or Path :param dest: Can be of type str or Path """ def shorten_home(path): expanded_home = os.path.expanduser("~") path = str(path) if path.startswith(expanded_home): return path.replace(expanded_home, "~") return path def truncate_middle(path: str, acceptable_len: int): """Middle truncate a string https://www.xormedia.com/string-truncate-middle-with-ellipsis/ """ if len(path) <= acceptable_len: return path # half of the size, minus the 3 .'s n_2 = int(acceptable_len / 2 - 3) # whatever's left n_1 = int(acceptable_len - n_2 - 3) return f"{path[:n_1]}...{path[-n_2:]}" trimmed_source = shorten_home(source) trimmed_dest = shorten_home(dest) longest_allowed_path_len = 87 if len(trimmed_source) + len(trimmed_dest) > longest_allowed_path_len: trimmed_source = truncate_middle(trimmed_source, longest_allowed_path_len) trimmed_dest = truncate_middle(trimmed_dest, longest_allowed_path_len) print( Fore.YELLOW + Style.BRIGHT + trimmed_source + Style.NORMAL, "->", Style.BRIGHT + trimmed_dest + Style.RESET_ALL, ) def print_version_info(cli=True): """ Formats version differently for CLI and splash screen. """ version = "v{} by {} (@{})".format( ProjInfo.VERSION, ProjInfo.AUTHOR_FULL_NAME, ProjInfo.AUTHOR_GITHUB ) if not cli: print(Fore.RED + Style.BRIGHT + "\t{}\n".format(version) + Style.RESET_ALL) else: print(version) def splash_screen(): """Display splash graphic, and then stylized version and author info.""" print(Fore.YELLOW + Style.BRIGHT + "\n" + ProjInfo.LOGO + Style.RESET_ALL) print_version_info(False) def print_section_header(title, color): """Prints variable sized section header.""" block = "#" * (len(title) + 2) print("\n" + color + Style.BRIGHT + block) print("#", title) print(block + "\n" + Style.RESET_ALL) def print_pkg_mgr_backup(mgr): print( "{}Backing up {}{}{}{}{} packages list...{}".format( Fore.BLUE, Style.BRIGHT, Fore.YELLOW, mgr, Fore.BLUE, Style.NORMAL, Style.RESET_ALL, ) ) def print_pkg_mgr_reinstall(mgr): print( "{}Reinstalling {}{}{}{}{}...{}".format( Fore.BLUE, Style.BRIGHT, Fore.YELLOW, mgr, Fore.BLUE, Style.NORMAL, Style.RESET_ALL, ) ) # TODO: BUG: Why does moving this to prompts.py cause circular imports? def prompt_yes_no(message, color, invert=False): """ Print question and return True or False depending on user selection from list. """ questions = [ inquirer.List( "choice", message=color + Style.BRIGHT + message + Fore.BLUE, choices=(" No", " Yes") if invert else (" Yes", " No"), ) ] answers = inquirer.prompt(questions) if answers: return answers.get("choice").strip().lower() == "yes" else: sys.exit(1) <file_sep>import os import sys import pytest from .testing_utility_functions import ( clean_up_dirs_and_env_vars, BACKUP_DEST_DIR, FAKE_HOME_DIR, create_dir_overwrite, setup_env_vars, create_config_for_test, ) sys.path.insert(0, "../shallow_backup") from shallow_backup.utils import copy_dir_if_valid class TestCopyMethods: """ Test the functionality of copying """ @staticmethod def setup_method(): setup_env_vars() create_config_for_test() create_dir_overwrite(FAKE_HOME_DIR) @staticmethod def teardown_method(): clean_up_dirs_and_env_vars() def test_copy_dir(self): """ Test that copying a directory works as expected """ # TODO: Test that all subfiles and folders are copied. test_file_name = "test-file.txt" test_dir_name = "subdir-to-copy" os.mkdir(os.path.join(FAKE_HOME_DIR, test_dir_name)) with open(os.path.join(FAKE_HOME_DIR, test_file_name), "w+") as file: file.write("TRASH") copy_dir_if_valid(FAKE_HOME_DIR, BACKUP_DEST_DIR) assert os.path.isfile(os.path.join(BACKUP_DEST_DIR, test_file_name)) assert os.path.isdir(os.path.join(BACKUP_DEST_DIR, test_dir_name)) @pytest.mark.parametrize("invalid", {".Trash", ".npm", ".cache", ".rvm"}) def test_copy_dir_invalid(self, invalid): """ Test that attempting to copy an invalid directory fails """ copy_dir_if_valid(invalid, FAKE_HOME_DIR) assert not os.path.isdir(os.path.join(BACKUP_DEST_DIR, invalid)) <file_sep>import os import sys from .testing_utility_functions import ( FAKE_HOME_DIR, setup_dirs_and_env_vars_and_create_config, clean_up_dirs_and_env_vars, ) sys.path.insert(0, "../shallow_backup") from shallow_backup.reinstall import reinstall_dots_sb TEST_TEXT_CONTENT = "THIS IS TEST CONTENT FOR THE DOTFILES" DOTFILES_PATH = os.path.join(FAKE_HOME_DIR, "dotfiles/") class TestReinstallDotfiles: """ Test the functionality of reinstalling dotfiles """ @staticmethod def setup_method(): def create_nested_dir(parent, name): new_dir = os.path.join(parent, name) print(f"Creating {new_dir}") if not os.path.isdir(new_dir): os.makedirs(new_dir) return new_dir def create_file(parent, name): file = os.path.join(parent, name) print(f"Creating {file}") with open(file, "w+") as f: f.write(TEST_TEXT_CONTENT) def create_git_dir(parent): git_dir = create_nested_dir(parent, ".git/") git_objects = create_nested_dir(git_dir, "objects/") create_file(git_dir, "config") create_file(git_objects, "obj1") return git_dir setup_dirs_and_env_vars_and_create_config() # Dotfiles / dirs to NOT reinstall create_git_dir(DOTFILES_PATH) # Should NOT reinstall DOTFILES_PATH/.git img_dir_should_not_reinstall = create_nested_dir(DOTFILES_PATH, "img") create_file(img_dir_should_not_reinstall, "test.png") create_file(DOTFILES_PATH, "README.md") create_file(DOTFILES_PATH, ".gitignore") # Dotfiles / dirs to reinstall testfolder = create_nested_dir(DOTFILES_PATH, ".config/tmux/") testfolder2 = create_nested_dir(testfolder, "testfolder2/") create_file(testfolder2, "test.sh") create_git_dir(testfolder2) git_config = create_nested_dir(DOTFILES_PATH, ".config/git") create_file(git_config, "test") create_file(testfolder2, ".gitignore") create_file(DOTFILES_PATH, ".zshenv") @staticmethod def teardown_method(): clean_up_dirs_and_env_vars() def test_reinstall_dotfiles(self): """ Test reinstalling dotfiles to fake home dir """ reinstall_dots_sb( dots_path=DOTFILES_PATH, home_path=FAKE_HOME_DIR, dry_run=False ) assert os.path.isfile(os.path.join(FAKE_HOME_DIR, ".zshenv")) testfolder2 = os.path.join( os.path.join(FAKE_HOME_DIR, ".config/tmux/"), "testfolder2" ) assert os.path.isdir(testfolder2) assert os.path.isfile(os.path.join(testfolder2, "test.sh")) assert os.path.isdir(os.path.join(FAKE_HOME_DIR, ".config/git/")) # Do reinstall other git files assert os.path.isdir(os.path.join(testfolder2, ".git")) assert os.path.isfile(os.path.join(testfolder2, ".gitignore")) # Don't reinstall root-level git files assert not os.path.isdir(os.path.join(FAKE_HOME_DIR, ".git")) assert not os.path.isfile(os.path.join(FAKE_HOME_DIR, ".gitignore")) # Don't reinstall img or README.md assert not os.path.isdir(os.path.join(FAKE_HOME_DIR, "img")) assert not os.path.isfile(os.path.join(FAKE_HOME_DIR, "README.md")) <file_sep>import os import shutil import sys sys.path.insert(0, "../shallow_backup") from shallow_backup.config import safe_create_config def setup_env_vars(): os.environ["SHALLOW_BACKUP_TEST_BACKUP_DIR"] = ( os.path.abspath(BASE_TEST_DIR) + "/backup" ) os.environ["SHALLOW_BACKUP_TEST_HOME_DIR"] = ( os.path.abspath(BASE_TEST_DIR) + "/home" ) # This env var is referenced in shallow_backup/config.py os.environ["SHALLOW_BACKUP_TEST_CONFIG_PATH"] = ( os.path.abspath(BASE_TEST_DIR) + "/shallow-backup.conf" ) def unset_env_vars(): del os.environ["SHALLOW_BACKUP_TEST_BACKUP_DIR"] del os.environ["SHALLOW_BACKUP_TEST_HOME_DIR"] del os.environ["SHALLOW_BACKUP_TEST_CONFIG_PATH"] def create_config_for_test(): config_file = os.environ["SHALLOW_BACKUP_TEST_CONFIG_PATH"] if os.path.isfile(config_file): os.remove(config_file) safe_create_config() def create_dir_overwrite(directory): if os.path.isdir(directory): shutil.rmtree(directory) os.makedirs(directory) def setup_dirs_and_env_vars_and_create_config(): setup_env_vars() create_config_for_test() for directory in DIRS: create_dir_overwrite(directory) def clean_up_dirs_and_env_vars(): shutil.rmtree(BASE_TEST_DIR) unset_env_vars() # TODO: Update to tempfile and tempdir because testing in the home directory is so stupid. # These globals must remain at the bottom of this file for some reason # This global is required to be set for the setup_env_vars call to work properly. BASE_TEST_DIR = os.path.expanduser("~") + "/SHALLOW-BACKUP-TEST-DIRECTORY" setup_env_vars() BACKUP_DEST_DIR = os.environ.get("SHALLOW_BACKUP_TEST_BACKUP_DIR") FAKE_HOME_DIR = os.environ.get("SHALLOW_BACKUP_TEST_HOME_DIR") DIRS = [BACKUP_DEST_DIR, FAKE_HOME_DIR] DOTFILES = [ os.path.join(FAKE_HOME_DIR, ".ssh/"), os.path.join(FAKE_HOME_DIR, ".config/git/"), os.path.join(FAKE_HOME_DIR, ".zshenv"), os.path.join(FAKE_HOME_DIR, ".pypirc"), os.path.join(FAKE_HOME_DIR, ".config/nvim/init.vim"), os.path.join(FAKE_HOME_DIR, ".config/zsh/.zshrc"), ] <file_sep>import sys from .testing_utility_functions import setup_env_vars, unset_env_vars sys.path.insert(0, "../shallow_backup") from shallow_backup.utils import run_cmd_return_bool class TestUtilMethods: """ Test the functionality of utils """ @staticmethod def setup_method(): setup_env_vars() @staticmethod def teardown_method(): unset_env_vars() def test_run_cmd_return_bool(self): """Test that evaluating bash commands to get booleans works as expected""" # Basic bash conditionals with command substitution should_fail = "[[ -z $(uname -s) ]]" assert run_cmd_return_bool(should_fail) is False should_pass = "[[ -n $(uname -s) ]]" assert run_cmd_return_bool(should_pass) is True # Using env vars should_pass = '[[ -n "$SHALLOW_BACKUP_TEST_BACKUP_DIR" ]]' assert run_cmd_return_bool(should_pass) is True should_pass = "[[ -n $SHALLOW_BACKUP_TEST_BACKUP_DIR ]]" assert run_cmd_return_bool(should_pass) is True <file_sep>import os from shlex import quote from .utils import ( run_cmd, get_abs_path_subfiles, exit_if_dir_is_empty, safe_mkdir, evaluate_condition, ) from .printing import * from .compatibility import * from .config import get_config from pathlib import Path from shutil import copytree, copyfile, copy # NOTE: Naming convention is like this since the CLI flags would otherwise # conflict with the function names. def reinstall_dots_sb( dots_path: str, home_path: str = os.path.expanduser("~"), dry_run: bool = False ): """Reinstall all dotfiles and folders by copying them from dots_path to a path relative to home_path, or to an absolute path.""" exit_if_dir_is_empty(dots_path, "dotfile") print_section_header("REINSTALLING DOTFILES", Fore.BLUE) # Get paths of ALL files that we will be reinstalling from config. # If .ssh is in the config, full paths of all dots_path/.ssh/* files # will be in dotfiles_to_reinstall config = get_config()["dotfiles"] dotfiles_to_reinstall = [] for dotfile_path_from_config, options in config.items(): # Evaluate condition, if specified. Skip if the command doesn't return true. condition_success = evaluate_condition( condition=options.get("reinstall_condition", ""), backup_or_reinstall="reinstall", dotfile_path=dotfile_path_from_config, ) if not condition_success: continue real_path_dotfile = os.path.join(dots_path, dotfile_path_from_config) if os.path.isfile(real_path_dotfile): dotfiles_to_reinstall.append(real_path_dotfile) else: subfiles_to_add = get_abs_path_subfiles(real_path_dotfile) dotfiles_to_reinstall.extend(subfiles_to_add) # Create list of tuples containing source and dest paths for dotfile reinstallation # The absolute file paths prepended with ':' are converted back to valid paths # Format: [(source, dest), ... ] full_path_dotfiles_to_reinstall = [] for source in dotfiles_to_reinstall: # If it's an absolute path, dest is the corrected path if source.startswith(":"): dest = "/" + source[1:] else: # Otherwise, it should go in a path relative to the home path dest = source.replace(dots_path, home_path + "/") full_path_dotfiles_to_reinstall.append((Path(source), Path(dest))) # Copy files from backup to system for dot_source, dot_dest in full_path_dotfiles_to_reinstall: if dry_run: print_dry_run_copy_info(dot_source, dot_dest) continue # Create dest parent dir if it doesn't exist safe_mkdir(dot_dest.parent) try: copy(dot_source, dot_dest) except PermissionError as err: print_red_bold(f"ERROR: {err}") except FileNotFoundError as err: print_red_bold(f"ERROR: {err}") print_section_header("DOTFILE REINSTALLATION COMPLETED", Fore.BLUE) def reinstall_fonts_sb(fonts_path: str, dry_run: bool = False): """Reinstall all fonts.""" exit_if_dir_is_empty(fonts_path, "font") print_section_header("REINSTALLING FONTS", Fore.BLUE) # Copy every file in fonts_path to ~/Library/Fonts for font in get_abs_path_subfiles(fonts_path): fonts_dir = get_fonts_dir() dest_path = quote(os.path.join(fonts_dir, font.split("/")[-1])) if dry_run: print_dry_run_copy_info(font, dest_path) continue copyfile(quote(font), quote(dest_path)) print_section_header("FONT REINSTALLATION COMPLETED", Fore.BLUE) def reinstall_configs_sb(configs_path: str, dry_run: bool = False): """Reinstall all configs from the backup.""" exit_if_dir_is_empty(configs_path, "config") print_section_header("REINSTALLING CONFIG FILES", Fore.BLUE) config = get_config() for dest_path, backup_loc in config["config_mapping"].items(): dest_path = quote(dest_path) source_path = quote(os.path.join(configs_path, backup_loc)) if dry_run: print_dry_run_copy_info(source_path, dest_path) continue if os.path.isdir(source_path): copytree(source_path, dest_path) elif os.path.isfile(source_path): copyfile(source_path, dest_path) print_section_header("CONFIG REINSTALLATION COMPLETED", Fore.BLUE) def reinstall_packages_sb(packages_path: str, dry_run: bool = False): """Reinstall all packages from the files in backup/installs.""" def run_cmd_if_no_dry_run(command, dry_run) -> int: if dry_run: print_yellow_bold(f"$ {command}") # Return 0 for any processes depending on chained successful commands return 0 else: return run_cmd(command) exit_if_dir_is_empty(packages_path, "package") print_section_header("REINSTALLING PACKAGES", Fore.BLUE) # Figure out which install lists they have saved package_mgrs = set() for file in os.listdir(packages_path): manager = file.split("_")[0].replace("-", " ") if manager in [ "gem", "cargo", "npm", "pip", "pip3", "brew", "vscode", "macports", ]: package_mgrs.add(file.split("_")[0]) print_blue_bold("Package Manager Backups Found:") for mgr in package_mgrs: print_yellow("\t{}".format(mgr)) print() # TODO: Multithreading for reinstallation. # Construct reinstallation commands and execute them for pm in package_mgrs: if pm == "brew": print_pkg_mgr_reinstall(pm) cmd = f"brew bundle install --no-lock --file {packages_path}/brew_list.txt" run_cmd_if_no_dry_run(cmd, dry_run) elif pm == "npm": print_pkg_mgr_reinstall(pm) cmd = f"cat {packages_path}/npm_list.txt | xargs npm install -g" run_cmd_if_no_dry_run(cmd, dry_run) elif pm == "pip": print_pkg_mgr_reinstall(pm) cmd = f"pip install -r {packages_path}/pip_list.txt" run_cmd_if_no_dry_run(cmd, dry_run) elif pm == "pip3": print_pkg_mgr_reinstall(pm) cmd = f"pip3 install -r {packages_path}/pip3_list.txt" run_cmd_if_no_dry_run(cmd, dry_run) elif pm == "vscode": print_pkg_mgr_reinstall(pm) with open(f"{packages_path}/vscode_list.txt", "r") as file: for package in file: cmd = f"code --install-extension {package}" run_cmd_if_no_dry_run(cmd, dry_run) elif pm == "macports": print_red_bold("WARNING: Macports reinstallation is not supported.") elif pm == "gem": print_pkg_mgr_reinstall(pm) cmd = f"cat {packages_path}/gem_list.txt | xargs -L 1 gem install" run_cmd_if_no_dry_run(cmd, dry_run) elif pm == "cargo": print_pkg_mgr_reinstall(pm) cmd = f"cat {packages_path}/cargo_list.txt | xargs -L 1 cargo install" run_cmd_if_no_dry_run(cmd, dry_run) print_section_header("PACKAGE REINSTALLATION COMPLETED", Fore.BLUE) def reinstall_all_sb( dotfiles_path: str, packages_path: str, fonts_path: str, configs_path: str, dry_run: bool = False, ): """Call all reinstallation methods.""" reinstall_dots_sb(dotfiles_path, dry_run=dry_run) reinstall_packages_sb(packages_path, dry_run=dry_run) reinstall_fonts_sb(fonts_path, dry_run=dry_run) reinstall_configs_sb(configs_path, dry_run=dry_run) <file_sep>#!/bin/bash # Release script for shallow-backup # NOTE: Must be run from project root directory set -e # Check if on master BRANCH=$(git rev-parse --abbrev-ref HEAD) if [[ "$BRANCH" != "master" ]]; then echo 'Must be on master branch to cut a release!'; exit 1; fi # Check if master is dirty if [[ -n $(git status -s) ]]; then echo 'Master branch dirty! Aborting.'; exit 1; fi SB_VERSION="v$(python3 -c "from shallow_backup.constants import ProjInfo; print(ProjInfo.VERSION)")" SB_VERSION_NO_V="$(python3 -c "from shallow_backup.constants import ProjInfo; print(ProjInfo.VERSION)")" read -r -p "Release shallow-backup $SB_VERSION? Version bump should already be committed and pushed. [y/N] " response case "$response" in [yY][eE][sS]|[yY]) echo "Releasing." ;; *) echo "Aborting." exit; ;; esac git checkout master && git pull git tag -a "$SB_VERSION" -m "shallow-backup $SB_VERSION" && git push github_changelog_generator --user alichtman --project shallow-backup git add CHANGELOG.md && git commit -m "Add CHANGELOG for $SB_VERSION" && git push echo "Generating distribution files..." rm -rf dist/* && python3 setup.py sdist echo "Creating GH release..." hub release create "$SB_VERSION" --file "dist/shallow-backup-$SB_VERSION_NO_V.tar.gz" -m "shallow-backup $SB_VERSION" echo "Uploading to pypi..." twine upload --repository pypi dist/* <file_sep>import sys from .config import get_config from .printing import print_red_bold, print_red from .constants import ProjInfo def check_if_config_upgrade_needed(): """Checks if a config is supported by the current version of shallow-backup""" config = get_config() # If this key is not in the config, that means the config was installed pre-v5.0.0a if "lowest_supported_version" not in config: print_red_bold( f"ERROR: Config version detected as incompatible with current shallow-backup version ({ProjInfo.VERSION})." ) print_red("There are two possible fixes.") print_red( "1. Backup your config file to another location and remove the original config." ) print_red("\tshallow-backup will recreate a compatible config on the next run.") print_red("\tYou can then add in your custom backup paths manually.") print_red("2. Manually upgrade the config.") print_red_bold( "Please downgrade to a version of shallow-backup before v5.0.0a if you do not want to upgrade your config." ) sys.exit() <file_sep>import os import sys from .testing_utility_functions import ( FAKE_HOME_DIR, clean_up_dirs_and_env_vars, setup_dirs_and_env_vars_and_create_config, ) sys.path.insert(0, "../shallow_backup") from shallow_backup.utils import destroy_backup_dir TEST_BACKUP_TEXT_FILE = os.path.join(FAKE_HOME_DIR, "test-file.txt") class TestDeleteMethods: """ Test the functionality of deleting """ @staticmethod def setup_method(): setup_dirs_and_env_vars_and_create_config() with open(TEST_BACKUP_TEXT_FILE, "w+") as file: file.write("RANDOM TEXT") @staticmethod def teardown_method(): clean_up_dirs_and_env_vars() def test_clean_an_existing_backup_directory(self): """ Test that deleting the backup directory works as expected """ assert os.path.isdir(FAKE_HOME_DIR) assert os.path.isfile(TEST_BACKUP_TEXT_FILE) destroy_backup_dir(FAKE_HOME_DIR) assert not os.path.isdir(FAKE_HOME_DIR) assert not os.path.isfile(TEST_BACKUP_TEXT_FILE) def test_can_handle_cleaning_non_existing_backup_directory(self): """ Test that we exit gracefully when cleaning an non existing backup directory """ nonexist_backup_dir = os.path.join(FAKE_HOME_DIR, "NON-EXISTENT") assert not os.path.isdir(nonexist_backup_dir) destroy_backup_dir(nonexist_backup_dir) assert not os.path.isdir(nonexist_backup_dir)
203986955971f17a79fa97d49a9ab72176a1ae89
[ "TOML", "Python", "Markdown", "Shell" ]
18
Python
Fred-Barclay/shallow-backup
05203bdddb041e4183b80cb79368adffc85e938d
5dddedd7cba94b8234ac81675500cb8c6a908c88
refs/heads/master
<file_sep>import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class LanzadorCliente { private static InputStreamReader isr = new InputStreamReader(System.in); private static BufferedReader teclado = new BufferedReader(isr); public static void main(String[] args) { System.out.println("Introduce tu nombre de usuario:"); String nombre=""; try { nombre = teclado.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Hola " + nombre + ", Bienvenido al chat"); ClienteEscribir c1 = new ClienteEscribir("localhost", 5000, nombre); ClienteLeer c2 = new ClienteLeer("localhost", 5000, nombre); Thread t1 = new Thread(c1); Thread t2 = new Thread(c2); t1.start(); t2.start(); } } <file_sep> import java.net.*; import java.io.*; public class ServerThread extends Thread { protected Socket clientSocket; private String nombreCliente; public ServerThread(Socket clientSoc) { clientSocket = clientSoc; } public void run() { System.out.println("Iniciando hilo......"); try { PrintWriter respuesta = new PrintWriter(clientSocket.getOutputStream(),true); BufferedReader lectura = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine = ""; while ((inputLine = lectura.readLine()) != null) { try { synchronized (Servidor.listaClientes) { //Respondo a todos los clientes for (int i = 0; i < Servidor.listaClientes.size(); i++) { if (!Servidor.listaClientes.get(i).getClientSocket().isClosed()) { respuesta = new PrintWriter(Servidor.listaClientes.get(i).getClientSocket().getOutputStream(), true); respuesta.println(inputLine); } }//End for //Elimino clientes desconectados for (int i = 0; i < Servidor.listaClientes.size(); i++) { if (Servidor.listaClientes.get(i).getClientSocket().isClosed()) Servidor.listaClientes.remove(i); }//End for } } catch (Exception e) { e.printStackTrace(); } System.out.println("Server: " + inputLine); if (inputLine.substring(inputLine.indexOf(':') + 2).equals("Bye.")) { System.out.println("Cerrando cliente"); Thread.interrupted(); Servidor.listaClientes.remove(this); }//End if }//End while respuesta.close(); lectura.close(); clientSocket.close(); } catch (IOException e) { System.out.println("Algún cliente se ha desconectado del servidor"); } } public void setNombreCliente(String nombreCliente) { this.nombreCliente = nombreCliente; } public String getNombreCliente() { return nombreCliente; } public Socket getClientSocket() { return clientSocket; } public void setClientSocket(Socket clientSocket) { this.clientSocket = clientSocket; } }<file_sep>import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; public class ClienteEscribir implements Runnable { private static InputStreamReader isr = new InputStreamReader(System.in); private static BufferedReader teclado = new BufferedReader(isr); private String serverHostname = new String("localhost"); private int port = 5000; private String nombre = ""; public ClienteEscribir(String serverHostname, int port, String nombre) { super(); this.serverHostname = serverHostname; this.port = port; this.nombre = nombre; } public ClienteEscribir() { } @Override public void run() { System.out.println("Intentando conexión del cliente " + nombre + " al servidor" + serverHostname + " en puerto " + port); Socket s = null; PrintWriter pw = null; String texto="" ; try { s = new Socket(serverHostname, 5000); pw = new PrintWriter(s.getOutputStream(), true); } catch (UnknownHostException e) { System.err.println("No conozco el servidor: " + serverHostname); System.exit(1); } catch (IOException e) { System.err.println("No consigo entrar " + "al servidor "+ serverHostname); System.exit(1); } System.out.println("Conectado al servidor. Escribe \"Bye.\" para desconectarte"); boolean flag=true; while(flag) { try { texto = teclado.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (texto.equals("Bye.")) { pw.println(nombre + ": " + texto); System.out.println("DESCONECTO DEL SERVIDOR, CIERRO EL CHAT"); flag=false; Thread.interrupted(); } if(texto!="") pw.println(nombre + ": " + texto); } } }
7ba35ecaa47458ac41d74e4bec4cab0b61b89e3d
[ "Java" ]
3
Java
google-code/chat-java-filipinas
70b00d8c49499a0514335979543040441885b7d2
b491542283ef27a6930f8bc35436e0508ec99766
refs/heads/master
<file_sep>// // Filter.swift // Yelp // // Created by <NAME> on 9/25/15. // Copyright © 2015 <NAME>. All rights reserved. // import UIKit class Filter: NSObject { var deal: Bool? var distance: Int? var sortBy: YelpSortMode? var categories: [String]! } <file_sep>// // ButtonCell.swift // Yelp // // Created by <NAME> on 9/25/15. // Copyright © 2015 <NAME>. All rights reserved. // import UIKit class ButtonCell: UITableViewCell { @IBOutlet weak var rowLabel: UILabel! @IBOutlet weak var button: UIButton! override func awakeFromNib() { super.awakeFromNib() // button.layer.borderColor = UIColor.darkGrayColor().CGColor // button.backgroundColor = UIColor.lightGrayColor() button.setImage(UIImage(named: "buttonoff.png"), forState: UIControlState.Normal) button.setImage(UIImage(named: "buttonOn.png"), forState: UIControlState.Selected) // Initialization code } var select: Bool! { didSet { if (select != nil) && select == true { // button.layer.borderColor = UIColor.darkGrayColor().CGColor // button.backgroundColor = UIColor.redColor() button.setImage(UIImage(named: "buttonOn.png"), forState: UIControlState.Normal) print("setting Button Images") } else { // button.layer.borderColor = UIColor.darkGrayColor().CGColor // button.backgroundColor = UIColor.lightGrayColor() button.setImage(UIImage(named: "buttonoff.png"), forState: UIControlState.Normal) print("setting Button Images") } } } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } <file_sep>// // FiltersViewController.swift // Yelp // // Created by <NAME> on 9/22/15. // Copyright © 2015 <NAME>. All rights reserved. // import UIKit @objc protocol FiltersViewControllerDelegate { optional func filtersViewController(filtersViewController: FiltersViewController, didUpdateFilters filters: Filter) } class FiltersViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, SwitchCellDelegate { @IBOutlet weak var tableView: UITableView! weak var delegate: FiltersViewControllerDelegate? var categories = [[String:String]]() var switchStates = [NSIndexPath:Bool]() override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self tableView.estimatedRowHeight = 100 tableView.rowHeight = UITableViewAutomaticDimension loadCategories() // categories = yelpCategories(); // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func loadCategories() { let categoriesURL = NSURL(string: "https://s3-media2.fl.yelpcdn.com/assets/srv0/developer_pages/5e749b17ad6a/assets/json/categories.json") let request = NSURLRequest(URL: categoriesURL!, cachePolicy: .UseProtocolCachePolicy, timeoutInterval: 0.0) let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in if let error = error { print(error.localizedDescription) } else { let json = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0)) as? NSArray if let json = json { for category in json! { for parent in (category["parents"] as! NSArray) { if !parent.isKindOfClass(NSNull) && (parent as! String) == "restaurants"{ let categoryToAdd = ["name":(category["title"] as! String), "code":(category["alias"] as! String)] self.categories.append(categoryToAdd) } } } } } dispatch_async(dispatch_get_main_queue(), { () -> Void in self.tableView.reloadData() }) } task.resume() } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return Sections.count.rawValue } // func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { // return Sections(rawValue: section)?.getTitle() // } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerCell = tableView.dequeueReusableCellWithIdentifier("HeaderCell") as! CustomHeaderCell headerCell.backgroundColor = UIColor.whiteColor() switch (section) { case 0: headerCell.headerLabel.text = Sections(rawValue: section)?.getTitle() //return sectionHeaderView case 1: headerCell.headerLabel.text = Sections(rawValue: section)?.getTitle() //return sectionHeaderView case 2: headerCell.headerLabel.text = Sections(rawValue: section)?.getTitle() //return sectionHeaderView default: headerCell.headerLabel.text = Sections(rawValue: section)?.getTitle() } return headerCell } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch Sections(rawValue: indexPath.section)! { case .offeringDeal: let cell = tableView.dequeueReusableCellWithIdentifier("SwitchCell", forIndexPath:indexPath) as! SwitchCell cell.switchLabel.text = "Offering a Deal" cell.delegate = self cell.onSwitch.on = switchStates[indexPath] ?? false return cell case .distance: let cell = tableView.dequeueReusableCellWithIdentifier("ButtonCell", forIndexPath: indexPath) as! ButtonCell cell.rowLabel.text = Distances(rawValue: indexPath.row)?.getDistanceTitle() cell.select = switchStates[indexPath] ?? false return cell case .sortBy: let cell = tableView.dequeueReusableCellWithIdentifier("ButtonCell", forIndexPath: indexPath) as! ButtonCell cell.rowLabel.text = YelpSortMode(rawValue: indexPath.row)?.getTitle() cell.select = switchStates[indexPath] ?? false return cell case .category: let cell = tableView.dequeueReusableCellWithIdentifier("SwitchCell", forIndexPath:indexPath) as! SwitchCell cell.switchLabel.text = categories[indexPath.row]["name"] cell.delegate = self cell.onSwitch.on = switchStates[indexPath] ?? false return cell case .count: let cell = tableView.dequeueReusableCellWithIdentifier("SwitchCell", forIndexPath:indexPath) as! SwitchCell print(true, "Error getting table view cell for this index") return cell } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch Sections(rawValue: section)! { case .offeringDeal: return 1 case .distance : return Distances.count.rawValue case .sortBy: return YelpSortMode.count.rawValue case .category: return categories.count case .count: print("invalid number of sections") } return 0 } @IBAction func onFilterButtonPressed(sender: AnyObject) { //get the section that it's from let selectedIndexPath = tableView.indexPathForCell(sender.superview!!.superview as! UITableViewCell) print("filter Button Pressed") print(selectedIndexPath!.section) print(selectedIndexPath!.row) if switchStates[selectedIndexPath!] == nil{ for(var i = 0; i<tableView.numberOfRowsInSection((selectedIndexPath?.section)!); i++){ let tempIP = NSIndexPath(forRow: i, inSection: (selectedIndexPath?.section)!) switchStates[tempIP] = false } } //set that button to selected //go through all the other buttons in that section and mark them as not selected for (indexPath, _) in switchStates { if indexPath.section == selectedIndexPath?.section { if indexPath.row == selectedIndexPath?.row { print("index set to true") switchStates[indexPath] = true }else{ print("index set to false") switchStates[indexPath] = false } } } tableView.reloadData() } @IBAction func onSearch(sender: AnyObject) { var filters = Filter() var selectedCategories = [String]() filters.distance = Distances.Mile10.getDistanceInMeters() filters.sortBy = YelpSortMode.BestMatched for (indexPath, isSelected) in switchStates { //Get Categories if (indexPath.section == Sections.category.rawValue){ if isSelected { selectedCategories.append(categories[indexPath.row]["code"]!) print(categories[indexPath.row]["code"]) } } //get distance if (indexPath.section == Sections.distance.rawValue){ if isSelected { filters.distance = Distances(rawValue: indexPath.row)?.getDistanceInMeters() print(filters.distance) } } //get sort by if (indexPath.section == Sections.sortBy.rawValue){ if isSelected { filters.sortBy = YelpSortMode(rawValue: indexPath.row)! print(filters.sortBy?.getTitle()) } } } //get deals filters.deal = switchStates[NSIndexPath(forRow: 0, inSection: Sections.offeringDeal.rawValue)] ?? false print(filters.deal) filters.categories = selectedCategories delegate?.filtersViewController?(self, didUpdateFilters: filters) dismissViewControllerAnimated(true, completion:nil) } @IBAction func onCancel(sender: AnyObject) { dismissViewControllerAnimated(true, completion:nil) } func switchCell(switchCell: SwitchCell, didChangeValue value: Bool){ let indexPath = tableView.indexPathForCell(switchCell)! switchStates[indexPath] = value } //enum for section headers in filters view enum Sections : Int{ case offeringDeal=0, distance, sortBy, category, count static let headerTitles = [ offeringDeal: "", distance: "Distance", sortBy: "Sort By", category: "Category" ] func getTitle() -> String { if let title = Sections.headerTitles[self] { return title } else { return "Error: passed in a number that is not valid" } } } enum Distances : Int{ case Mile05=0, Mile1, Mile5, Mile10, Mile20, count static let distanceTitles = [ Mile05: "0.5 Miles", Mile1: "1 Mile", Mile5: "5 Miles", Mile10: "10 Miles", Mile20: "20 Miles" ] static let distanceInMeters = [ Mile05: 805, Mile1: 1609, Mile5: 8047, Mile10: 16093, Mile20: 32187 ] func getDistanceTitle() -> String { if let distanceTitle = Distances.distanceTitles[self] { return distanceTitle } else { return "Error: passed in a number that is not valid" } } func getDistanceInMeters() -> Int{ if let distanceInMeters = Distances.distanceInMeters[self] { return distanceInMeters } else { return 16093 } } } }
3514305b617f7846a91d7e62526097b9cb4899e7
[ "Swift" ]
3
Swift
funnycat/Yelp
e10fb5f953048f0f462151da4aa7095e313d32cc
6382e2273d213e5e4256878faab046d55b50cd5f
refs/heads/master
<repo_name>ramonfe/embedded_systems<file_sep>/stats.h /****************************************************************************** * Copyright (C) 2017 by <NAME> - University of Colorado * * Redistribution, modification or use of this software in source or binary * forms is permitted as long as the files maintain this copyright. Users are * permitted to modify this and use it to learn about the field of embedded * software. <NAME> and the University of Colorado are not liable for any * misuse of this material. * *****************************************************************************/ /** * @file <Add File Name> * @brief <Add Brief Description Here > * * <Add Extended Description Here> * * @author <Add FirsName LastName> * @date <Add date > * */ #ifndef __STATS_H__ #define __STATS_H__ /* Add Your Declarations and Function Comments here */ /** * @brief A function that prints the statistics of an array including minimum, * maximum, mean, and median. * * @return void */ void print_statistics(unsigned char * ptr, unsigned int count); /** * @brief Given an array of data and a length, prints the array to the screen * * @param A unsigned char pointer to an n-element data array * @param An unsigned integer as the size of the array * @return void */ void print_array(unsigned char * ptr, unsigned int count); /** * @brief Given an array of data and a length, returns the median value * * @param A unsigned char pointer to an n-element data array * @param An unsigned integer as the size of the array * @return a median from given array */ unsigned char find_median(unsigned char * ptr, unsigned int count); /** * @brief Given an array of data and a length, returns the mean * * @param A unsigned char pointer to an n-element data array * @param An unsigned integer as the size of the array * @return a mean from given array */ unsigned char find_mean(unsigned char * ptr, unsigned int count); /** * @brief Given an array of data and a length, returns the maximum * * @param A unsigned char pointer to an n-element data array * @param An unsigned integer as the size of the array * @return a maxim from given array */ unsigned char find_maximum(unsigned char * ptr, unsigned int count); /** * @brief Given an array of data and a length, returns the minimum * * @param A unsigned char pointer to an n-element data array * @param An unsigned integer as the size of the array * @return a minimum from given array */ unsigned char find_minimum(unsigned char * ptr, unsigned int count); /** * @brief Given an array of data and a length, sorts the array from largest to * smallest. (The zeroth Element should be the largest value, and the last * element (n-1) should be the smallest value. ) * * @param A unsigned char pointer to an n-element data array * @param An unsigned integer as the size of the array * @return void */ void sort_array(unsigned char * ptr, unsigned int count); #endif /* __STATS_H__ */ <file_sep>/stats.c /****************************************************************************** * Copyright (C) 2017 by <NAME> - University of Colorado * * Redistribution, modification or use of this software in source or binary * forms is permitted as long as the files maintain this copyright. Users are * permitted to modify this and use it to learn about the field of embedded * software. <NAME> and the University of Colorado are not liable for any * misuse of this material. * *****************************************************************************/ /** * @file <stats.c> * @brief < A file that covers the first ssignment for Embedded System course > * * <Add Extended Description Here> * * @author <<NAME>> * @date <Nov 14, 2019> * */ #include <stdio.h> #include "stats.h" /* Size of the Data Set */ #define SIZE (40) unsigned char find_mean(unsigned char * ptr, unsigned int count) { int i; int mean = 0; for (i = 0; i < count; i++) { mean += *ptr; ptr++; } return (mean / count); } unsigned char find_median(unsigned char * ptr, unsigned int count) { int i = 0; int median = 0; i = count / 2; if (count % 2 == 0) { median = (ptr[i] + ptr[i + 1]) / 2; } else { median = ptr[i]; } return median; } void sort_array(unsigned char * ptr, unsigned int count) { int i, j, max, temp; for (i = 0; i < count - 1; i++) { max = i; for (j = i + 1; j < count; j++) if (ptr[j] > ptr[max]) max = j; temp = ptr[i]; ptr[i] = ptr[max]; ptr[max] = temp; } } unsigned char find_maximum(unsigned char * ptr, unsigned int count) { int i, j, max, temp; max = 0; for (i = 0; i < count - 1; i++) { if (ptr[i + 1] > ptr[max]) max = i + 1; } return ptr[max]; } void print_array(unsigned char * ptr, unsigned int count) { int i=0; for (i = 0; i < count; i++) printf(", %d", ptr[i]); } unsigned char find_minimum(unsigned char * ptr, unsigned int count) { int i, j, min, temp; min = 0; for (i = 0; i < count - 1; i++) { if (ptr[i + 1] < ptr[min]) min = i + 1; } return ptr[min]; } void print_statistics(unsigned char * ptr, unsigned int count) { printf("\nGiven Array is: \n"); print_array(ptr, count); printf("\nSorted Array is: \n"); sort_array(ptr, count); print_array(ptr, count); printf("\nMin Array Value is: %d \n", find_minimum(ptr, count)); printf("\nMax Array Value is: %d \n", find_maximum(ptr, count)); printf("\nMean Array Value is: %d \n", find_mean(ptr, count)); printf("\nMedian Array Value is: %d \n", find_median(ptr, count)); } void main() { unsigned char test[SIZE] = { 34, 201, 190, 154, 8, 194, 2, 6, 114, 88, 45, 76, 123, 87, 25, 23, 200, 122, 150, 90, 92, 87, 177, 244, 201, 6, 12, 60, 8, 2, 5, 67, 7, 87, 250, 230, 99, 3, 100, 90}; unsigned int n = sizeof(test) / sizeof(test[0]); /* Other Variable Declarations Go Here */ /* Statistics and Printing Functions Go Here */ print_statistics(test, n); } <file_sep>/README.md /* Add Author and Project Details here */ #Author: <NAME> #Date: Nov 14, 2019 ### This is my first project asiggnment for Introduction to Embedded System
b6ef15fce0ff59e32287fd169a534b57e4c71c2f
[ "Markdown", "C" ]
3
C
ramonfe/embedded_systems
ebd3c35a417ae64d03f8e34597297a7d9459103a
cfd78ef9266414d07cbb17c8123f02e407359291
refs/heads/master
<repo_name>usaboo/TelosB-Sensor-Network<file_sep>/region 2 - tree1/2112/Sender.h #ifndef BLINKTORADIO_H #define BLINKTORADIO_H enum { AM_BLINKTORADIO = 6, AM_BLINKTORADIOMSG = 6, TIMER_PERIOD_MILLI = 5005, TIMER_PERIOD_MILLI1= 1333, TIMER_PERIOD_MILLI2= 2749, TIMER_PERIOD_MILLI3= 3313, TIMER_PERIOD_MILLI4= 4129, TIME_SYNC = 00, DATA_AGGR = 01 }; typedef nx_struct serial_pkt { nx_uint16_t nodeid; nx_uint16_t ackn; } serial_pkt; typedef nx_struct TimeSync { nx_uint32_t T2; nx_uint32_t T3; nx_float phase_delay; nx_float prop_delay; //NODE ID OF THAT WHICH HAS SENT MESSAGE nx_uint16_t nodeid_t; //VERY IMPORTANT nx_uint8_t stage; //IF IT IS 0 IT MEANS NOTE DOWN T2,T3 AND SEND DOWN //IF IT IS 1 IT MEANS YOU HAVE RECEIVED PROP AND PHASE DELAYS //IF IT IS 2 IT MEANS YOU HAVE RECEIVED T2,T3 AND MUST NOTE DOWN T4 AND CALCULATE PROP AND PHASE DELAYS } TimeSync; typedef nx_struct BlinkToRadioMsg { nx_uint16_t nodeid_3; nx_uint16_t counter_3; nx_float time_stamp_3; nx_uint16_t nodeid_2; nx_uint16_t counter_2; nx_float time_stamp_2; nx_uint16_t nodeid_1; nx_uint16_t counter_1; nx_float time_stamp_1; nx_uint16_t serial_id; } BlinkToRadioMsg; typedef nx_struct query { nx_uint16_t nodeid; nx_uint16_t flag; } query; typedef nx_struct response { nx_uint16_t nodeid; nx_uint16_t counter; nx_float time_stamp; nx_uint16_t flag; } response; #endif <file_sep>/README.md # TelosB-Sensor-Network Contains the codes and PDF for our TelosB sensor network <file_sep>/region 1 - tree3/1212/Makefile COMPONENT=SenderAppC PFLAGS += -I$(TOSDIR)/lib/printf include $(MAKERULES) BUILD_EXTRA_DEPS=BuildToRadioMsg.class BlinkToRadioMsg.class: BlinkToRadioMsg.java javac BlinkToRadioMsg.java BlinkToRadioMsg.java: mig java -target=null -java-classname=BlinkToRadioMsg Sender.h BlinkToRadioMsg -o $@ <file_sep>/serial forwarder - region 1/Makefile COMPONENT=SenderAppC include $(MAKERULES) PFLAGS += -I$(TOSDIR)/lib/printf BUILD_EXTRA_DEPS=BuildToRadioMsg.class BlinkToRadioMsg.class: BlinkToRadioMsg.java javac BlinkToRadioMsg.java BlinkToRadioMsg.java: mig java -target=null -java-classname=BlinkToRadioMsg Sender.h BlinkToRadioMsg -o $@ <file_sep>/region 1 - tree4/1223/Sender.h #ifndef BLINKTORADIO_H #define BLINKTORADIO_H enum { AM_BLINKTORADIO = 6, AM_BLINKTORADIOMSG = 6, TIMER_PERIOD_MILLI = 5005, TIMER_PERIOD_MILLI1= 1333, TIMER_PERIOD_MILLI2= 2749, TIMER_PERIOD_MILLI3= 3313, TIMER_PERIOD_MILLI4= 4129, }; typedef nx_struct TimeSync { nx_uint32_t T2; nx_uint32_t T3; nx_float phase_delay; nx_float prop_delay; nx_uint16_t nodeid_t; nx_uint8_t stage; } TimeSync; typedef nx_struct BlinkToRadioMsg { nx_uint16_t nodeid_3; nx_uint16_t counter_3; nx_float time_stamp_3; nx_uint16_t nodeid_2; nx_uint16_t counter_2; nx_float time_stamp_2; nx_uint16_t nodeid_1; nx_uint16_t counter_1; nx_float time_stamp_1; nx_uint16_t serial_id; } BlinkToRadioMsg; typedef nx_struct query { nx_uint16_t nodeid; nx_uint16_t flag; } query; typedef nx_struct response { nx_uint16_t nodeid; nx_uint16_t counter; nx_float time_stamp; nx_uint16_t flag; } response; #endif
6c68dab98b3ce53bc1d4ea040f1af4bdf5f137e3
[ "Markdown", "C", "Makefile" ]
5
C
usaboo/TelosB-Sensor-Network
5bbbf5eb4fdde4cd69b2cb65cee984a841373ceb
7ea943238f1d73b51b85a5a4d4a5c7d678868f5a
refs/heads/main
<file_sep>/* bspI2c.h Board support for controlling I2C interfaces on NUCLEO-F401RE MCU Developed for University of Washington embedded systems programming certificate 2018/12 <NAME> wrote/arranged it */ #ifndef ___BSPI2C_H #define ___BSPI2C_H #include "stm32l4xx_ll_i2c.h" #define PJDF_I2C1 I2C1 // Address of I2C1 memory mapped register block #define MAX_NBYTE_SIZE 0xFF //maximum byte that I2C Interface can take void BspI2C1_init(void); void BspI2c_WaitWithTimeoutReset(uint32_t (*IsActive)(I2C_TypeDef *I2Cx), uint32_t value); uint8_t I2C_read_ack(I2C_TypeDef* I2Cx); uint8_t I2C_read_nack(I2C_TypeDef* I2Cx); void I2C_start(I2C_TypeDef* I2Cx, uint8_t address, uint32_t direction, uint32_t request, uint8_t nBytes); void I2C_stop(I2C_TypeDef* I2Cx); void I2C_write(I2C_TypeDef* I2Cx, uint8_t data); #endif <file_sep>/* bspSpi.c Board support for controlling SPI interfaces on NUCLEO-F401RE MCU Developed for University of Washington embedded systems programming certificate 2016/2 <NAME> wrote/arranged it */ #include "bsp.h" // BspSPI1Init // Initializes the SPI1 memory mapped register block and enables it for use // as a master SPI device. void BspSPI1Init() { LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOA); LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_SPI1); /* Configure SPI1 communication */ LL_SPI_SetBaudRatePrescaler(SPI1, LL_SPI_BAUDRATEPRESCALER_DIV256); LL_SPI_SetTransferDirection(SPI1,LL_SPI_FULL_DUPLEX); LL_SPI_SetClockPhase(SPI1, LL_SPI_PHASE_1EDGE); LL_SPI_SetClockPolarity(SPI1, LL_SPI_POLARITY_LOW); LL_SPI_SetTransferBitOrder(SPI1, LL_SPI_MSB_FIRST); LL_SPI_SetDataWidth(SPI1, LL_SPI_DATAWIDTH_8BIT); LL_SPI_SetNSSMode(SPI1, LL_SPI_NSS_SOFT); LL_SPI_SetRxFIFOThreshold(SPI1, LL_SPI_RX_FIFO_TH_QUARTER); LL_SPI_SetMode(SPI1, LL_SPI_MODE_MASTER); LL_GPIO_InitTypeDef GPIO_InitStruct; /*-------- Configure SCK, MISO, MOSI --------*/ GPIO_InitStruct.Pin = LL_GPIO_PIN_5 | LL_GPIO_PIN_6 | LL_GPIO_PIN_7; GPIO_InitStruct.Mode = LL_GPIO_MODE_ALTERNATE; GPIO_InitStruct.Speed = LL_GPIO_SPEED_FREQ_HIGH; GPIO_InitStruct.OutputType = LL_GPIO_OUTPUT_PUSHPULL; GPIO_InitStruct.Pull = LL_GPIO_PULL_NO; LL_GPIO_Init(GPIOA, &GPIO_InitStruct); /*--------- Configure alternate GPIO functions to SPI1 ------*/ LL_GPIO_SetAFPin_0_7(GPIOA, LL_GPIO_PIN_5, LL_GPIO_AF_5); LL_GPIO_SetAFPin_0_7(GPIOA, LL_GPIO_PIN_6, LL_GPIO_AF_5); LL_GPIO_SetAFPin_0_7(GPIOA, LL_GPIO_PIN_7, LL_GPIO_AF_5); LL_SPI_Enable(SPI1); } // SPI_SendBuffer // Sends the given data to the given SPI device void SPI_SendBuffer(SPI_TypeDef *spi, uint8_t *buffer, uint16_t bufLength) { for (int i = 0; i < bufLength; i++) { while(!LL_SPI_IsActiveFlag_TXE(spi)); LL_SPI_TransmitData8(spi, buffer[i]); while(!LL_SPI_IsActiveFlag_RXNE(spi)); LL_SPI_ReceiveData8(spi); } } // SPI_GetBuffer // Sends the given data to the given SPI device. // buffer: on entry contains the command to retrieve data from the spi device. // On exit the buffer is OVERWRITTEN with the data output by the device // in response to the command. void SPI_GetBuffer(SPI_TypeDef *spi, uint8_t *buffer, uint16_t bufLength) { int iread = 0; for (int i = 0; i < bufLength; i++) { while(!LL_SPI_IsActiveFlag_TXE(spi)); LL_SPI_TransmitData8(spi, buffer[i]); while(!LL_SPI_IsActiveFlag_RXNE(spi)); buffer[iread++] =LL_SPI_ReceiveData8(spi); } } // Set a value to control the data rate of the given SPI interface void SPI_SetDataRate(SPI_TypeDef *spi, uint16_t value) { LL_SPI_SetBaudRatePrescaler(spi, value); } <file_sep>/* mp3Util.h Some utility functions for controlling the MP3 decoder. Developed for University of Washington embedded systems programming certificate 2016/2 <NAME> wrote/arranged it */ #ifndef __MP3UTIL_H #define __MP3UTIL_H #include "SD.h" #include "globals.h" #include "events.h" #include "bsp.h" #include "print.h" typedef enum { VOLUP = 0, VOLDOWN } VolumeCounter; PjdfErrCode Mp3GetRegister(HANDLE hMp3, INT8U *cmdInDataOut, INT32U bufLen); void Mp3StreamInit(HANDLE hMp3); //void Mp3Test(HANDLE hMp3); //void Mp3Stream(HANDLE hMp3, INT8U *pBuf, INT32U bufLen); //void Mp3StreamSDFile(HANDLE hMp3, char *pFilename); void Mp3VolumeControl(HANDLE hMp3, VolumeCounter state); void Mp3FetchFileNames(); //void Mp3FetchFileNames(char **list, int maxRow, int col, int *size); void Mp3StreamCycle(HANDLE hMp3); #endif<file_sep># mp3-player A Basic MP3 Player for B-L475E-IOT01A platform using the Adafruit Music Maker MP3 Shield, and the Adafruit 2.8” TFT LCD shield. Below are the features of the MP3 Player - to be implemented in an incremental way: •Play and Pause •Play Progress •Forward and Rewind •Display song progress on the LCD display •A feature to change song •Read song files from SD card <file_sep>/* bspUart.h Board support for controlling UART interfaces Developed for University of Washington embedded systems programming certificate 2016/2 <NAME> wrote/arranged it for NUCLEO-F401RE MCU 2020/8 <NAME> wrote/arranged it for STM32L475 */ #ifndef __BSPUART_H #define __BSPUART_H #define USARTx_INSTANCE USART1 #define USARTx_CLKSOURCE LL_RCC_USART2_CLKSOURCE #define USARTx_CLK_ENABLE() LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_USART1) #define USARTx_CLK_SOURCE() LL_RCC_SetUSARTClockSource(LL_RCC_USART1_CLKSOURCE_PCLK2) #define USARTx_GPIO_CLK_ENABLE() LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOB) /* Enable the peripheral clock of GPIOB */ #define USARTx_TX_PIN LL_GPIO_PIN_6 #define USARTx_TX_GPIO_PORT GPIOB #define USARTx_SET_TX_GPIO_AF() LL_GPIO_SetAFPin_0_7(GPIOB, LL_GPIO_PIN_6, LL_GPIO_AF_7) #define USARTx_RX_PIN LL_GPIO_PIN_7 #define USARTx_RX_GPIO_PORT GPIOB #define USARTx_SET_RX_GPIO_AF() LL_GPIO_SetAFPin_0_7(GPIOA, LL_GPIO_PIN_7, LL_GPIO_AF_7) // Application interface to hardware void UartInit(uint32_t baud); void PrintByte(char c); char ReadByte(); #endif /* __BSPUART_H */<file_sep>/* bspLcd.h Board support for controlling the ILI9341 LCD on the Adafruit '2.8" TFT LCD w/Cap Touch' via NUCLEO-F401RE MCU Developed for University of Washington embedded systems programming certificate 2016/2 <NAME> wrote/arranged it */ #include "stm32l4xx.h" #ifndef __BSPLCD_H #define __BSPLCD_H #define LCD_ILI9341_CS_GPIO GPIOA #define LCD_ILI9341_CS_GPIO_Pin LL_GPIO_PIN_2 #define LCD_ILI9341_DC_GPIO GPIOA #define LCD_ILI9341_DC_GPIO_Pin LL_GPIO_PIN_15 #define LCD_ILI9341_CS_ASSERT() LL_GPIO_ResetOutputPin(LCD_ILI9341_CS_GPIO, LCD_ILI9341_CS_GPIO_Pin); #define LCD_ILI9341_CS_DEASSERT() LL_GPIO_SetOutputPin(LCD_ILI9341_CS_GPIO, LCD_ILI9341_CS_GPIO_Pin); #define LCD_ILI9341_DC_LOW() LL_GPIO_ResetOutputPin(LCD_ILI9341_DC_GPIO, LCD_ILI9341_DC_GPIO_Pin); #define LCD_ILI9341_DC_HIGH() LL_GPIO_SetOutputPin(LCD_ILI9341_DC_GPIO, LCD_ILI9341_DC_GPIO_Pin); #define LCD_SPI_DEVICE_ID PJDF_DEVICE_ID_SPI1 #define LCD_SPI_DATARATE LL_SPI_BAUDRATEPRESCALER_DIV2 // Tune to find optimal value LCD controller will work with. OK with 16MHz and 80MHzHCLK void BspLcdInitILI9341(); #endif<file_sep>/* uiSettings.h Header file for controlling objects on UI of LCD Display - carries display object coordinates Developed for University of Washington embedded systems programming certificate 2021/3 <NAME> wrote/arranged it */ #ifndef __MP3UISETTINGS_H #define __MP3UISETTINGS_H #include <Adafruit_GFX.h> #include <Adafruit_ILI9341.h> /* Definition: MP3 Main Player Window and its labels UI Interface Note: Contains all coordinate related Information/definitions Window space is divided into two halves - first half (240*160) music file related display & progress bar And second half is MP3 controller, that contains buttons (0, 0) - Top Left Coordinate ------------------------------------------------------------- | <.Song Title....................(Wrap Around)> | | | | | | | | | | | | | | | | | | | | | | | Music BitMap File | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ---------------------------------------------- | |-----------------------------------------------------------| | Progress Bar | |-----------------------------------------------------------| | ---------------- ---------------- ---------------- | | | | | | | | | | | Play | | Pause | | Stop | | | | | | | | | | | ---------------- ---------------- ---------------- | | --------------- -------------- | | | | | | | | | Prev | | Next | | | | | | | | | --------------- -------------- | | ------------- | | ---------------- | | | | | | | Vol+ | | | | Menu | <Play Status> | | | | | | ------------- | | ---------------- ------------- | | | | | | | Vol- | | | | | | | ------------- | -------------------------------------------------------------- Alternatively, ------------------------------------------------------------- | <.Song Title1....................(Wrap Around)> | | <.Song Title2....................(Wrap Around)> | | <.Song Title3....................(Wrap Around)> | | <.Song Title4....................(Wrap Around)> | | <.Song Title5....................(Wrap Around)> | | <.Song Title6....................(Wrap Around)> | | <.Song Title7....................(Wrap Around)> | | <.Song Title8....................(Wrap Around)> | | <.Song Title9....................(Wrap Around)> | | <.Song Title10...................(Wrap Around)> | |-----------------------------------------------------------| | Progress Bar | |-----------------------------------------------------------| | ---------------- ---------------- ---------------- | | | | | | | | | | | Play | | Pause | | Stop | | | | | | | | | | | ---------------- ---------------- ---------------- | | --------------- -------------- | | | | | | | | | Rewind | | FF | | | | | | | | | --------------- -------------- | | ------------- ------------- | | | | | | | | | UP | | Vol+ | | | | | <Play Status> | | | | ------------- ------------- | | ------------- ------------- | | | | | | | | | DOWN | | Vol- | | | | | | | | | ------------- ------------- | -------------------------------------------------------------- */ // Standard button width and height #define STD_BUTTON_WIDTH 68U #define STD_BUTTON_HEIGHT 30U // Small button width and height #define SM_BUTTON_WIDTH 60U #define SM_BUTTON_HEIGHT 30U // Menu button width and height #define MENU_BUTTON_WIDTH 240U #define MENU_BUTTON_HEIGHT 20U // Status Bar button width and height #define BAR_BUTTON_WIDTH 30U//18U #define BAR_BUTTON_HEIGHT 18U #define BAR_BUTTON_XCOORD 15U//14U // Space between status bar #define BAR_BUTTON_SPACE 24U // x-center of rectangle + 6 (distance between bars) // Volume Box and Stack button width and height #define BOX_BUTTON_WIDTH 18U #define BOX_BUTTON_HEIGHT 105U #define STK_BUTTON_WIDTH 16U//18U #define STK_BUTTON_HEIGHT 10U #define STK_BUTTON_XCOORD 225U//14U #define STK_BUTTON_SPACE 2U // Player Window Buttons (Designed on lower half) and other Objects Coordinate Mapping #define MENU_XCOORD_BEGIN 120U #define MENU_YCOORD_BEGIN 10U #define PLAY_XCOORD 40U #define PLAY_YCOORD 185U #define PAUSE_XCOORD 120U #define PAUSE_YCOORD 185U #define STOP_XCOORD 200U #define STOP_YCOORD 185U #define REWIND_XCOORD 65U #define REWIND_YCOORD 222U #define FF_XCOORD 145U #define FF_YCOORD 222U //#define MENU_XCOORD 85U //#define MENU_YCOORD 230U #define UP_XCOORD 40U #define UP_YCOORD 259U #define DOWN_XCOORD 40U #define DOWN_YCOORD 299U #define VOLPLUS_XCOORD 180U #define VOLPLUS_YCOORD 259U #define VOLMINUS_XCOORD 180U #define VOLMINUS_YCOORD 299U #define STATUS_XCOORD 80U #define STATUS_YCOORD 272U #define VOLBOX_XCOORD 225U #define VOLBOX_YCOORD 260U #define PLAYERBUTTONNUM 9U #define MAXMENULIST 7U #define STATUSBARSNUM 10U #define VOLUMEBARSNUM 14U #define DEFAULTVOLINDX 5U // MP3 Player Button Indexes typedef enum { PLAY = 0, PAUSE, STOP, REWIND, FF, UP, DOWN, VOLPLUS, VOLMINUS } PlayerButtonIndex; // Declare MP3 Player Winodows here // The Player Window - where functions of controlling MP3 events are provided typedef struct _PlayerWindow { // -----------Start of Upper Half of the display--------------------// // Music Title & Music Bitmap File Adafruit_GFX_Button menu_list[MAXMENULIST]; // Music Progress bar Adafruit_GFX_Button status_box; Adafruit_GFX_Button status_bar[STATUSBARSNUM]; // -----------End of Upper Half of the display--------------------// // -----------Start of Lower Half of the display--------------------// // A list of MP3 Player buttons (Play, Pause, Stop, Prev, Next, Menu, Vol+, Vol-) Adafruit_GFX_Button button_list[PLAYERBUTTONNUM]; // Current Play Status - Text Content char *player_status; // Volume Bar Adafruit_GFX_Button vol_box; Adafruit_GFX_Button vol_bar[VOLUMEBARSNUM]; // -----------End of Lower Half of the display--------------------// } PlayerWindow; #endif<file_sep>/* bspLed.c Board support for controlling LEDs Developed for University of Washington embedded systems programming certificate 2020/8 <NAME> wrote/arranged it for STM332L475 */ #include "bsp.h" void LedInit() { /* Enable the LED2 Clock */ LED2_GPIO_CLK_ENABLE(); /* Configure IO in output push-pull mode to drive external LED2 */ LL_GPIO_SetPinMode(LED2_GPIO_PORT, LED2_PIN, LL_GPIO_MODE_OUTPUT); } void SetLED(BOOLEAN On) { if (On) { LL_GPIO_SetOutputPin(GPIO_PORT_LD2, GPIO_PIN_LD2); } else { /* The high 16 bits of BSRR reset the pin */ LL_GPIO_ResetOutputPin(GPIO_PORT_LD2, GPIO_PIN_LD2); } } <file_sep>/* hw_init.c Initializes hardware for the app 2021/1 <NAME> wrote/arranged it */ #include "bsp.h" void SystemClock_Config16(void); void SystemClock_Config80(void); // Boot up processor void Hw_init(void) { SystemClock_Config16(); UartInit(115200); NVIC_SetPriority(PendSV_IRQn, 0xFF); // Lowest possible priority } void SetSysTick(uint32_t ticksPerSec) { OS_CPU_SysTickInit(ticksPerSec); LL_RCC_ClocksTypeDef rcc_ClocksStatus; LL_RCC_GetSystemClocksFreq(&rcc_ClocksStatus); PrintString("HCLK frequency = "); Print_uint32(rcc_ClocksStatus.HCLK_Frequency / 1000000); PrintString(" MHz\n"); PrintString("Configured ticksPerSec = "); Print_uint32(ticksPerSec); PrintString("\n"); } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config16(void) { LL_FLASH_SetLatency(LL_FLASH_LATENCY_0); while(LL_FLASH_GetLatency()!= LL_FLASH_LATENCY_0) { } LL_PWR_SetRegulVoltageScaling(LL_PWR_REGU_VOLTAGE_SCALE1); LL_RCC_HSI_Enable(); /* Wait till HSI is ready */ while(LL_RCC_HSI_IsReady() != 1) { } LL_RCC_HSI_SetCalibTrimming(16); LL_RCC_MSI_Enable(); /* Wait till MSI is ready */ while(LL_RCC_MSI_IsReady() != 1) { } LL_RCC_MSI_EnablePLLMode(); LL_RCC_MSI_EnableRangeSelection(); LL_RCC_MSI_SetRange(LL_RCC_MSIRANGE_6); LL_RCC_MSI_SetCalibTrimming(0); LL_PWR_EnableBkUpAccess(); // LL_RCC_LSE_SetDriveCapability(LL_RCC_LSEDRIVE_LOW); // LL_RCC_LSE_Enable(); // // /* Wait till LSE is ready */ // while(LL_RCC_LSE_IsReady() != 1) // { // // } LL_RCC_PLLSAI1_ConfigDomain_48M(LL_RCC_PLLSOURCE_MSI, LL_RCC_PLLM_DIV_1, 24, LL_RCC_PLLSAI1Q_DIV_2); LL_RCC_PLLSAI1_EnableDomain_48M(); LL_RCC_PLLSAI1_Enable(); /* Wait till PLLSAI1 is ready */ while(LL_RCC_PLLSAI1_IsReady() != 1) { } LL_RCC_SetSysClkSource(LL_RCC_SYS_CLKSOURCE_HSI); /* Wait till System clock is ready */ while(LL_RCC_GetSysClkSource() != LL_RCC_SYS_CLKSOURCE_STATUS_HSI) { } LL_RCC_SetAHBPrescaler(LL_RCC_SYSCLK_DIV_1); LL_RCC_SetAPB1Prescaler(LL_RCC_APB1_DIV_1); LL_RCC_SetAPB2Prescaler(LL_RCC_APB2_DIV_1); LL_SetSystemCoreClock(16000000); // /* Update the time base */ // if (HAL_InitTick (TICK_INT_PRIORITY) != HAL_OK) // { // Error_Handler(); // } // LL_RCC_SetUSARTClockSource(LL_RCC_USART1_CLKSOURCE_PCLK2); // LL_RCC_SetUSARTClockSource(LL_RCC_USART3_CLKSOURCE_PCLK1); // LL_RCC_SetI2CClockSource(LL_RCC_I2C1_CLKSOURCE_PCLK1); // LL_RCC_SetI2CClockSource(LL_RCC_I2C2_CLKSOURCE_PCLK1); // LL_RCC_SetUSBClockSource(LL_RCC_USB_CLKSOURCE_PLLSAI1); // LL_RCC_SetDFSDMClockSource(LL_RCC_DFSDM_CLKSOURCE_PCLK); } /** * @brief System Clock Configuration * The system Clock is configured as follows : * System Clock source = PLL (MSI) * SYSCLK(Hz) = 80000000 * HCLK(Hz) = 80000000 * AHB Prescaler = 1 * APB1 Prescaler = 1 * APB2 Prescaler = 1 * MSI Frequency(Hz) = 4000000 * PLL_M = 1 * PLL_N = 40 * PLL_R = 2 * Flash Latency(WS) = 4 * @param None * @retval None */ void SystemClock_Config80(void) { /* MSI configuration and activation */ LL_FLASH_SetLatency(LL_FLASH_LATENCY_4); LL_RCC_MSI_Enable(); while(LL_RCC_MSI_IsReady() != 1) { }; /* Main PLL configuration and activation */ LL_RCC_PLL_ConfigDomain_SYS(LL_RCC_PLLSOURCE_MSI, LL_RCC_PLLM_DIV_1, 40, LL_RCC_PLLR_DIV_2); LL_RCC_PLL_Enable(); LL_RCC_PLL_EnableDomain_SYS(); while(LL_RCC_PLL_IsReady() != 1) { }; /* Sysclk activation on the main PLL */ LL_RCC_SetAHBPrescaler(LL_RCC_SYSCLK_DIV_1); LL_RCC_SetSysClkSource(LL_RCC_SYS_CLKSOURCE_PLL); while(LL_RCC_GetSysClkSource() != LL_RCC_SYS_CLKSOURCE_STATUS_PLL) { }; /* Set APB1 & APB2 prescaler*/ LL_RCC_SetAPB1Prescaler(LL_RCC_APB1_DIV_1); LL_RCC_SetAPB2Prescaler(LL_RCC_APB2_DIV_1); /* Set systick to 1ms in using frequency set to 80MHz */ /* This frequency can be calculated through LL RCC macro */ /* ex: __LL_RCC_CALC_PLLCLK_FREQ(__LL_RCC_CALC_MSI_FREQ(LL_RCC_MSIRANGESEL_RUN, LL_RCC_MSIRANGE_6), LL_RCC_PLLM_DIV_1, 40, LL_RCC_PLLR_DIV_2)*/ //LL_Init1msTick(80000000); /* Update CMSIS variable (which can be updated also through SystemCoreClockUpdate function) */ LL_SetSystemCoreClock(80000000); } <file_sep>/* mp3UserInterface.c MP3 Player User Interfacing implementation. This is the implementation of the mp3UserInterface.h driver interface exposed to applications. Developed for University of Washington embedded systems programming certificate 2021/3 <NAME> wrote it */ #include "mp3UserInterface.h" #define DEAFULT_VOL_POS 7U // Button Intialization list static ButtonParameter playerParamList[PLAYERBUTTONNUM] = { {"Play", PLAY_XCOORD, PLAY_YCOORD, STD_BUTTON_WIDTH, STD_BUTTON_HEIGHT }, {"Pause", PAUSE_XCOORD, PAUSE_YCOORD, STD_BUTTON_WIDTH, STD_BUTTON_HEIGHT }, {"Stop", STOP_XCOORD, STOP_YCOORD, STD_BUTTON_WIDTH, STD_BUTTON_HEIGHT }, {"Rewind",REWIND_XCOORD, REWIND_YCOORD, STD_BUTTON_WIDTH, STD_BUTTON_HEIGHT }, {"FF", FF_XCOORD, FF_YCOORD, STD_BUTTON_WIDTH, STD_BUTTON_HEIGHT }, {"Up", UP_XCOORD, UP_YCOORD, SM_BUTTON_WIDTH, SM_BUTTON_HEIGHT}, {"Down", DOWN_XCOORD, DOWN_YCOORD, SM_BUTTON_WIDTH, SM_BUTTON_HEIGHT}, {"Vol+", VOLPLUS_XCOORD, VOLPLUS_YCOORD, SM_BUTTON_WIDTH, SM_BUTTON_HEIGHT }, {"Vol-", VOLMINUS_XCOORD,VOLMINUS_YCOORD, SM_BUTTON_WIDTH, SM_BUTTON_HEIGHT } }; static char* player_status[] = {"Select&Play", "Playing....", "Paused.....", "Stopped...."}; // Active Buttons Count static INT8U activeMenuBtnCnt = 0; static INT8U currMenuSelectCounter = 0; // Adafruit LCD Controller Instance Adafruit_ILI9341 lcdCtrl = Adafruit_ILI9341(); // Status Bar Count static INT8S statusBarBtnCnt = -1; static INT8S volumeBarBtnCnt = DEAFULT_VOL_POS; // Private function definitions static void buttonPressResponse(Adafruit_GFX_Button *button); static void buttonReleaseResponse(Adafruit_GFX_Button *button); static void setMenuToSelectState(Adafruit_GFX_Button *menu); static void updateStatusBar(Adafruit_GFX_Button *status, BOOLEAN state); static void updateVolumeBar(Adafruit_GFX_Button *vol, BOOLEAN state); static void setMenuToInactiveState(Adafruit_GFX_Button *menu); static INT8U getActiveButtonCount (boolean upDownFlag); static void drawPlayStatus(char *status); static void PrintCharToLcd(char c); void InitMenuLabels(PlayerWindow *pWindow, boolean upDownFlag); /******************************************************************************* * Function: SetUpLCDInterface * * Description: Set Up LCD Controller and related interface. * * Arguments: * * Return Value: None * ******************************************************************************/ void SetUpLCDInterface (void) { PjdfErrCode pjdfErr; INT32U length; // Open handle to the LCD driver HANDLE hLcd = Open(PJDF_DEVICE_ID_LCD_ILI9341, 0); //hang here for debugging purpose - to be replaced with Error log if project scope is expanded if (!PJDF_IS_VALID_HANDLE(hLcd)) while(1); // Open handle to the SPI driver HANDLE hSPI = Open(LCD_SPI_DEVICE_ID, 0); if (!PJDF_IS_VALID_HANDLE(hSPI)) while(1); length = sizeof(HANDLE); pjdfErr = Ioctl(hLcd, PJDF_CTRL_LCD_SET_SPI_HANDLE, &hSPI, &length); if(PJDF_IS_ERROR(pjdfErr)) while(1); // Now Initialize the LCD Controller lcdCtrl.setPjdfHandle(hLcd); lcdCtrl.begin(); } /******************************************************************************* * Function: InitPlayerWindow * * Description: Intialize PlayerWindow Datastructure * To be called at the beginning of display task * * Arguments: None * * Return Value: None * ******************************************************************************/ void InitPlayerWindow(PlayerWindow *pWindow) { OS_CPU_SR cpu_sr; OS_ENTER_CRITICAL(); // allow slow lower pri drawing operation to finish without preemption // Clear Screen - And set up a background color for the screen lcdCtrl.fillScreen(ILI9341_WHITE); // Init List of menu for (int i = 0; i < MAXMENULIST; i++) { pWindow->menu_list[i] = Adafruit_GFX_Button(); pWindow->menu_list[i].initButton( &lcdCtrl, MENU_XCOORD_BEGIN, MENU_YCOORD_BEGIN + (i*MENU_BUTTON_HEIGHT), MENU_BUTTON_WIDTH, MENU_BUTTON_HEIGHT, ILI9341_WHITE, // outline ILI9341_BLUE, // fill ILI9341_WHITE, // text color "", 1); } // If there are active menu buttons, first item is by default selected activeMenuBtnCnt = getActiveButtonCount(true); InitMenuLabels(pWindow, true); if(activeMenuBtnCnt > 0) { setMenuToSelectState(&pWindow->menu_list[0]); pWindow->menu_list[0].drawButton(false, true); } // Initialize Status Box and Status Bar pWindow->status_box = Adafruit_GFX_Button(); pWindow->status_box.initButton( &lcdCtrl, MENU_XCOORD_BEGIN, MENU_YCOORD_BEGIN + (MAXMENULIST*MENU_BUTTON_HEIGHT)+3, MENU_BUTTON_WIDTH, MENU_BUTTON_HEIGHT, ILI9341_BLACK, ILI9341_WHITE, ILI9341_WHITE, "", 1); pWindow->status_box.drawButton(false, false); for (int i = 0; i < STATUSBARSNUM; i++) { pWindow->status_bar[i] = Adafruit_GFX_Button(); pWindow->status_bar[i].initButton( &lcdCtrl, BAR_BUTTON_XCOORD + (i * BAR_BUTTON_SPACE), MENU_YCOORD_BEGIN + (MAXMENULIST*MENU_BUTTON_HEIGHT)+3, BAR_BUTTON_WIDTH, BAR_BUTTON_HEIGHT, ILI9341_BLUE, ILI9341_WHITE, ILI9341_WHITE, "", 1); //pWindow->status_bar[i].drawButton(false, false); } // Initialize Status Box and Status Bar pWindow->vol_box = Adafruit_GFX_Button(); pWindow->vol_box.initButton( &lcdCtrl, VOLBOX_XCOORD, VOLBOX_YCOORD, BOX_BUTTON_WIDTH, BOX_BUTTON_HEIGHT, ILI9341_BLACK, ILI9341_WHITE, ILI9341_WHITE, "", 1); pWindow->vol_box.drawButton(false, false); for (int i = 0; i < VOLUMEBARSNUM; i++) { pWindow->vol_bar[i] = Adafruit_GFX_Button(); pWindow->vol_bar[i].initButton( &lcdCtrl, STK_BUTTON_XCOORD, 306 - (i * 7), STK_BUTTON_WIDTH, STK_BUTTON_HEIGHT, ILI9341_WHITE, ILI9341_BLUE, ILI9341_WHITE, "", 1); } // display default volume psoition for (int i = 0; i <= volumeBarBtnCnt; i++) { pWindow->vol_bar[i].drawButton(false, false); } // Initialize a list of player buttons for (int i = 0; i < PLAYERBUTTONNUM; i++) { pWindow->button_list[i] = Adafruit_GFX_Button(); pWindow->button_list[i].initButton( &lcdCtrl, playerParamList[i].x_coordinate, playerParamList[i].y_coordinate, playerParamList[i].width, playerParamList[i].height, ILI9341_BLACK, // outline ILI9341_WHITE, // fill ILI9341_BLACK, // text color playerParamList[i].label, 1); pWindow->button_list[i].drawButton(false, false); } drawPlayStatus(player_status[SELECT]); OS_EXIT_CRITICAL(); } /******************************************************************************* * Function: drawPlayerWindow * * Description: Display the MP3 Player Window * * Arguments: None * * Return Value: None * ******************************************************************************/ void DrawPlayerWindow(PlayerWindow *pWindow) { // Display a list of songs fetched for (int i = 0; i < MAXMENULIST; i++) { pWindow->menu_list[i].drawButton(false, true); } // Display buttons for (int i = 0; i < PLAYERBUTTONNUM; i++) { pWindow->button_list[i].drawButton(false, false); } } /******************************************************************************* * Function: InitMenuLabel * * Description: Init menu buttons * * Arguments: None * * Return Value: None * ******************************************************************************/ void InitMenuLabels(PlayerWindow *pWindow, boolean upDownFlag) { // Fetch a list of songs from SD card and initialize in the list for (int i = 0; i < activeMenuBtnCnt; i++) { if(upDownFlag) { pWindow->menu_list[i].relabelButton(listOfSongs[currSongFilePntr+i]); pWindow->menu_list[i].drawButton(false, true); } else { // Should scroll over - feed lower menu to upwards pWindow->menu_list[(activeMenuBtnCnt-1) - i].relabelButton(listOfSongs[currSongFilePntr-i]); pWindow->menu_list[(activeMenuBtnCnt-1) - i].drawButton(false, true); } } //count is not equal to menu count, fill remaining with NULL labelling if(activeMenuBtnCnt != MAXMENULIST) { for(int i = activeMenuBtnCnt; i < MAXMENULIST; ++i) { pWindow->menu_list[i].relabelButton(""); pWindow->menu_list[i].drawButton(false, true); } } } /******************************************************************************* * Function: getActiveButtonCount * * Description: Determine active list of menu buttons to be created * * Arguments: size * index pointer * updown event: true - Down event, false - Up event * * Return Value: None * ******************************************************************************/ static INT8U getActiveButtonCount (boolean upDownFlag) { int count = 0; if(sizeOfList == 0) return count; if(upDownFlag) // Determine the number of labels to be displayed count = (((sizeOfList-1) - currSongFilePntr) >= MAXMENULIST) ? MAXMENULIST : ((sizeOfList-1) - currSongFilePntr); else // Upper will always be filled with 7 values, wont allow creation of // buttons if current point is at 0 count = (currSongFilePntr > 0) ? MAXMENULIST : 0; return count; } /******************************************************************************* * Function: buttonPressResponse * * Description: A unique display for button on a press event * * Arguments: Adafruit_GFX_Button - button background color value to be updated * * Return Value: None * ******************************************************************************/ static void buttonPressResponse(Adafruit_GFX_Button *button) { button->refillButton(ILI9341_DARKGREY); } /******************************************************************************* * Function: buttonReleaseResponse * * Description: A unique display for button on a release event * * Arguments: Adafruit_GFX_Button - button background color value to be updated * * Return Value: None * ******************************************************************************/ static void buttonReleaseResponse(Adafruit_GFX_Button *button) { button->refillButton(ILI9341_WHITE); } /******************************************************************************* * Function: setMenuToSelectState * * Description: A unique display for menu on a select event * * Arguments: Adafruit_GFX_Button - button background color value to be updated * * Return Value: None * ******************************************************************************/ static void setMenuToSelectState(Adafruit_GFX_Button *menu) { menu->refillButton(ILI9341_BLACK); } /******************************************************************************* * Function: updateStatusBar * * Description: A unique display for status button on a active/inactive event * * Arguments: Adafruit_GFX_Button - button background color value to be updated * * Return Value: None * ******************************************************************************/ static void updateStatusBar(Adafruit_GFX_Button *status, BOOLEAN state = OS_FALSE) { if(state) { status->refillButton(ILI9341_BLUE); status->reoutlineButton(ILI9341_BLUE); } else { status->refillButton(ILI9341_WHITE); status->reoutlineButton(ILI9341_WHITE); } } /******************************************************************************* * Function: updateVolumeBar * * Description: A unique display for volume bar on a active/inactive event * * Arguments: Adafruit_GFX_Button - button background color value to be updated * * Return Value: None * ******************************************************************************/ static void updateVolumeBar(Adafruit_GFX_Button *vol, BOOLEAN state = OS_FALSE) { if(state) { vol->refillButton(ILI9341_BLUE); } else { vol->refillButton(ILI9341_WHITE); } } /******************************************************************************* * Function: setMenuToSelectActive * * Description: A unique display for menu on a active event * * Arguments: Adafruit_GFX_Button - button background color value to be updated * * Return Value: None * ******************************************************************************/ static void setMenuToActiveState(Adafruit_GFX_Button *menu) { menu->refillButton(ILI9341_BLUE); } /******************************************************************************* * Function: setMenuToSelectActive * * Description: A unique display for menu on a active event * * Arguments: Adafruit_GFX_Button - button background color value to be updated * * Return Value: None * ******************************************************************************/ static void setMenuToInactiveState(Adafruit_GFX_Button *menu) { menu->refillButton(ILI9341_WHITE); } /******************************************************************************* * Function: drawPlayStatus * * Description: Display Current Play Status * * Arguments: char[] - status value to be displayed * * Return Value: None * ******************************************************************************/ static void drawPlayStatus(char *status) { char buf[BUFFERSIZE]; lcdCtrl.setCursor(STATUS_XCOORD, STATUS_YCOORD); lcdCtrl.setTextColor(ILI9341_BLACK, ILI9341_WHITE); lcdCtrl.setTextSize(1); PrintToLcdWithBuf(buf, BUFFERSIZE, status); } // Renders a character at the current cursor position on the LCD static void PrintCharToLcd(char c) { lcdCtrl.write(c); } /************************************************************************************ Print a formated string with the given buffer to LCD. Each task should use its own buffer to prevent data corruption. ************************************************************************************/ void PrintToLcdWithBuf(char *buf, int size, char *format, ...) { va_list args; va_start(args, format); PrintToDeviceWithBuf(PrintCharToLcd, buf, size, format, args); va_end(args); } /******************************************************************************* * Function: PlayerWindowStateMachine * * Description: State Machine for MP3 Player Window UI Inerface * * Arguments: Event_Type * * Return Value: None * ******************************************************************************/ void PlayerWindowStateMachine(PlayerWindow *pWindow, Event_Type winEvent) { OS_CPU_SR cpu_sr; switch (winEvent) { case EVENT_PLAY_PRESS: buttonPressResponse(&pWindow->button_list[PLAY]); pWindow->button_list[PLAY].drawButton(); break; case EVENT_PLAY_RELEASE: buttonReleaseResponse(&pWindow->button_list[PLAY]); pWindow->button_list[PLAY].drawButton(); drawPlayStatus(player_status[PLAYING]); break; case EVENT_PAUSE_PRESS: buttonPressResponse(&pWindow->button_list[PAUSE]); pWindow->button_list[PAUSE].drawButton(); break; case EVENT_PAUSE_RELEASE: buttonReleaseResponse(&pWindow->button_list[PAUSE]); pWindow->button_list[PAUSE].drawButton(); drawPlayStatus(player_status[PAUSED]); break; case EVENT_STOP_PRESS: buttonPressResponse(&pWindow->button_list[STOP]); pWindow->button_list[STOP].drawButton(); break; case EVENT_STOP_RELEASE: buttonReleaseResponse(&pWindow->button_list[STOP]); pWindow->button_list[STOP].drawButton(); setMenuToActiveState(&pWindow->status_box); pWindow->status_box.drawButton(false, false); OSTimeDly(50); setMenuToInactiveState(&pWindow->status_box); pWindow->status_box.drawButton(false, false); statusBarBtnCnt = -1; drawPlayStatus(player_status[STOPPED]); break; case EVENT_REWIND_PRESS: buttonPressResponse(&pWindow->button_list[REWIND]); pWindow->button_list[REWIND].drawButton(); break; case EVENT_REWIND_RELEASE: buttonReleaseResponse(&pWindow->button_list[REWIND]); pWindow->button_list[REWIND].drawButton(); break; case EVENT_FF_PRESS: buttonPressResponse(&pWindow->button_list[FF]); pWindow->button_list[FF].drawButton(); break; case EVENT_FF_RELEASE: buttonReleaseResponse(&pWindow->button_list[FF]); pWindow->button_list[FF].drawButton(); break; case EVENT_UP_PRESS: buttonPressResponse(&pWindow->button_list[UP]); pWindow->button_list[UP].drawButton(); break; case EVENT_UP_RELEASE: buttonReleaseResponse(&pWindow->button_list[UP]); pWindow->button_list[UP].drawButton(); if((currMenuSelectCounter-1) == -1) { if(getActiveButtonCount(false) > 0) { activeMenuBtnCnt = getActiveButtonCount(false); // Set last button to active state before resetting button values setMenuToActiveState(&pWindow->menu_list[currMenuSelectCounter]); pWindow->menu_list[currMenuSelectCounter].drawButton(false, true); currSongFilePntr--; // Reinit with new values InitMenuLabels(pWindow,false); currMenuSelectCounter = activeMenuBtnCnt-1; // Set last menu button as selected setMenuToSelectState(&pWindow->menu_list[currMenuSelectCounter]); pWindow->menu_list[currMenuSelectCounter].drawButton(false, true); } else { //need to be dealt here activeMenuBtnCnt = getActiveButtonCount(true); } } else if(activeMenuBtnCnt != 0) { setMenuToActiveState(&pWindow->menu_list[currMenuSelectCounter]); pWindow->menu_list[currMenuSelectCounter].drawButton(false, true); OS_ENTER_CRITICAL(); currSongFilePntr--; OS_EXIT_CRITICAL(); currMenuSelectCounter--; setMenuToSelectState(&pWindow->menu_list[currMenuSelectCounter]); pWindow->menu_list[currMenuSelectCounter].drawButton(false, true); } else { } break; case EVENT_DOWN_PRESS: buttonPressResponse(&pWindow->button_list[DOWN]); pWindow->button_list[DOWN].drawButton(); break; case EVENT_DOWN_RELEASE: buttonReleaseResponse(&pWindow->button_list[DOWN]); pWindow->button_list[DOWN].drawButton(); if((currMenuSelectCounter+1) == activeMenuBtnCnt) { if(getActiveButtonCount(true) > 0) { activeMenuBtnCnt = getActiveButtonCount(true); // Set last button to active state before resetting button values setMenuToActiveState(&pWindow->menu_list[currMenuSelectCounter]); pWindow->menu_list[currMenuSelectCounter].drawButton(false, true); OS_ENTER_CRITICAL(); ; currSongFilePntr++; OS_EXIT_CRITICAL(); // Reinit with new values InitMenuLabels(pWindow,true); currMenuSelectCounter = 0; // Set first menu button as selected setMenuToSelectState(&pWindow->menu_list[currMenuSelectCounter]); pWindow->menu_list[currMenuSelectCounter].drawButton(false, true); } else { activeMenuBtnCnt = getActiveButtonCount(false); } } else if(activeMenuBtnCnt != 0 && currSongFilePntr != sizeOfList -1) { setMenuToActiveState(&pWindow->menu_list[currMenuSelectCounter]); pWindow->menu_list[currMenuSelectCounter].drawButton(false, true); OS_ENTER_CRITICAL(); currSongFilePntr++; OS_EXIT_CRITICAL(); currMenuSelectCounter++; setMenuToSelectState(&pWindow->menu_list[currMenuSelectCounter]); pWindow->menu_list[currMenuSelectCounter].drawButton(false, true); } break; case EVENT_VOLPLUS_PRESS: buttonPressResponse(&pWindow->button_list[VOLPLUS]); pWindow->button_list[VOLPLUS].drawButton(); break; case EVENT_VOLPLUS_RELEASE: buttonReleaseResponse(&pWindow->button_list[VOLPLUS]); pWindow->button_list[VOLPLUS].drawButton(); if(volumeBarBtnCnt < (INT8S)(VOLUMEBARSNUM-1)) { volumeBarBtnCnt += 1; updateVolumeBar(&pWindow->vol_bar[volumeBarBtnCnt], OS_TRUE); pWindow->vol_bar[volumeBarBtnCnt].drawButton(); } break; case EVENT_VOLMINUS_PRESS: buttonPressResponse(&pWindow->button_list[VOLMINUS]); pWindow->button_list[VOLMINUS].drawButton(); break; case EVENT_VOLMINUS_RELEASE: buttonReleaseResponse(&pWindow->button_list[VOLMINUS]); pWindow->button_list[VOLMINUS].drawButton(); if(volumeBarBtnCnt >= 0) { updateVolumeBar(&pWindow->vol_bar[volumeBarBtnCnt]); pWindow->vol_bar[volumeBarBtnCnt].drawButton(); volumeBarBtnCnt--; } break; case EVENT_STATUSBAR_INC: if(statusBarBtnCnt < (INT8S)(STATUSBARSNUM-1)) { statusBarBtnCnt += 1; updateStatusBar(&pWindow->status_bar[statusBarBtnCnt], OS_TRUE); pWindow->status_bar[statusBarBtnCnt].drawButton(); } break; case EVENT_STATUSBAR_DEC: // MP3 ensures status increment and decrement in the range of 1/10th if(statusBarBtnCnt >= 0) { updateStatusBar(&pWindow->status_bar[statusBarBtnCnt]); pWindow->status_bar[statusBarBtnCnt].drawButton(); statusBarBtnCnt--; } break; case EVENT_NONE: break; default: break; } }<file_sep>/** discoveryboard.h Board specific definitions live here Developed for University of Washington embedded systems programming certificate 2021/1 <NAME> wrote/arranged it */ #ifndef __DISCOVERYBOARD_H #define __DISCOVERYBOARD_H /* Includes ------------------------------------------------------------------*/ #include "stm32l4xx.h" #include "stm32l4xx_ll_system.h" #include "stm32l4xx_ll_rcc.h" #include "stm32l4xx_ll_bus.h" #include "stm32l4xx_ll_usart.h" #include "stm32l4xx_ll_gpio.h" #include "stm32l4xx_ll_spi.h" #include "stm32l4xx_ll_exti.h" #include "stm32l4xx_ll_i2c.h" #include "stm32l4xx_ll_utils.h" #include "stm32l4xx_ll_pwr.h" /* Exported define -----------------------------------------------------------*/ // User button //#define GPIO_PIN_USER_BUTTON LL_GPIO_PIN_13 //#define GPIO_PORT_USER_BUTTON GPIOC // Green LED #define GPIO_PIN_LD2 LL_GPIO_PIN_14 #define GPIO_PORT_LD2 GPIOB // USART GPIO #define GPIO_TX_AF_SOURCE LL_GPIO_PIN_6 #define GPIO_RX_AF_SOURCE LL_GPIO_PIN_7 #define GPIO_USART_AF GPIO_AF_USART1 #define GPIO_PIN_TX LL_GPIO_PIN_6 #define GPIO_PIN_RX LL_GPIO_PIN_7 #define GPIO_PORT_USART GPIOA // USART #define BAUD_RATE 115200 #define COMM USART1 #endif<file_sep>/* bspI2c.c Board support for controlling I2C interfaces Adapted for University of Washington embedded systems programming certificate 2016/2 <NAME> adapted it 2020/8 <NAME> adapted it for ST32L475VGT6 */ #include "bsp.h" #define MAX_TIMEOUT_ITERATIONS 10000 /** * @brief I2C1 Initialization Function * @param None * @retval None */ void BspI2C1_init(void) { /* USER CODE BEGIN I2C1_Init 0 */ /* USER CODE END I2C1_Init 0 */ LL_I2C_InitTypeDef I2C_InitStruct = {0}; LL_GPIO_InitTypeDef GPIO_InitStruct = {0}; LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOB); /**I2C1 GPIO Configuration PB8 ------> I2C1_SCL PB9 ------> I2C1_SDA */ GPIO_InitStruct.Pin = LL_GPIO_PIN_8|LL_GPIO_PIN_9; GPIO_InitStruct.Mode = LL_GPIO_MODE_ALTERNATE; GPIO_InitStruct.Speed = LL_GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.OutputType = LL_GPIO_OUTPUT_OPENDRAIN; GPIO_InitStruct.Pull = LL_GPIO_PULL_UP; GPIO_InitStruct.Alternate = LL_GPIO_AF_4; LL_GPIO_Init(GPIOB, &GPIO_InitStruct); /* Peripheral clock enable */ LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_I2C1); /* USER CODE BEGIN I2C1_Init 1 */ /* USER CODE END I2C1_Init 1 */ /** I2C Initialization */ LL_I2C_EnableAutoEndMode(I2C1); LL_I2C_DisableOwnAddress2(I2C1); LL_I2C_DisableGeneralCall(I2C1); LL_I2C_EnableClockStretching(I2C1); I2C_InitStruct.PeripheralMode = LL_I2C_MODE_I2C; I2C_InitStruct.Timing = 0x00303D5B; I2C_InitStruct.AnalogFilter = LL_I2C_ANALOGFILTER_ENABLE; I2C_InitStruct.DigitalFilter = 0; I2C_InitStruct.OwnAddress1 = 0; I2C_InitStruct.TypeAcknowledge = LL_I2C_ACK; I2C_InitStruct.OwnAddrSize = LL_I2C_OWNADDRESS1_7BIT; LL_I2C_Init(I2C1, &I2C_InitStruct); LL_I2C_SetOwnAddress2(I2C1, 0, LL_I2C_OWNADDRESS2_NOMASK); /* USER CODE BEGIN I2C1_Init 2 */ /* USER CODE END I2C1_Init 2 */ } // Perform a wait with timeout on the given I2C1 flag. If timeout occurs, reset I2C1. // IsActive is a pointer to a LL_I2C_IsActiveFlag_X() function. // value is 0 or 1 and represents the desired active state to wait for. 0 means inactive, 1 means active. void BspI2c_WaitWithTimeoutReset(uint32_t (*IsActive)(I2C_TypeDef *I2Cx), uint32_t value) { int32_t timeoutCount = MAX_TIMEOUT_ITERATIONS; if (value) { while (!(*IsActive)(I2C1) && --timeoutCount); } else { while ((*IsActive)(I2C1) && --timeoutCount); } if (timeoutCount <= 0) BspI2C1_init(); } /* This function issues a start condition and * transmits the slave address + R/W bit * * Parameters: * I2Cx --> the I2C peripheral e.g. I2C1 * address --> the 7 bit slave address * direction --> the transmission direction can be: * LL_I2C_GENERATE_START_WRITE for Master transmitter mode * LL_I2C_GENERATE_START_READ for Master receiver mode */ void I2C_start(I2C_TypeDef* I2Cx, uint8_t address, uint32_t direction, uint32_t request, uint8_t nBytes){ BspI2c_WaitWithTimeoutReset(LL_I2C_IsActiveFlag_BUSY, 0); LL_I2C_HandleTransfer(I2Cx, address, LL_I2C_ADDRSLAVE_7BIT, (uint32_t)nBytes, request, direction); //LL_I2C_MODE_AUTOEND } /* This function transmits one byte to the slave device * Parameters: * I2Cx --> the I2C peripheral e.g. I2C1 * data --> the data byte to be transmitted */ void I2C_write(I2C_TypeDef* I2Cx, uint8_t data) { // Wait for transmit reg to be empty BspI2c_WaitWithTimeoutReset(LL_I2C_IsActiveFlag_TXE, 1); LL_I2C_TransmitData8(I2Cx, data); BspI2c_WaitWithTimeoutReset(LL_I2C_IsActiveFlag_TXE, 1); } /* This function reads one byte from the slave device. * I2C_start must be called first to set up the read. If the NBYTE register * of the specified I2C device becomes 0, a NACK is sent to the slave after * the read, otherwise, ACK is sent. */ uint8_t I2C_read_ack(I2C_TypeDef* I2Cx){ LL_I2C_AcknowledgeNextData(I2Cx, LL_I2C_ACK); BspI2c_WaitWithTimeoutReset(LL_I2C_IsActiveFlag_RXNE, 1); // read data from I2C data register and return data byte uint8_t data = LL_I2C_ReceiveData8(I2Cx); return data; } /* This function reads one byte from the slave device * and doesn't acknowledge the received data * after that a STOP condition is transmitted */ uint8_t I2C_read_nack(I2C_TypeDef* I2Cx){ // disable acknowledge of received data // nack also generates stop condition after last byte received // see reference manual for more info LL_I2C_AcknowledgeNextData(I2Cx, LL_I2C_NACK); // wait until one byte has been received BspI2c_WaitWithTimeoutReset(LL_I2C_IsActiveFlag_RXNE, 1); // read data from I2C data register and return data byte uint8_t data = LL_I2C_ReceiveData8(I2Cx); return data; } /* This function issues a stop condition and therefore * releases the bus */ void I2C_stop(I2C_TypeDef* I2Cx){ LL_I2C_GenerateStopCondition(I2Cx); BspI2c_WaitWithTimeoutReset(LL_I2C_IsActiveFlag_STOP, 1); } <file_sep>/* mp3UserInterface.h MP3 Player User Interfacing Objects and functions for controlling the LCD Display related activities. Developed for University of Washington embedded systems programming certificate 2021/2 <NAME> it */ #ifndef __MP3USERINTERFACE_H #define __MP3USERINTERFACE_H #include "bsp.h" #include "print.h" #include "events.h" #include "globals.h" #include "mp3UserInterface.h" #include "mp3UiSettings.h" #define BUFFERSIZE 32U // Play Status typedef enum { SELECT = 0, PLAYING, PAUSED, STOPPED } PlayStatus; typedef struct{ char *label; uint16_t x_coordinate; uint16_t y_coordinate; uint8_t width; uint8_t height; }ButtonParameter; // LCD Controller Setup and Inialization void SetUpLCDInterface (); // MP3 Player Window Control Functions void InitPlayerWindow(PlayerWindow *pWindow); //void DeinitPlayerWindow(PlayerWindow *pWindow); void DrawPlayerWindow(PlayerWindow *pWindow); void PlayerWindowStateMachine(PlayerWindow *pWindow, Event_Type winEvent); void PrintToLcdWithBuf(char *buf, int size, char *format, ...); #endif <file_sep>/* bspLcd.c Board support for controlling the ILI9341 LCD on the Adafruit '2.8" TFT LCD w/Cap Touch' via NUCLEO-F401RE MCU Developed for University of Washington embedded systems programming certificate 2016/2 <NAME> wrote/arranged it */ #include "bsp.h" // Initializes GPIO pins for the ILI9341 LCD device. void BspLcdInitILI9341() { LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOA); LL_GPIO_InitTypeDef GPIO_InitStruct; /*-------- Configure CS ChipSelect Pin --------*/ GPIO_InitStruct.Pin = LCD_ILI9341_CS_GPIO_Pin; GPIO_InitStruct.Mode = LL_GPIO_MODE_OUTPUT; GPIO_InitStruct.Speed = LL_GPIO_SPEED_FREQ_HIGH; GPIO_InitStruct.OutputType = LL_GPIO_OUTPUT_PUSHPULL; GPIO_InitStruct.Pull = LL_GPIO_PULL_UP; LL_GPIO_Init(LCD_ILI9341_CS_GPIO, &GPIO_InitStruct); LCD_ILI9341_CS_DEASSERT(); /*-------- Configure DC Data/Command Pin --------*/ GPIO_InitStruct.Pin = LCD_ILI9341_DC_GPIO_Pin; GPIO_InitStruct.Mode = LL_GPIO_MODE_OUTPUT; GPIO_InitStruct.Speed = LL_GPIO_SPEED_FREQ_HIGH; GPIO_InitStruct.OutputType = LL_GPIO_OUTPUT_PUSHPULL; GPIO_InitStruct.Pull = LL_GPIO_PULL_UP; LL_GPIO_Init(LCD_ILI9341_DC_GPIO, &GPIO_InitStruct); }<file_sep>/* bspSD.c Board support for controlling the SD on the Adafruit shields via NUCLEO-F401RE MCU Developed for University of Washington embedded systems programming certificate 2016/2 <NAME> wrote/arranged it */ #include "bsp.h" // Initializes GPIO pins for the SD device. void BspSDInitAdafruit() { LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOA); LL_GPIO_InitTypeDef GPIO_InitStruct; /*-------- Configure CS ChipSelect Pin --------*/ GPIO_InitStruct.Pin = SD_ADAFRUIT_CS_GPIO_Pin; GPIO_InitStruct.Mode = LL_GPIO_MODE_OUTPUT; GPIO_InitStruct.Speed = LL_GPIO_SPEED_FREQ_HIGH; GPIO_InitStruct.OutputType = LL_GPIO_OUTPUT_PUSHPULL; GPIO_InitStruct.Pull = LL_GPIO_PULL_UP; LL_GPIO_Init(SD_ADAFRUIT_CS_GPIO, &GPIO_InitStruct); SD_ADAFRUIT_CS_DEASSERT(); }<file_sep>/* bspUart.c Board support for controlling UART interfaces Developed for University of Washington embedded systems programming certificate 2016/2 <NAME> wrote/arranged it for NUCLEO-F401RE 2020/8 <NAME> wrote/arranged it for STM32L475 */ #include "bsp.h" void UartInit(uint32_t baud) { USARTx_GPIO_CLK_ENABLE(); /* Configure Tx Pin as : Alternate function, High Speed, Push pull, Pull up */ LL_GPIO_SetPinMode(USARTx_TX_GPIO_PORT, USARTx_TX_PIN, LL_GPIO_MODE_ALTERNATE); USARTx_SET_TX_GPIO_AF(); LL_GPIO_SetPinSpeed(USARTx_TX_GPIO_PORT, USARTx_TX_PIN, LL_GPIO_SPEED_FREQ_HIGH); LL_GPIO_SetPinOutputType(USARTx_TX_GPIO_PORT, USARTx_TX_PIN, LL_GPIO_OUTPUT_PUSHPULL); LL_GPIO_SetPinPull(USARTx_TX_GPIO_PORT, USARTx_TX_PIN, LL_GPIO_PULL_UP); /* Configure Rx Pin as : Alternate function, High Speed, Push pull, Pull up */ LL_GPIO_SetPinMode(USARTx_RX_GPIO_PORT, USARTx_RX_PIN, LL_GPIO_MODE_ALTERNATE); USARTx_SET_RX_GPIO_AF(); LL_GPIO_SetPinSpeed(USARTx_RX_GPIO_PORT, USARTx_RX_PIN, LL_GPIO_SPEED_FREQ_HIGH); LL_GPIO_SetPinOutputType(USARTx_RX_GPIO_PORT, USARTx_RX_PIN, LL_GPIO_OUTPUT_PUSHPULL); LL_GPIO_SetPinPull(USARTx_RX_GPIO_PORT, USARTx_RX_PIN, LL_GPIO_PULL_UP); /* (2) Enable USART peripheral clock and clock source ***********************/ USARTx_CLK_ENABLE(); /* Set clock source */ USARTx_CLK_SOURCE(); /* (3) Configure USART functional parameters ********************************/ /* Disable USART prior modifying configuration registers */ /* Note: Commented as corresponding to Reset value */ // LL_USART_Disable(USARTx_INSTANCE); /* TX/RX direction */ LL_USART_SetTransferDirection(USARTx_INSTANCE, LL_USART_DIRECTION_TX_RX); /* 8 data bit, 1 start bit, 1 stop bit, no parity */ LL_USART_ConfigCharacter(USARTx_INSTANCE, LL_USART_DATAWIDTH_8B, LL_USART_PARITY_NONE, LL_USART_STOPBITS_1); /* No Hardware Flow control */ /* Reset value is LL_USART_HWCONTROL_NONE */ // LL_USART_SetHWFlowCtrl(USARTx_INSTANCE, LL_USART_HWCONTROL_NONE); /* Oversampling by 16 */ /* Reset value is LL_USART_OVERSAMPLING_16 */ // LL_USART_SetOverSampling(USARTx_INSTANCE, LL_USART_OVERSAMPLING_16); /* Set Baudrate to 115200 using APB frequency set to 80000000 Hz */ /* Frequency available for USART peripheral can also be calculated through LL RCC macro */ /* Ex : Periphclk = LL_RCC_GetUSARTClockFreq(Instance); or LL_RCC_GetUARTClockFreq(Instance); depending on USART/UART instance In this example, Peripheral Clock is expected to be equal to 80000000 Hz => equal to SystemCoreClock */ uint32_t Periphclk = LL_RCC_GetUSARTClockFreq(USARTx_CLKSOURCE); LL_USART_SetBaudRate(USARTx_INSTANCE, Periphclk, LL_USART_OVERSAMPLING_16, baud); /* (4) Enable USART *********************************************************/ LL_USART_Enable(USARTx_INSTANCE); /* Polling USART initialisation */ while((!(LL_USART_IsActiveFlag_TEACK(USARTx_INSTANCE))) || (!(LL_USART_IsActiveFlag_REACK(USARTx_INSTANCE)))) { } } /** * @brief Print a character on the HyperTerminal * @param c: The character to be printed * @retval None */ void PrintByte(char c) { LL_USART_TransmitData8(COMM, c); while (!LL_USART_IsActiveFlag_TXE(COMM)); } /** * @brief Busy wait for a character on the HyperTerminal * @retval: The character that was read */ char ReadByte() { while (!LL_USART_IsEnabledIT_RXNE(COMM)); uint16_t c =LL_USART_ReceiveData8(COMM); LL_USART_DisableIT_RXNE(COMM); return c; }<file_sep>/* hw_init.h 2021/1 <NAME> wrote/arranged it */ #ifndef __HW_INIT_H #define __HW_INIT_H // Application interface to hardware void Hw_init(void); void SetSysTick(uint32_t ticksPerSec); #endif /* __HW_INIT_H */<file_sep>/* mp3TouchInterface.c MP3 Player Touch Interface Implementation Developed for University of Washington embedded systems programming certificate 2021/3 <NAME> wrote/arranged it */ #include "mp3TouchInterface.h" static long MapTouchToScreen(long x, long in_min, long in_max, long out_min, long out_max); Event_Type event; // The touch controller Instance Adafruit_FT6206 touchCtrl = Adafruit_FT6206(); // Button Status // It's 0th - 8th bits (mapped with PlayerButtonIndex) are used to track button status // Set to 1 if button press activity is carried out, else default 0 (release/noactivity) static unsigned int ButtonStatus = 0; //static HANDLE hI2c = 0; // Function Definitions static boolean IsAnyButtonsPressed (void); static void SetButtonStatus (unsigned int index); static void ResetButtonStatus (unsigned int index); static unsigned int WhichButtonWasPressed (void); /******************************************************************************* * Function: SetUpTouchInterface * * Description: Set Up Touch Controller and related interface. * * Arguments: * * Return Value: None * ******************************************************************************/ void SetUpTouchInterface(void) { PjdfErrCode pjdfErr; // Open a HANDLE for accessing device PJDF_DEVICE_ID_I2C1 HANDLE hI2c = Open(PJDF_DEVICE_ID_I2C1, 0); if (!PJDF_IS_VALID_HANDLE(hI2c)) while(1); // Call Ioctl on that handle to set the I2C device address to FT6206_ADDR INT8U addressFT6206 = (FT6206_ADDR << 1); pjdfErr = Ioctl(hI2c, PJDF_CTRL_I2C_SET_DEVICE_ADDRESS, &addressFT6206, NULL); if(PJDF_IS_ERROR(pjdfErr)) while(1); // Call setPjdfHandle() on the touch contoller to pass in the I2C handle touchCtrl.setPjdfHandle(hI2c); if (! touchCtrl.begin(40)) { // pass in 'sensitivity' coefficient //PrintWithBuf(buf, BUFSIZE, "Couldn't start FT6206 touchscreen controller\n"); while (1); } } /******************************************************************************* * Function: TouchEventGenerator * * Description: It maps the touch points w.r.t screen orientation, if touch points * match with any MP3 Player window buttons - updates button's press * status. And then based on press/release status, it sends events in mailbox * Note: Ensures not to send multiple press/release events of a button * Also handles one button press/release event at a time * * Arguments: * * Return Value: None * ******************************************************************************/ void TouchEventGenerator (PlayerWindow pWindow) { boolean touched; // Get touch status touched = touchCtrl.touched(); if(IsAnyButtonsPressed() & !touched) { unsigned int button; // implies button was released, so send a release event for the respective button button = WhichButtonWasPressed(); // button events were numbered w.r.t to number of events in system - release is just a numeric up event = (Event_Type) (button * NUM_TYPE_OF_EVENTS + BUTTON_RELEASED); OSMboxPost(touchEventsMbox, (void*)&event); // Rest button Status ResetButtonStatus(button); } else if( !(IsAnyButtonsPressed()) & touched) { TS_Point point; TS_Point p = TS_Point(); point = touchCtrl.getPoint(); if (point.x == 0 && point.y == 0) { //break; // usually spurious, so ignore } // transform touch orientation to screen orientation. p.x = MapTouchToScreen(point.x, 0, ILI9341_TFTWIDTH, ILI9341_TFTWIDTH, 0); p.y = MapTouchToScreen(point.y, 0, ILI9341_TFTHEIGHT, ILI9341_TFTHEIGHT, 0); // If button is pressed, set button status and send button status event for(unsigned int button = PLAY; button < PLAYERBUTTONNUM; ++button) { if (pWindow.button_list[button].contains(p.x, p.y)) { event = (Event_Type) (button * NUM_TYPE_OF_EVENTS + BUTTON_PRESSED); OSMboxPost(touchEventsMbox, (void*)&event); SetButtonStatus(button); } } } else { // TBD } } /******************************************************************************* * Function: MapTouchToScreen * * Description: Transform touch orientation to the screen orientation * * Arguments: x - x or y coordinate value * in_main - starting x or y axis value * in_max - end x or y axis value * out_min - end x or y axis value * out_max - starting x or y axis value * * Return Value: screen equivalent touch point (x or y coordinate) * ******************************************************************************/ static long MapTouchToScreen(long x, long in_min, long in_max, long out_min, long out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } /******************************************************************************* * Function: IsAnyButtonsPressed * * Description: Sends true, if any of the button is pressed at any given time * * Note: Buttons could be either pressed or released state * * Arguments: None * * Return Value: boolean * ******************************************************************************/ static boolean IsAnyButtonsPressed (void) { return (ButtonStatus > 0); } /******************************************************************************* * Function: SetButtonStatus * * Description: Sets respective index (identified as button) of ButtonStatus * * Arguments: index * * Return Value: None * ******************************************************************************/ static void SetButtonStatus (unsigned int index) { ButtonStatus |= (1 << index); } /******************************************************************************* * Function: ResetButtonStatus * * Description: Resets respective index (identified as button) of ButtonStatus * * Arguments: index * * Return Value: None * ******************************************************************************/ static void ResetButtonStatus (unsigned int index) { ButtonStatus &= ~(1 << index); } /******************************************************************************* * Function: WhichButtonWasPressed * * Description: Get the index of button that was pressed * To be used if any button press event had occured ( * i.e. call IsAnyButtonsPressed() before) * * Arguments: None * * Return Value: unsigned int -> button index value * ******************************************************************************/ static unsigned int WhichButtonWasPressed (void) { unsigned int index = PLAY; int item = ButtonStatus; while (item > 1) { item >>= 1; ++index; } return index; }<file_sep>/* events.h Header file for for event-definition of the application and some helping functions for managing OS Events. Developed for University of Washington embedded systems programming certificate 2021/3 <NAME> wrote/arranged it */ #ifndef __EVENTS_H #define __EVENTS_H #define EVENT_QUEUE_SIZE 20U #define NUM_TYPE_OF_EVENTS 10U // display events group // Specific for controlling Display events typedef enum { // Play Button Event EVENT_PLAY_PRESS = 0, EVENT_PLAY_RELEASE, // Pause Button Event EVENT_PAUSE_PRESS = 10, EVENT_PAUSE_RELEASE, // Stop Button Event EVENT_STOP_PRESS = 20, EVENT_STOP_RELEASE, // Rewind Button Event EVENT_REWIND_PRESS = 30, EVENT_REWIND_RELEASE, // Fast Forward Button Event EVENT_FF_PRESS = 40, EVENT_FF_RELEASE, // UP Button Event EVENT_UP_PRESS = 50, EVENT_UP_RELEASE, // Down Button Event EVENT_DOWN_PRESS = 60, EVENT_DOWN_RELEASE, // Volume Increase Button Event EVENT_VOLPLUS_PRESS = 70, EVENT_VOLPLUS_RELEASE, // Volume Decrease Button Event EVENT_VOLMINUS_PRESS = 80, EVENT_VOLMINUS_RELEASE, // Status Bar Increment and Decrement Update Event EVENT_STATUSBAR_INC, EVENT_STATUSBAR_DEC, EVENT_NONE } Event_Type; // MP3 Decoder Task event flags -- not using /* typedef enum { setPlayFlag = (OS_FLAGS)0x1, setPauseFlag, // pause event works if setPlayFlag is set setStopFlag, // stop event works if setStopFlag is set setFastForwardFlag, // fast forward event works if setPlayFlag is set setRewindFlag, // Rewind flag works if setPlayFlag is set setVolUpFlag, setVolDownFlag } Flag_Type; */ // OS Events extern OS_EVENT *touchEventsMbox; extern OS_EVENT *mp3EventsMbox; //extern OS_EVENT *mtxFileFetch; // Event flags for controlling MP3 Streaming Events /* extern OS_FLAG_GRP *mp3Flags; extern OS_FLAGS MP3PlayFlag; */ extern OS_EVENT *displayQMsg; extern void * displayQMsgPtrs[EVENT_QUEUE_SIZE]; #endif<file_sep>/************************************************************************************ Copyright (c) 2001-2016 University of Washington Extension. Module Name: tasks.c Module Description: The tasks that are executed by the test application. 2016/2 <NAME> adapted it for NUCLEO-F401RE ************************************************************************************/ #include <stdarg.h> #include "bsp.h" #include "print.h" #include "mp3Util.h" #include <Adafruit_GFX.h> // Core graphics library #include <Adafruit_ILI9341.h> #include <Adafruit_FT6206.h> Adafruit_ILI9341 lcdCtrl = Adafruit_ILI9341(); // The LCD controller Adafruit_FT6206 touchCtrl = Adafruit_FT6206(); // The touch controller #define PENRADIUS 3 long MapTouchToScreen(long x, long in_min, long in_max, long out_min, long out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } #include "train_crossing.h" #define BUFSIZE 256 /************************************************************************************ Allocate the stacks for each task. The maximum number of tasks the application can have is defined by OS_MAX_TASKS in os_cfg.h ************************************************************************************/ static OS_STK LcdTouchDemoTaskStk[APP_CFG_TASK_START_STK_SIZE]; static OS_STK Mp3DemoTaskStk[APP_CFG_TASK_START_STK_SIZE]; // Task prototypes void LcdTouchDemoTask(void* pdata); void Mp3DemoTask(void* pdata); // Useful functions void PrintToLcdWithBuf(char *buf, int size, char *format, ...); // Globals BOOLEAN nextSong = OS_FALSE; /************************************************************************************ This task is the initial task running, started by main(). It starts the system tick timer and creates all the other tasks. Then it deletes itself. ************************************************************************************/ void StartupTask(void* pdata) { char buf[BUFSIZE]; PjdfErrCode pjdfErr; INT32U length; static HANDLE hSD = 0; static HANDLE hSPI = 0; PrintWithBuf(buf, BUFSIZE, "StartupTask: Begin\n"); PrintWithBuf(buf, BUFSIZE, "StartupTask: Starting timer tick\n"); // Start the system tick SetSysTick(OS_TICKS_PER_SEC); // Initialize SD card PrintWithBuf(buf, PRINTBUFMAX, "Opening handle to SD driver: %s\n", PJDF_DEVICE_ID_SD_ADAFRUIT); hSD = Open(PJDF_DEVICE_ID_SD_ADAFRUIT, 0); if (!PJDF_IS_VALID_HANDLE(hSD)) while(1); PrintWithBuf(buf, PRINTBUFMAX, "Opening SD SPI driver: %s\n", SD_SPI_DEVICE_ID); // We talk to the SD controller over a SPI interface therefore // open an instance of that SPI driver and pass the handle to // the SD driver. hSPI = Open(SD_SPI_DEVICE_ID, 0); if (!PJDF_IS_VALID_HANDLE(hSPI)) while(1); length = sizeof(HANDLE); pjdfErr = Ioctl(hSD, PJDF_CTRL_SD_SET_SPI_HANDLE, &hSPI, &length); if(PJDF_IS_ERROR(pjdfErr)) while(1); // Create the test tasks PrintWithBuf(buf, BUFSIZE, "StartupTask: Creating the application tasks\n"); // The maximum number of tasks the application can have is defined by OS_MAX_TASKS in os_cfg.h OSTaskCreate(Mp3DemoTask, (void*)0, &Mp3DemoTaskStk[APP_CFG_TASK_START_STK_SIZE-1], APP_TASK_TEST1_PRIO); OSTaskCreate(LcdTouchDemoTask, (void*)0, &LcdTouchDemoTaskStk[APP_CFG_TASK_START_STK_SIZE-1], APP_TASK_TEST2_PRIO); // Delete ourselves, letting the work be done in the new tasks. PrintWithBuf(buf, BUFSIZE, "StartupTask: deleting self\n"); OSTaskDel(OS_PRIO_SELF); } static void DrawLcdContents() { char buf[BUFSIZE]; OS_CPU_SR cpu_sr; // allow slow lower pri drawing operation to finish without preemption OS_ENTER_CRITICAL(); lcdCtrl.fillScreen(ILI9341_BLACK); // Print a message on the LCD lcdCtrl.setCursor(40, 60); lcdCtrl.setTextColor(ILI9341_WHITE); lcdCtrl.setTextSize(2); PrintToLcdWithBuf(buf, BUFSIZE, "Hello World!"); OS_EXIT_CRITICAL(); } /************************************************************************************ Runs LCD/Touch demo code ************************************************************************************/ void LcdTouchDemoTask(void* pdata) { PjdfErrCode pjdfErr; INT32U length; char buf[BUFSIZE]; PrintWithBuf(buf, BUFSIZE, "LcdTouchDemoTask: starting\n"); PrintWithBuf(buf, BUFSIZE, "Opening LCD driver: %s\n", PJDF_DEVICE_ID_LCD_ILI9341); // Open handle to the LCD driver HANDLE hLcd = Open(PJDF_DEVICE_ID_LCD_ILI9341, 0); if (!PJDF_IS_VALID_HANDLE(hLcd)) while(1); PrintWithBuf(buf, BUFSIZE, "Opening LCD SPI driver: %s\n", LCD_SPI_DEVICE_ID); // We talk to the LCD controller over a SPI interface therefore // open an instance of that SPI driver and pass the handle to // the LCD driver. HANDLE hSPI = Open(LCD_SPI_DEVICE_ID, 0); if (!PJDF_IS_VALID_HANDLE(hSPI)) while(1); length = sizeof(HANDLE); pjdfErr = Ioctl(hLcd, PJDF_CTRL_LCD_SET_SPI_HANDLE, &hSPI, &length); if(PJDF_IS_ERROR(pjdfErr)) while(1); PrintWithBuf(buf, BUFSIZE, "Initializing LCD controller\n"); lcdCtrl.setPjdfHandle(hLcd); lcdCtrl.begin(); DrawLcdContents(); PrintWithBuf(buf, BUFSIZE, "Initializing FT6206 touchscreen controller\n"); if (! touchCtrl.begin(40)) { // pass in 'sensitivity' coefficient PrintWithBuf(buf, BUFSIZE, "Couldn't start FT6206 touchscreen controller\n"); while (1); } int currentcolor = ILI9341_RED; while (1) { boolean touched; touched = touchCtrl.touched(); if (! touched) { OSTimeDly(5); continue; } TS_Point point; point = touchCtrl.getPoint(); if (point.x == 0 && point.y == 0) { continue; // usually spurious, so ignore } // transform touch orientation to screen orientation. TS_Point p = TS_Point(); p.x = MapTouchToScreen(point.x, 0, ILI9341_TFTWIDTH, ILI9341_TFTWIDTH, 0); p.y = MapTouchToScreen(point.y, 0, ILI9341_TFTHEIGHT, ILI9341_TFTHEIGHT, 0); lcdCtrl.fillCircle(p.x, p.y, PENRADIUS, currentcolor); } } /************************************************************************************ Runs MP3 demo code ************************************************************************************/ void Mp3DemoTask(void* pdata) { PjdfErrCode pjdfErr; INT32U length; char buf[BUFSIZE]; PrintWithBuf(buf, BUFSIZE, "Mp3DemoTask: starting\n"); PrintWithBuf(buf, BUFSIZE, "Opening MP3 driver: %s\n", PJDF_DEVICE_ID_MP3_VS1053); // Open handle to the MP3 decoder driver HANDLE hMp3 = Open(PJDF_DEVICE_ID_MP3_VS1053, 0); if (!PJDF_IS_VALID_HANDLE(hMp3)) while(1); PrintWithBuf(buf, BUFSIZE, "Opening MP3 SPI driver: %s\n", MP3_SPI_DEVICE_ID); // We talk to the MP3 decoder over a SPI interface therefore // open an instance of that SPI driver and pass the handle to // the MP3 driver. HANDLE hSPI = Open(MP3_SPI_DEVICE_ID, 0); if (!PJDF_IS_VALID_HANDLE(hSPI)) while(1); length = sizeof(HANDLE); pjdfErr = Ioctl(hMp3, PJDF_CTRL_MP3_SET_SPI_HANDLE, &hSPI, &length); if(PJDF_IS_ERROR(pjdfErr)) while(1); // Send initialization data to the MP3 decoder and run a test PrintWithBuf(buf, BUFSIZE, "Starting MP3 device test\n"); Mp3Init(hMp3); int count = 0; while (1) { OSTimeDly(500); PrintWithBuf(buf, BUFSIZE, "Begin streaming sound file count=%d\n", ++count); Mp3Stream(hMp3, (INT8U*)Train_Crossing, sizeof(Train_Crossing)); PrintWithBuf(buf, BUFSIZE, "Done streaming sound file count=%d\n", count); } } // Renders a character at the current cursor position on the LCD static void PrintCharToLcd(char c) { lcdCtrl.write(c); } /************************************************************************************ Print a formated string with the given buffer to LCD. Each task should use its own buffer to prevent data corruption. ************************************************************************************/ void PrintToLcdWithBuf(char *buf, int size, char *format, ...) { va_list args; va_start(args, format); PrintToDeviceWithBuf(PrintCharToLcd, buf, size, format, args); va_end(args); } <file_sep>/* mp3TouchInterface.h MP3 Player Touch Interfacing Objects and functions for controlling the LCD Touch related activities. Developed for University of Washington embedded systems programming certificate 2021/3 <NAME> wrote/arranged it */ #ifndef __MP3TOUCHINTERFACE_H #define __MP3TOUCHINTERFACE_H #include "bsp.h" #include "print.h" #include "events.h" #include "mp3UiSettings.h" #include <Adafruit_FT6206.h> // Button Status typedef enum { BUTTON_PRESSED = 0, BUTTON_RELEASED } ButtonState; // LCD Controller Setup and Inialization void SetUpTouchInterface (void); // Touch Event Generator void TouchEventGenerator (PlayerWindow pWindow); #endif<file_sep>/* bspSD.h Board support for controlling the SD on the Adafruit shields via NUCLEO-F401RE MCU Developed for University of Washington embedded systems programming certificate 2016/2 <NAME> wrote/arranged it */ #include "stm32l4xx.h" #ifndef __BSPSD_H #define __BSPSD_H #define SD_ADAFRUIT_CS_GPIO GPIOA #define SD_ADAFRUIT_CS_GPIO_Pin LL_GPIO_PIN_3 #define SD_ADAFRUIT_CS_ASSERT() LL_GPIO_ResetOutputPin(SD_ADAFRUIT_CS_GPIO, SD_ADAFRUIT_CS_GPIO_Pin); #define SD_ADAFRUIT_CS_DEASSERT() LL_GPIO_SetOutputPin(SD_ADAFRUIT_CS_GPIO, SD_ADAFRUIT_CS_GPIO_Pin); #define SD_ADAFRUIT_DC_LOW() LL_GPIO_ResetOutputPin(SD_ADAFRUIT_DC_GPIO, SD_ADAFRUIT_DC_GPIO_Pin); #define SD_ADAFRUIT_DC_HIGH() LL_GPIO_SetOutputPin(SD_ADAFRUIT_DC_GPIO, SD_ADAFRUIT_DC_GPIO_Pin); #define SD_SPI_DEVICE_ID PJDF_DEVICE_ID_SPI1 //#define SD_SPI_DATARATE LL_SPI_BAUDRATEPRESCALER_DIV2 // Tune to find optimal value SD controller will work with. OK with 16mhz HCLK #define SD_SPI_DATARATE LL_SPI_BAUDRATEPRESCALER_DIV4 // Tune to find optimal value SD controller will work with. OK with 80MHz HCLK void BspSDInitAdafruit(); #endif<file_sep>/************************************************************************************ Copyright (c) 2001-2016 University of Washington Extension. Module Name: tasks.c Module Description: The tasks that are executed by the test application. 2016/2 <NAME> adapted it for NUCLEO-F401RE ************************************************************************************/ #include <stdarg.h> #include "bsp.h" #include "events.h" #include "globals.h" #include "print.h" #include "mp3Util.h" #include "mp3UserInterface.h" #include "mp3TouchInterface.h" #include <Adafruit_FT6206.h> #define PENRADIUS 3 //#include "train_crossing.h" #define BUFSIZE 256 char listOfSongs[MAXLISTOFSONGS][SUPPFILENAMESIZE]; // An array to prefetch a list of songs array unsigned int sizeOfList = 0; unsigned int currSongFilePntr = 0; BOOLEAN isPlaying = OS_FALSE; BOOLEAN isStopSong = OS_FALSE; BOOLEAN isFastForward= OS_FALSE; BOOLEAN isRewind = OS_FALSE; BOOLEAN isVolUp = OS_FALSE; BOOLEAN isVolDown = OS_FALSE; INT32U currPlayingSongFilePntr = INT_MAX; /************************************************************************************ Allocate the stacks for each task. The maximum number of tasks the application can have is defined by OS_MAX_TASKS in os_cfg.h ************************************************************************************/ static OS_STK LcdDisplayTaskStk[APP_DISPLAY_TASK_EQ_STK_SIZE]; static OS_STK Mp3StreamTaskStk[APP_MP3STREAM_TASK_EQ_STK_SIZE]; static OS_STK CmdControllerTaskStk[APP_CMD_TASK_EQ_STK_SIZE]; static OS_STK LcdTouchTaskStk[APP_TOUCH_TASK_EQ_STK_SIZE]; // Task prototypes void LcdDisplayTask(void* pdata); void Mp3StreamTask(void* pdata); void CmdControllerTask(void* pdata); void LcdTouchTask(void* pdata); // Globals PlayerWindow pWindow; // Player Window Instance //OS Events OS_EVENT *touchEventsMbox; OS_EVENT *mp3EventsMbox; OS_EVENT *displayQMsg; void * displayQMsgPtrs[EVENT_QUEUE_SIZE]; /************************************************************************************ This task is the initial task running, started by main(). It starts the system tick timer and creates all the other tasks. Then it deletes itself. ************************************************************************************/ void StartupTask(void* pdata) { char buf[BUFSIZE]; PjdfErrCode pjdfErr; INT32U length; INT8U err = 0; static HANDLE hSD = 0; static HANDLE hSPI = 0; //PrintWithBuf(buf, BUFSIZE, "StartupTask: Begin\n"); //PrintWithBuf(buf, BUFSIZE, "StartupTask: Starting timer tick\n"); // Start the system tick SetSysTick(OS_TICKS_PER_SEC); // Initialize SD card //PrintWithBuf(buf, PRINTBUFMAX, "Opening handle to SD driver: %s\n", PJDF_DEVICE_ID_SD_ADAFRUIT); hSD = Open(PJDF_DEVICE_ID_SD_ADAFRUIT, 0); if (!PJDF_IS_VALID_HANDLE(hSD)) while(1); //PrintWithBuf(buf, PRINTBUFMAX, "Opening SD SPI driver: %s\n", SD_SPI_DEVICE_ID); // We talk to the SD controller over a SPI interface therefore // open an instance of that SPI driver and pass the handle to // the SD driver. hSPI = Open(SD_SPI_DEVICE_ID, 0); if (!PJDF_IS_VALID_HANDLE(hSPI)) while(1); length = sizeof(HANDLE); pjdfErr = Ioctl(hSD, PJDF_CTRL_SD_SET_SPI_HANDLE, &hSPI, &length); if(PJDF_IS_ERROR(pjdfErr)) while(1); if (!SD.begin(hSD)) { //PrintWithBuf(buf, PRINTBUFMAX, "Attempt to initialize SD card failed.\n"); } // Create the test tasks PrintWithBuf(buf, BUFSIZE, "StartupTask: Creating the application tasks\n"); // Create Mailbox touchEventsMbox = OSMboxCreate(NULL); mp3EventsMbox = OSMboxCreate(NULL); //Create Queue displayQMsg = OSQCreate(displayQMsgPtrs, EVENT_QUEUE_SIZE); //Create Event Flag -- not using //mp3Flags = OSFlagCreate( 0x1, &err); // The maximum number of tasks the application can have is defined by OS_MAX_TASKS in os_cfg.h OSTaskCreate(Mp3StreamTask, (void*)0, &Mp3StreamTaskStk[APP_MP3STREAM_TASK_EQ_STK_SIZE-1], APP_TASK_TEST4_PRIO); OSTaskCreate(LcdDisplayTask, (void*)0, &LcdDisplayTaskStk[APP_DISPLAY_TASK_EQ_STK_SIZE-1], APP_TASK_TEST2_PRIO); OSTaskCreate(LcdTouchTask, (void*)0, &LcdTouchTaskStk[APP_TOUCH_TASK_EQ_STK_SIZE-1], APP_TASK_TEST1_PRIO); OSTaskCreate(CmdControllerTask, (void*)0, &CmdControllerTaskStk[APP_CMD_TASK_EQ_STK_SIZE-1], APP_TASK_TEST3_PRIO); // Delete ourselves, letting the work be done in the new tasks. PrintWithBuf(buf, BUFSIZE, "StartupTask: deleting self\n"); OSTaskDel(OS_PRIO_SELF); } /************************************************************************************ Runs LCD Display code ************************************************************************************/ void LcdDisplayTask(void* pdata) { INT8U err; Event_Type winEvent; Mp3FetchFileNames(); SetUpLCDInterface(); InitPlayerWindow(&pWindow); while (1) { winEvent = *((Event_Type*)OSQPend(displayQMsg, 0, &err)); if(err != OS_ERR_NONE) while(1); PlayerWindowStateMachine(&pWindow, winEvent); OSTimeDly(10); } } /************************************************************************************ Runs LCD Display code ************************************************************************************/ void LcdTouchTask(void* pdata) { SetUpTouchInterface(); while (1) { TouchEventGenerator(pWindow); OSTimeDly(10); } } /************************************************************************************ Runs LCD Display code ************************************************************************************/ void CmdControllerTask(void* pdata) { Event_Type receivedEvent = EVENT_NONE; INT8U err = 0; while (1) { receivedEvent = *((Event_Type*)OSMboxPend(touchEventsMbox, 0, &err)); if(err != OS_ERR_NONE) while(1); // Send their respective operating events to MP3 Decoder Task and Display Tasks switch (receivedEvent) { case EVENT_PLAY_PRESS: err = OSQPost(displayQMsg, (void*)&receivedEvent); break; case EVENT_PLAY_RELEASE: //if(!isPaused){ if(currPlayingSongFilePntr != currSongFilePntr) { // exit from song loop isStopSong = OS_TRUE; OSMboxPost(mp3EventsMbox, (void*)&receivedEvent); } OSTimeDly(50); isPlaying = OS_TRUE; err = OSQPost(displayQMsg, (void*)&receivedEvent); break; case EVENT_PAUSE_PRESS: err = OSQPost(displayQMsg, (void*)&receivedEvent); break; case EVENT_PAUSE_RELEASE: isPlaying = OS_FALSE; err = OSQPost(displayQMsg, (void*)&receivedEvent); break; case EVENT_STOP_PRESS: err = OSQPost(displayQMsg, (void*)&receivedEvent); break; case EVENT_STOP_RELEASE: if(isPlaying || (currPlayingSongFilePntr == currSongFilePntr)) { isStopSong = OS_TRUE; } else { err = OSQPost(displayQMsg, (void*)&receivedEvent); } break; case EVENT_REWIND_PRESS: err = OSQPost(displayQMsg, (void*)&receivedEvent); break; case EVENT_REWIND_RELEASE: isRewind = OS_TRUE; err = OSQPost(displayQMsg, (void*)&receivedEvent); break; case EVENT_FF_PRESS: err = OSQPost(displayQMsg, (void*)&receivedEvent); break; case EVENT_FF_RELEASE: isFastForward = OS_TRUE; err = OSQPost(displayQMsg, (void*)&receivedEvent); break; case EVENT_UP_PRESS: err = OSQPost(displayQMsg, (void*)&receivedEvent); break; case EVENT_UP_RELEASE: err = OSQPost(displayQMsg, (void*)&receivedEvent); break; case EVENT_DOWN_PRESS: err = OSQPost(displayQMsg, (void*)&receivedEvent); break; case EVENT_DOWN_RELEASE: err = OSQPost(displayQMsg, (void*)&receivedEvent); break; case EVENT_VOLPLUS_PRESS: err = OSQPost(displayQMsg, (void*)&receivedEvent); break; case EVENT_VOLPLUS_RELEASE: if(isPlaying) isVolUp = OS_TRUE; else OSMboxPost(mp3EventsMbox, (void*)&receivedEvent); err = OSQPost(displayQMsg, (void*)&receivedEvent); break; case EVENT_VOLMINUS_PRESS: err = OSQPost(displayQMsg, (void*)&receivedEvent); break; case EVENT_VOLMINUS_RELEASE: if(isPlaying) isVolDown = OS_TRUE; else OSMboxPost(mp3EventsMbox, (void*)&receivedEvent); err = OSQPost(displayQMsg, (void*)&receivedEvent); break; case EVENT_NONE: break; default: break; } OSTimeDly(5); } } /************************************************************************************ Runs MP3 demo code ************************************************************************************/ void Mp3StreamTask(void* pdata) { Event_Type mp3Event; PjdfErrCode pjdfErr; INT8U err; INT32U length; char buf[BUFSIZE]; PrintWithBuf(buf, BUFSIZE, "Mp3DemoTask: starting\n"); PrintWithBuf(buf, BUFSIZE, "Opening MP3 driver: %s\n", PJDF_DEVICE_ID_MP3_VS1053); // Open handle to the MP3 decoder driver HANDLE hMp3 = Open(PJDF_DEVICE_ID_MP3_VS1053, 0); if (!PJDF_IS_VALID_HANDLE(hMp3)) while(1); PrintWithBuf(buf, BUFSIZE, "Opening MP3 SPI driver: %s\n", MP3_SPI_DEVICE_ID); // We talk to the MP3 decoder over a SPI interface therefore // open an instance of that SPI driver and pass the handle to // the MP3 driver. HANDLE hSPI = Open(MP3_SPI_DEVICE_ID, 0); if (!PJDF_IS_VALID_HANDLE(hSPI)) while(1); length = sizeof(HANDLE); pjdfErr = Ioctl(hMp3, PJDF_CTRL_MP3_SET_SPI_HANDLE, &hSPI, &length); if(PJDF_IS_ERROR(pjdfErr)) while(1); // Send initialization data to the MP3 decoder and run a test PrintWithBuf(buf, BUFSIZE, "Starting MP3 device test\n"); // OS_ENTER_CRITICAL(); // Mp3FetchFileNames(); // OS_EXIT_CRITICAL(); while (1) { //OSTimeDly(50); mp3Event = *((Event_Type*)OSMboxPend(mp3EventsMbox, 0, &err)); if(err != OS_ERR_NONE) while(1); // Process their respective operating events to MP3 Decoder Task and Display Tasks switch (mp3Event) { case EVENT_PLAY_RELEASE: Mp3StreamCycle(hMp3); break; case EVENT_VOLPLUS_RELEASE: Mp3VolumeControl(hMp3, VOLUP); break; case EVENT_VOLMINUS_RELEASE: Mp3VolumeControl(hMp3, VOLDOWN); break; default: break; } } } <file_sep>/* globals.h Global definitions for the application Developed for University of Washington embedded systems programming certificate 2021/2 <NAME> wrote/arranged it */ #ifndef __GLOBALS_H #define __GLOBALS_H #define MAXLISTOFSONGS 100 #define SUPPFILENAMESIZE 13 #define INT_MAX 0x7FFFFFFF extern char listOfSongs[MAXLISTOFSONGS][SUPPFILENAMESIZE]; // An array to prefetch a list of songs array extern unsigned int sizeOfList; // Max allowed songs list = 100, this variable will store the number fetched songs extern unsigned int currSongFilePntr; // points to current song to be played #endif<file_sep>/* bspLed.h Board support for controlling LEDs Developed for University of Washington embedded systems programming certificate 2020/8 <NAME> wrote/arranged it for STM32L475 */ #ifndef __BSPLED_H #define __BSPLED_H #define LED2_PIN LL_GPIO_PIN_5 #define LED2_GPIO_PORT GPIOA #define LED2_GPIO_CLK_ENABLE() LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOA) void LedInit(); void SetLED(BOOLEAN On); #endif /* __BSPLED_H */<file_sep>/* mp3Util.c Some utility functions for controlling the MP3 decoder. Developed for University of Washington embedded systems programming certificate 2016/2 <NAME> wrote/arranged it 2021/2 <NAME> updated to support MP3 Streaming task for the project */ #include "mp3Util.h" #define DEFAULT_VOLUME_INDEX 8 void delay(uint32_t time); static File dataFile; static INT8U mp3Buf[MP3_DECODER_BUF_SIZE]; static INT32U iBufPos = 0; static INT32U iDataFileMovPos = 0; static INT32U iDataFileCurPos = 0; static INT32U iDataFileBegPos = 0; static INT32U progressCounter = 0; static INT8U volProgressCounter = DEFAULT_VOLUME_INDEX; static Event_Type mp3Event; extern BOOLEAN isFileStart; extern BOOLEAN isPlaying; extern BOOLEAN isStopSong; extern BOOLEAN isFastForward; extern BOOLEAN isRewind; extern BOOLEAN isVolUp; extern BOOLEAN isVolDown; extern INT32U currPlayingSongFilePntr; void Mp3StreamInit(HANDLE hMp3) { INT32U length; // Place MP3 driver in command mode (subsequent writes will be sent to the decoder's command interface) Ioctl(hMp3, PJDF_CTRL_MP3_SELECT_COMMAND, 0, 0); // Reset the device length = BspMp3SoftResetLen; Write(hMp3, (void*)BspMp3SoftReset, &length); length = BspMp3SetClockFLen; Write(hMp3, (void*)BspMp3SetClockF, &length); // Set volume length = BspMp3SetVolLen; Write(hMp3, (void*)BspMp3SetVolRange[volProgressCounter], &length); // To allow streaming data, set the decoder mode to Play Mode length = BspMp3PlayModeLen; Write(hMp3, (void*)BspMp3PlayMode, &length); // Set MP3 driver to data mode (subsequent writes will be sent to decoder's data interface) Ioctl(hMp3, PJDF_CTRL_MP3_SELECT_DATA, 0, 0); } // Volume Controller for the application void Mp3VolumeControl(HANDLE hMp3, VolumeCounter state) { INT32U length; if(state == VOLUP) { // Volume Range Index Sanity Check if(volProgressCounter == MP3_VOLUME_RANGE-1) return; ++volProgressCounter; } else { // Volume Range Index Sanity Check if(volProgressCounter == 0) return; --volProgressCounter; } // Place MP3 driver in command mode Ioctl(hMp3, PJDF_CTRL_MP3_SELECT_COMMAND, 0, 0); // Set volume length = BspMp3SetVolLen; Write(hMp3, (void*)BspMp3SetVolRange[volProgressCounter], &length); // To allow streaming data, set the decoder mode to Play Mode length = BspMp3PlayModeLen; Write(hMp3, (void*)BspMp3PlayMode, &length); // Set MP3 driver to data mode Ioctl(hMp3, PJDF_CTRL_MP3_SELECT_DATA, 0, 0); } // Mp3GetRegister // Gets a register value from the MP3 decoder. // hMp3: an open handle to the MP3 decoder // cmdInDataOut: on entry this buffer must contain the // command to get the desired register from the decoder. On exit // this buffer will be OVERWRITTEN by the data output by the decoder in // response to the command. Note: the buffer must not reside in readonly memory. // bufLen: the number of bytes in cmdInDataOut. // Returns: PJDF_ERR_NONE if no error otherwise an error code. PjdfErrCode Mp3GetRegister(HANDLE hMp3, INT8U *cmdInDataOut, INT32U bufLen) { PjdfErrCode retval; if (!PJDF_IS_VALID_HANDLE(hMp3)) while (1); // Place MP3 driver in command mode (subsequent writes will be sent to the decoder's command interface) Ioctl(hMp3, PJDF_CTRL_MP3_SELECT_COMMAND, 0, 0); retval = Read(hMp3, cmdInDataOut, &bufLen); return retval; } // Mp3FetchFileNames // Fetches a list of file names from the SD card // Note: This function needs to be called at the beginning of the MP3Task() // list - A string array where a list of songs will be stored // size - tracks size of array as it grows // maxSize - maximum allowable list //void Mp3FetchFileNames(char **list, int maxRow, int col, int *sizeOfList) void Mp3FetchFileNames() { // Endless loop to read files from the root directory and stream them File dir = SD.open("/"); char buf[13]; while (sizeOfList <= MAXLISTOFSONGS) { File entry = dir.openNextFile(); if (!entry) { break; } if (entry.isDirectory()) // skip directories { entry.close(); continue; } char *filename = entry.name(); for(int i = 0; i < SUPPFILENAMESIZE; ++i) listOfSongs[sizeOfList][i] = filename[i]; PrintWithBuf(buf, 13, listOfSongs[sizeOfList]); sizeOfList++; entry.close(); } dir.seek(0); // reset directory file to read again; } // Mp3StreamSDFile // Streams the given file from the SD card to the given MP3 decoder. // hMP3: an open handle to the MP3 decoder // pFilename: The file on the SD card to stream. void Mp3StreamCycle(HANDLE hMp3) { INT32U length; INT8U err = 0; Mp3StreamInit(hMp3); //char printBuf[PRINTBUFMAX]; dataFile = SD.open(listOfSongs[currSongFilePntr], O_READ); if (!dataFile) { //PrintWithBuf(printBuf, PRINTBUFMAX, "Error: could not open SD card file '%s'\n", listOfSongs[currSongFilePntr]); return; } // Initialize flags isStopSong = OS_FALSE; isFastForward = OS_FALSE; isRewind = OS_FALSE; isVolUp = OS_FALSE; isVolDown = OS_FALSE; progressCounter = 1; currPlayingSongFilePntr = currSongFilePntr; // this value will be used for increment/decrement song position . // A song data will be seen as ten parts and it will move accordingly iDataFileMovPos = dataFile.size()/10; iDataFileBegPos = dataFile.position(); iDataFileCurPos = iDataFileBegPos; while (dataFile.available()) { iBufPos = 0; //iDataFileCurPos = dataFile.position(); // if Paused stays in the loop and then picks when played again if(isPlaying) { while (dataFile.available() && iBufPos < MP3_DECODER_BUF_SIZE) { mp3Buf[iBufPos] = dataFile.read(); if((dataFile.position() - iDataFileBegPos) == (progressCounter * iDataFileMovPos)) { mp3Event = EVENT_STATUSBAR_INC; err = OSQPost(displayQMsg, (void*)&mp3Event); progressCounter++; } //delay(30); iBufPos++; } Write(hMp3, mp3Buf, &iBufPos); //OSTimeDly(5); } // new data file position iDataFileCurPos = dataFile.position(); // Fast Forward, Rewind, Vol+, Vol- and Stop functions should work if it // is Playing or Paused if(isFastForward) { //set new position iDataFileCurPos += iDataFileMovPos; //set the value in file datastructure dataFile.seek(iDataFileCurPos); //Send a Status Bar Update Event to display task mp3Event = EVENT_STATUSBAR_INC; err = OSQPost(displayQMsg, (void*)&mp3Event); progressCounter++; isFastForward = OS_FALSE; //OSFlagPost(mp3Flags, setFastForwardFlag, OS_FLAG_SET, &err); } if(isRewind) { iDataFileCurPos = (iDataFileMovPos >= iDataFileCurPos) ? iDataFileBegPos : (iDataFileCurPos - iDataFileMovPos); //set the value in file datastructure dataFile.seek(iDataFileCurPos); //Send a Status Bar Update Event to display task mp3Event = EVENT_STATUSBAR_DEC; err = OSQPost(displayQMsg, (void*)&mp3Event); progressCounter--; isRewind = OS_FALSE; } if(isVolUp) { Mp3VolumeControl(hMp3, VOLUP); isVolUp = OS_FALSE; } if(isVolDown) { Mp3VolumeControl(hMp3, VOLDOWN); isVolDown = OS_FALSE; } if(isStopSong) { isStopSong = OS_FALSE; break; } } currPlayingSongFilePntr = INT_MAX; isPlaying = OS_FALSE; dataFile.close(); mp3Event = EVENT_STOP_RELEASE; err = OSQPost(displayQMsg, (void*)&mp3Event); //OSFlagPost(mp3Flags, setPlayFlag | setPauseFlag, OS_FLAG_WAIT_SET_ALL, &err); Ioctl(hMp3, PJDF_CTRL_MP3_SELECT_COMMAND, 0, 0); length = BspMp3SoftResetLen; Write(hMp3, (void*)BspMp3SoftReset, &length); }
e75044657ae4544ef9b1e8430b2ce6ef15ebaa66
[ "Markdown", "C" ]
26
C
asahoo5/mp3-player
9c0c0a97362f949598c002719f86afb0784d2c3e
4e48b194bbfa51749b3791ca58abd926e6898add
refs/heads/master
<file_sep>var mysql = require('mysql'); function User(name,surname,dateOfBirth,city){ this.name = name; this.surname = surname; this.dateOfBirth = dateOfBirth; this.city = city; } var users=[]; users[0] = new User('Nermin','Demir',new Date(95,0,30),'Kakanj'); users[1] = new User('Amel','Sisic',new Date(95,1,8),'Kakanj'); users[2] = new User('Said','Sikira',new Date(95,2,19),'Kakanj'); var connection = mysql.createConnection({ host : 'localhost', user : 'user', password : '<PASSWORD>', database : 'baza' }); connection.connect(function (err) { if (err) return console.error(err); console.log('Connected'); }); connection.query('CREATE TABLE IF NOT EXISTS users (' + 'userId int NOT NULL AUTO_INCREMENT,' + 'name varchar(255),' + 'surname varchar(255),' + 'dateOfBirth datetime,' + 'city varchar(255),' + 'PRIMARY KEY(userId)' + ');',function (err){ if (err) return console.log(err); console.log('Table created'); }); function clearTable(conn,cb){ conn.query('DELETE FROM users;',function(err){ if (err) return console.error(err); console.log('Table cleared'); if (cb) cb(); }) } clearTable(connection); for (var i = 0; i < users.length; i++) { connection.query('INSERT INTO users (name,surname,dateOfBirth,city) VALUES("' + users[i].name + '","' + users[i].surname + '","' + users[i].dateOfBirth + '","' + users[i].city + '");' ,function(err){ if(err) return console.error(err); console.log('User saved'); }); }; connection.query('SELECT * FROM users;',function(err,result){ if (err) console.error(err); for (var i = 0; i < result.length; i++) { console.log(''); console.log(result[i].name + ' ' + result[i].surname); console.log(result[i].city); }; }); connection.end();
d2119d2b5a97f8389dea38e98825733725cb55b8
[ "JavaScript" ]
1
JavaScript
NerminD/DBApp_SQL
2493a627a499a23df33b38efde0d84a45368c57b
bff2af65edae84948ea86394d500ca1a501d964c
refs/heads/master
<repo_name>MaQuiNa1995/WebServiceSimple<file_sep>/src/main/java/es/maquina/webservice/repository/GenericRepositoryImpl.java package es.maquina.webservice.repository; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; /** * Clase usada para la implementacion de metodos comunes por todos los daos * empleando los objetos genericos * * @param <M> El tipo genérico */ public abstract class GenericRepositoryImpl<M> implements GenericRepository<M> { /** * El entity manager que será usado por los hijos para poder crear llamadas a * base de datos mas complejas que las que hay definidas en esta clase */ @PersistenceContext(name = "MaQuiNaPersistenceUnit") protected EntityManager entityManager; @Transactional @Override public M persist(M objetoPersistir) { entityManager.persist(objetoPersistir); return objetoPersistir; } @Transactional @Override public M merge(M objetoUpdatear) { entityManager.merge(objetoUpdatear); return objetoUpdatear; } } <file_sep>/src/main/java/es/maquina/webservice/controller/RegistroController.java package es.maquina.webservice.controller; import java.util.List; import es.maquina.webservice.dominio.Respuesta; import es.maquina.webservice.persistencia.dominio.Registro; /** * Clase encargada de la exposición de 2 endpoints * * <li><a href="http://localhost:8080/saludar?nombre=TuNombre">/saludar</a></li> * <li><a href="http:localhost:8080/verRegistrados">/verRegistrados</a></li> * * @author MaQuiNa1995 */ public interface RegistroController { /** * Creación de un Endpoint que te saluda si le pasas un parámetro * * @param String nombre que contiene el nombre de un usuario para saludarle * @return String que contiene la cadena de saludo */ Respuesta saludarUsuario(String nombre); /** * Creación de un Endpoint que devuelve la lista de usuarios registrados * * @return Mapa que contiene todos los usuarios registrados */ List<Registro> verRegistro(); }<file_sep>/README.md # WebServiceSimple para acceder a este web service: Sin Parámetros: http://localhost:8080/verRegistrados Con Parámetros: http://localhost:8080/saludar?nombre=TuNombre TuNombre = Pon tu nombre (Puedes poner espacios) <file_sep>/src/main/resources/application.properties logging.file=Log\\WebService.log<file_sep>/src/main/java/es/maquina/webservice/repository/GenericRepository.java package es.maquina.webservice.repository; /** * Implementacion generica de capa Repository * * @param <M> hace referencia al objeto generico que se va a usar en la clase */ public interface GenericRepository<M> { /** * Método usado para persistir un objeto pasado como parámetro * * @param objetoPersistir el objeto a persistir * @return la entidad persistida en base de datos */ M persist(M objetoPersistir); /** * Método usado para mergear un objeto pasado como parámetro * * @param objetoUpdatear el objeto a modificar * @return the M */ M merge(M objetoUpdatear); /** * Se obtiene la clase del Repository que se ha usado en el generico * * @return clase que usa el repository para la persistencia */ public abstract Class<M> getClassDeM(); } <file_sep>/src/main/java/es/maquina/webservice/repository/RegistroRepositoryImpl.java package es.maquina.webservice.repository; import java.util.List; import javax.persistence.TypedQuery; import org.springframework.stereotype.Repository; import es.maquina.webservice.persistencia.dominio.Registro; /** * Implementacion de la interacción con la tabla {@link #NOMBRE_TABLA} * * @author MaQuiNa1995 * */ @Repository("registroRepository") public class RegistroRepositoryImpl extends GenericRepositoryImpl<Registro> implements RegistroRepository { /** * Nombre de base de datos a la que acccede este repository */ public static final String NOMBRE_TABLA = "REGISTRO"; /** * Nombre de consulta para encontrar todas las entidades de la tabla */ public static final String FIND_ALL_QUERY = "Registro.findAll"; /** * Nombre de consulta para encontrar todas las entidades de la tabla que tengan * X nombre */ public static final String EXISTE_USUARIO = "Registro.findByNombrehola"; @Override public List<Registro> findAll() { TypedQuery<Registro> listadoRegistrados = entityManager.createNamedQuery(FIND_ALL_QUERY, Registro.class); return listadoRegistrados.getResultList(); } @Override public String findByUsuario(String nombreUsuario) { TypedQuery<String> listadoRegistrados = entityManager.createNamedQuery(EXISTE_USUARIO, String.class); listadoRegistrados.setParameter("nombreUsuario", nombreUsuario); String nombre = ""; List<String> lista = listadoRegistrados.getResultList(); if (lista.isEmpty() == Boolean.FALSE) { nombre = lista.get(0); } return nombre; } @Override public Class<Registro> getClassDeM() { return Registro.class; } }
269583d6f317020e53c1d7fa62ea695732a98e0f
[ "Markdown", "Java", "INI" ]
6
Java
MaQuiNa1995/WebServiceSimple
fa689882062b90a476993a5e60d89d34cd8dac28
d638becbf79a08d8c8fa43add420180ed5b7bde2
refs/heads/master
<file_sep>## Intro * Try to make this app in es6: https://scotch.io/tutorials/setup-a-react-environment-using-webpack-and-babel ## Ref * https://scotch.io/tutorials/setup-a-react-environment-using-webpack-and-babel * http://demo.tutorialzine.com/2015/04/first-webapp-react/ * http://tutorialzine.com/2015/04/first-webapp-react/ * https://github.com/MorganLKestner/react-location-search-app ## Install yarn install ## Run yarn start, then visit localhost:8080 <file_sep>import { TOGGLE_FAV_LOCATION, IS_FAV } from "./types"; import isAddressInFav from "../utils/isAddressInFav"; export function toggleFavLocation(currAddress, lat, lng) { // https://stackoverflow.com/questions/39257740/how-to-access-state-inside-redux-reducer return (dispatch, getState) => { // get currAddr and addrArr const { toggleFavLocation } = getState(); // is fav let isFav; // fav array let favArr = toggleFavLocation.favArr; // is it in state. let index = isAddressInFav(favArr, currAddress); let timenow = Date.now(); let newArr = []; if(index !== -1) { // found, remove isFav = false; // because any obj in javascript is ref // if change ref obj, individual data within state cannot be touched. // https://stackoverflow.com/questions/34582678/is-this-the-correct-way-to-delete-an-item-using-redux newArr = [ ...favArr.slice(0, index), ...favArr.slice(index + 1) ]; dispatch({ type: TOGGLE_FAV_LOCATION, currAddress: currAddress, favArr: newArr }); // store localStorage.favArr = JSON.stringify(newArr); } else { // not there, add isFav = true; // https://stackoverflow.com/questions/40911194/how-do-i-add-an-element-to-array-in-reducer-of-react-native-redux // currAddr and addr array newArr = [...favArr, { address: currAddress, timestamp: Date.now(), lat: lat, lng: lng }]; dispatch({ type: TOGGLE_FAV_LOCATION, currAddress: currAddress, favArr: newArr }); // store localStorage.favArr = JSON.stringify(newArr); } // the star dispatch({ type: IS_FAV, currAddress: currAddress, isFav: isFav }); }; } <file_sep>import React from 'react'; import Search from './Search'; import Map from "./Map"; import CurrentLocation from "./CurrentLocation"; import ListLocation from "./ListLocation"; export default class App extends React.Component { render() { return ( <div> <h1>My react map</h1> <Search /> <Map /> <CurrentLocation /> <ListLocation /> </div> ); } } <file_sep>import React from 'react'; import { connect } from "react-redux"; import { search } from "../actions/search"; class Search extends React.Component { constructor(props) { // super props super(props); this.state = { // need to match up the name of input currAddress: this.props.currAddress }; this.onSubmit = this.onSubmit.bind(this); this.onChange = this.onChange.bind(this); } onSubmit(e) { e.preventDefault(); // it seems props not changing // so use this.state.xxxx this.props.search(this.state.currAddress); } onChange(e) { this.setState({ [e.target.name]: e.target.value }); } render() { //console.log("-- search input box render --"); // value, this.state.search return ( <form id="geocoding_form" className="form-horizontal" onSubmit={this.onSubmit}> <div className="form-group"> <div className="col-xs-12 col-md-6 col-md-offset-3"> <div className="input-group"> <input name="currAddress" type="text" className="form-control" id="address" placeholder="Find a location..." value={this.state.currAddress} onChange={this.onChange} /> <span className="input-group-btn"> <span className="glyphicon glyphicon-search" aria-hidden="true"></span> </span> </div> </div> </div> </form> ); } } function mapStateToProps(state) { return { currAddress: state.search.currAddress }; } export default connect(mapStateToProps, { search })(Search); <file_sep>import React from 'react'; import { connect } from "react-redux"; import SingleLocation from "./SingleLocation"; class ListLocation extends React.Component { constructor(props) { super(props); //console.log("construcotr...."); } render() { console.log("--- ListLocation.js, render ---"); console.log(this.props.propFavArr); // yes index let locations = this.props.propFavArr.map((loc, index) => { var active = this.props.propCurrAddress == loc.address; // need to return // have to return in array return <SingleLocation key={index} address={loc.address} lat={loc.lat} lng={loc.lng} active={active} timestamp={loc.timestamp} /> }); return ( <div className="list-group col-xs-12 col-md-6 col-md-offset-3"> <span className="list-group-item active">Saved Locations</span> { locations } </div> ); } } function mapStateToProps(state) { //test //console.log("--- ListLocation.js, mapStateToProps ---"); //console.log(state.toggleFavLocation.favArr); return { // The way to think about is multiple components can share a single reducer propCurrAddress: state.search.currAddress, propFavArr: state.toggleFavLocation.favArr }; } export default connect(mapStateToProps, { })(ListLocation); <file_sep>export default function isAddressInFavLocalStorage(address) { let condi = false; let favArr = []; if(localStorage.favArr) { favArr = JSON.parse(localStorage.favArr); for(let i=0; i < favArr.length; i++) { if(favArr[i].address === address) { condi = true; break; } else { } } } else { } return condi; } <file_sep>export default function favAddressInLocalStorage() { let favArr = []; if(localStorage.favArr) { favArr = JSON.parse(localStorage.favArr); } else { favArr = []; } return favArr; } <file_sep>// the types.js has many constant. import { CLICK_SINGLE_LOCATION, SEARCH } from "./types"; export default function clickSingleLocation(currAddress, lat, lng) { // https://www.youtube.com/watch?v=1QI-UE3-0PU return (dispatch, getState) => { //test //console.log("---- clickSingleLocation ----"); //console.log(currAddress); //console.log(lat); //console.log(lng); // search, map, list location re-render // single location gets re-render as well, because the parent ListLocation gets re-render. dispatch({ type: SEARCH, currAddress: currAddress, lat: lat, lng: lng }); } } <file_sep>import React from 'react'; import { connect } from "react-redux"; class Map extends React.Component { constructor(props) { //console.log("---- constructor: map state to props, call before constructor ----"); // super props super(props); } componentDidMount() { //console.log("---- in componentDidMount ----"); // init var map = new GMaps({ el: '#map', lat: this.props.lat, lng: this.props.lng }); map.addMarker({ lat: this.props.lat, lng: this.props.lng }); } // component did update, won't be called when page reload. componentDidUpdate() { //test //console.log("---- in componentDidUpdate ----"); var map = new GMaps({ el: '#map', lat: this.props.lat, lng: this.props.lng }); map.addMarker({ lat: this.props.lat, lng: this.props.lng }); } render() { return ( <div className="map-holder"> <p>Loading...</p> <div id="map"></div> </div> ); } } function mapStateToProps(state) { //test // The first time global state is empty, because no one changes global state. // When someone does something on UI, global state changes. //console.log("---- mapStateToProps ----"); //console.log(state); // This will together with the props pass down // you cannot call state.lat. // because you need to use the reducer as identifier. // e.g. state.search.lat or state.toggleFavLocation.toggleFavLocation return { lat: state.search.lat, lng: state.search.lng }; } export default connect(mapStateToProps, { })(Map); <file_sep>import React from 'react'; import { connect } from "react-redux"; import moment from 'moment'; import clickSingleLocation from "../actions/clickSingleLocation"; class SingleLocation extends React.Component { constructor(props) { super(props); this.onClick = this.onClick.bind(this); } // don't call onClick() onClick(e) { e.preventDefault(); this.props.clickSingleLocation(this.props.address, this.props.lat, this.props.lng); } render() { let cn = "list-group-item"; if (this.props.active) { cn += " active-location"; } // render and return // render and return return( <a className={cn} onClick={ this.onClick }> {this.props.address} &nbsp;----&nbsp; <span className="createAt">{ moment(this.props.timestamp).fromNow() }</span> <span className="glyphicon glyphicon-menu-right"></span> </a> ) } } export default connect(null, { clickSingleLocation })(SingleLocation); <file_sep>import { CLICK_SINGLE_LOCATION } from "../actions/types"; const initState = { currAddress: "" }; // able to fire export default function clickSingleLocation(state = initState, action = {}) { switch(action.type) { case CLICK_SINGLE_LOCATION: console.log("--- clickSingleLocation, reducer ----"); return { currAddress: action.currAddress, } default: return state; } } <file_sep>import { IS_FAV } from "./types"; import isAddressInFav from "../utils/isAddressInFav"; export function isFav(currAddress) { // https://stackoverflow.com/questions/39257740/how-to-access-state-inside-redux-reducer return (dispatch, getState) => { const { toggleFavLocation } = getState(); // add or remove from local storage let favArr = toggleFavLocation.favArr; let isFav; let index = isAddressInFav(favArr, currAddress); if(index !== -1) { // found, remove isFav = false; } else { // not there, add isFav = true; } // https://github.com/reactjs/redux/issues/1676 //console.log("---- in isFav ----"); //console.log(isFav); dispatch({ type: IS_FAV, currAddress: currAddress, isFav: isFav }); }; }
cb8515512544ba8f37f4c3d6a168b5e49d6e7336
[ "Markdown", "JavaScript" ]
12
Markdown
tb-44/my_react_map
7bec8debb3593c271a3b2f6beaae1911e73a1de1
368abb4a71bab1aa415b3b5498bc7a4a63c06207
refs/heads/master
<repo_name>santhoshrajr/TwitterSentiment<file_sep>/Dockerfile FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base WORKDIR /app EXPOSE 80 FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build WORKDIR /src COPY ["TwitterSentiment.csproj", ""] RUN dotnet restore "./TwitterSentiment.csproj" COPY . . WORKDIR "/src/." RUN dotnet build "TwitterSentiment.csproj" -c Release -o /app/build FROM build AS publish RUN dotnet publish "TwitterSentiment.csproj" -c Release -o /app/publish FROM base AS final WORKDIR /app COPY --from=publish /app/publish . ENTRYPOINT ["dotnet", "TwitterSentiment.dll"]<file_sep>/Controllers/SentimentController.cs using System; using LinqToTwitter; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using TwitterSentimentML.Model; using System.IO; using CsvHelper; using System.Globalization; using ServiceStack; namespace TwitterSentiment.Controllers { [Microsoft.AspNetCore.Mvc.Route("api/[controller]")] [ApiController] public class SentimentController : ControllerBase { List<Status> Statuses = new List<Status>(); static readonly int MaxStatusCount = 100; private readonly ILogger<SentimentController> _logger; public SentimentController(ILogger<SentimentController> logger) { _logger = logger; } private async Task<ApplicationOnlyAuthorizer> SetAuthentication() { var auth = new ApplicationOnlyAuthorizer() { CredentialStore = new InMemoryCredentialStore() { ConsumerKey = "6XoTsN2mhm19tsEtfmDIJD9XZ", ConsumerSecret = "<KEY>" //OAuthToken = "<KEY>", //OAuthTokenSecret = "<KEY>" } }; await auth.AuthorizeAsync(); return auth; } [HttpGet("{searchTerm}")] public async Task<string> GetTweetsAsync(string searchTerm) { var auth = await SetAuthentication(); var context = new TwitterContext(auth); var fileName = "bernie"; if (searchTerm.ToLower().Contains("biden") || searchTerm.ToLower().Contains("joe")) { fileName = "biden"; searchTerm = "#joebiden OR #biden2020 OR #joe2020 OR #TeamJoe OR #JoeMentum"; } else { searchTerm = "#BernieSanders OR #Sanders2020 OR #NotMeUs OR #Bernie2020 OR #TeamBernie"; } Search(context, $"#californiaprimary AND {searchTerm}"); if(Statuses.Count >0) { var model = new ConsumeModel(); var outSentiment = new List<Sentiment>(); foreach (var item in Statuses) { var input = new ModelInput() { TextToAnalyze = item.FullText }; var response = model.Predict(input); outSentiment.Add(new Sentiment { CreatedAt = item.CreatedAt, Text = item.FullText, Location = item.User.Location, SentimentPct = response.Probability, ImageUrl = item.Entities.MediaEntities.Any() ? item.Entities.MediaEntities[0].MediaUrlHttps : "" }); } using (var writer = new StreamWriter($".\\{fileName}.csv")) using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture)) { csv.WriteRecords(outSentiment); } return JsonConvert.SerializeObject(outSentiment); } else { var records = new List<Sentiment>(); if (System.IO.File.Exists($".\\{fileName}.csv")) { using (var reader = new StreamReader($".\\{fileName}.csv")) using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) { records = csv.GetRecords<Sentiment>().ToList(); } } return JsonConvert.SerializeObject(records); } } private void Search(TwitterContext context, string searchTerm, ulong sinceId = 1, ulong maxId = ulong.MaxValue) { if(context.RateLimitRemaining >0 || context.RateLimitRemaining == -1) { try { var response = context.Search.Where(s => s.Type == SearchType.Search && s.Query == searchTerm && s.TweetMode == TweetMode.Extended && s.IncludeEntities == true && s.SinceID == sinceId && s.MaxID == maxId).ToList(); if (response[0].Statuses.Any()) { maxId = response[0].Statuses.Min(s => s.StatusID) - 1; Statuses.AddRange(response[0].Statuses.Where(x => !x.FullText.StartsWith("RT"))); if (response[0].Statuses.Any() && Statuses.Count() < MaxStatusCount) Search(context, searchTerm, sinceId, maxId); } } catch(Exception ex) { _logger.LogInformation("Limit reached"); } } } } }
5e271a9f3f352ef711b0af42c2c810d95f202cd9
[ "C#", "Dockerfile" ]
2
Dockerfile
santhoshrajr/TwitterSentiment
fb0e9fc3464decbdd7c2b6103c68adbf175660f6
b9e370a18254b627ed8db9a9da05b693840c9dda
refs/heads/master
<file_sep>package Dep; import java.util.Scanner; public class Persona implements Registro { static final Scanner entrada=new Scanner(System.in); protected String DNI; protected String nombre; protected String apellidos; protected String fechaNacimiento; protected String direccion; protected String ciudadProcedencia; Persona(){ } public Persona(String dNI, String nombre, String apellidos) { DNI = dNI; this.nombre = nombre; this.apellidos = apellidos; } public Persona(String dNI, String nombre, String apellidos, String fechaNacimiento, String direccion, String ciudadProcedencia) { DNI = dNI; this.nombre = nombre; this.apellidos = apellidos; this.fechaNacimiento = fechaNacimiento; this.direccion = direccion; this.ciudadProcedencia = ciudadProcedencia; } public String getDNI() { return DNI; } public void setDNI(String dNI) { DNI = dNI; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getApellidos() { return apellidos; } public void setApellidos(String apellidos) { this.apellidos = apellidos; } public String getFechaNacimiento() { return fechaNacimiento; } public void setFechaNacimiento(String fechaNacimiento) { this.fechaNacimiento = fechaNacimiento; } public String getDireccion() { return direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } public String getCiudadProcedencia() { return ciudadProcedencia; } public void setCiudadProcedencia(String ciudadProcedencia) { this.ciudadProcedencia = ciudadProcedencia; } @Override public String toString(){ return String.format("%s %s\nDNI: %s\nFecha Nacimiento: %s\n" + "Direccion: %s\nCiudad Procedencia: %s\n",getNombre(), getApellidos(), getDNI(),getFechaNacimiento(), this.getDireccion(),this.getCiudadProcedencia()); } @Override public void Registrar(){ setDNI(entrada.next()); setNombre(entrada.next()); setApellidos(entrada.next()); setFechaNacimiento(entrada.next()); setDireccion(entrada.next()); setCiudadProcedencia(entrada.next()); } } <file_sep>package GUI; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import Dep.Paciente; import javax.swing.JTextField; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JRadioButton; import javax.swing.ButtonGroup; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class regPaciente extends JFrame { private JPanel contentPane; private JTextField txt_DNI; private JTextField txt_Nombre; private JTextField txt_Apellidos; private JTextField txt_FechaNacimiento; private JTextField txt_direccion; private JTextField txt_Procedencia; private JTextField txt_Historia; private JTextField txt_gSanguineo; private JTextField txt_medicamentos; private ButtonGroup botones=new ButtonGroup(); /* public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { regPaciente frame = new regPaciente(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } */ public regPaciente() { setTitle("Registrar Paciente"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 550, 400); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); txt_DNI = new JTextField(); txt_DNI.setBounds(99, 51, 116, 22); contentPane.add(txt_DNI); txt_DNI.setColumns(10); JLabel label_Dni = new JLabel("DNI"); label_Dni.setBounds(7, 54, 56, 16); contentPane.add(label_Dni); txt_Nombre = new JTextField(); txt_Nombre.setBounds(99, 86, 116, 22); contentPane.add(txt_Nombre); txt_Nombre.setColumns(10); JLabel lblNombre = new JLabel("Nombre"); lblNombre.setBounds(7, 89, 56, 16); contentPane.add(lblNombre); txt_Apellidos = new JTextField(); txt_Apellidos.setBounds(99, 121, 116, 22); contentPane.add(txt_Apellidos); txt_Apellidos.setColumns(10); JLabel label_Apellidos = new JLabel("Apellidos"); label_Apellidos.setBounds(7, 124, 56, 16); contentPane.add(label_Apellidos); txt_FechaNacimiento = new JTextField(); txt_FechaNacimiento.setText(""); txt_FechaNacimiento.setBounds(99, 156, 116, 22); contentPane.add(txt_FechaNacimiento); txt_FechaNacimiento.setColumns(10); JLabel label_Cumple = new JLabel("Cumple"); label_Cumple.setBounds(7, 159, 56, 16); contentPane.add(label_Cumple); txt_direccion = new JTextField(); txt_direccion.setBounds(99, 191, 116, 22); contentPane.add(txt_direccion); txt_direccion.setColumns(10); JLabel label_Direccion = new JLabel("Direccion"); label_Direccion.setBounds(7, 194, 56, 16); contentPane.add(label_Direccion); txt_Procedencia = new JTextField(); txt_Procedencia.setBounds(99, 226, 116, 22); contentPane.add(txt_Procedencia); txt_Procedencia.setColumns(10); JLabel label_Ciudad = new JLabel("Ciudad"); label_Ciudad.setBounds(7, 229, 56, 16); contentPane.add(label_Ciudad); txt_Historia = new JTextField(); txt_Historia.setBounds(99, 261, 116, 22); contentPane.add(txt_Historia); txt_Historia.setColumns(10); JLabel label_Historia = new JLabel("N\u00B0Historia"); label_Historia.setBounds(7, 264, 75, 16); contentPane.add(label_Historia); final JRadioButton botonFemenino = new JRadioButton("Femenino"); botonFemenino.setBounds(397, 47, 127, 25); contentPane.add(botonFemenino); final JRadioButton botonMasculino = new JRadioButton("Masculino"); botonMasculino.setBounds(397, 101, 127, 25); contentPane.add(botonMasculino); botones.add(botonMasculino); botones.add(botonFemenino); JLabel labelSexo = new JLabel("Sexo"); labelSexo.setBounds(327, 75, 56, 16); contentPane.add(labelSexo); JLabel labelGrupoSanguineo = new JLabel("Grupo Sanguineo"); labelGrupoSanguineo.setBounds(267, 138, 116, 16); contentPane.add(labelGrupoSanguineo); txt_gSanguineo = new JTextField(); txt_gSanguineo.setBounds(384, 135, 116, 22); contentPane.add(txt_gSanguineo); txt_gSanguineo.setColumns(10); txt_medicamentos = new JTextField(); txt_medicamentos.setBounds(267, 203, 219, 22); contentPane.add(txt_medicamentos); txt_medicamentos.setColumns(10); JLabel labelMedicamentos = new JLabel("Al\u00E9rgico a medicamentos \u00BFCu\u00E1les?"); labelMedicamentos.setBounds(284, 176, 207, 16); contentPane.add(labelMedicamentos); JButton botonRegistrar = new JButton("Registrar"); botonRegistrar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String sexo; if(botonMasculino.isSelected()){ sexo="Masculino"; }else { if(botonFemenino.isSelected()){ sexo="Femenino"; } else{ sexo="No definido"; } } String DNI=txt_DNI.getText(); String Nombre=txt_Nombre.getText(); String Apellidos=txt_Apellidos.getText(); String Fecha=txt_FechaNacimiento.getText(); String Direccion=txt_direccion.getText(); String Ciudad=txt_Procedencia.getText(); String Historia=txt_Historia.getText(); String Grupo=txt_gSanguineo.getText(); String Medicamentos=txt_medicamentos.getText(); Paciente paciente=new Paciente(DNI,Nombre, Apellidos, Fecha, Direccion, Ciudad,Historia,sexo, Grupo, Medicamentos); } }); botonRegistrar.setBounds(267, 238, 97, 25); contentPane.add(botonRegistrar); final Primera regresar=new Primera(); JButton btnRegresarAlMen = new JButton("Regresar al men\u00FA principal"); btnRegresarAlMen.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { regresar.setVisible(true); dispose(); } }); btnRegresarAlMen.setBounds(267, 315, 237, 25); contentPane.add(btnRegresarAlMen); } } <file_sep>package Dep; public class Medico extends EmpleadoPlanilla { protected String Especialidad; protected String servicio; protected String numeroConsultorio; Medico(){} public Medico(String dNI, String nombre, String apellidos, String fechaNacimiento, String direccion, String ciudadProcedencia, String codEmpleado, String horasExtra, String fechaIngreso, String area, String cargo, String salarioMensual, String porcentajeAd, String especialidad, String servicio, String numeroConsultorio) { super(dNI, nombre, apellidos, fechaNacimiento, direccion, ciudadProcedencia, codEmpleado, horasExtra, fechaIngreso, area, cargo, salarioMensual, porcentajeAd); Especialidad = especialidad; this.servicio = servicio; this.numeroConsultorio = numeroConsultorio; } public String getEspecialidad() { return Especialidad; } public void setEspecialidad(String especialidad) { Especialidad = especialidad; } public String getServicio() { return servicio; } public void setServicio(String servicio) { this.servicio = servicio; } public String getNumeroConsultorio() { return numeroConsultorio; } public void setNumeroConsultorio(String numeroConsultorio) { this.numeroConsultorio = numeroConsultorio; } @Override public String toString(){ return String.format("Medico %s\nEspecialidad: %s\n" + "Servicio: %s\nNumero Consultorio: %s\n" ,super.toString(),this.getEspecialidad(), this.getServicio(),this.getNumeroConsultorio()); } @Override public void Registrar(){ System.out.println("Medico"); this.setEspecialidad(entrada.next()); super.Registrar(); this.setServicio(entrada.next()); this.setNumeroConsultorio(entrada.next()); } } <file_sep>package GUI; import javax.swing.JOptionPane; public class SuperPrincipal { public static void main(String[] args) { JOptionPane.showMessageDialog(null, "Bienvenido al Departamento de Registro"); Primera inicio=new Primera(); inicio.setVisible(true); } } <file_sep>package Dep; public class EmpleadoPlanilla extends Empleado{ protected String salarioMensual; protected String porcentajeAd; EmpleadoPlanilla(){} public EmpleadoPlanilla(String dNI, String nombre, String apellidos, String fechaNacimiento, String direccion, String ciudadProcedencia, String codEmpleado, String horasExtra, String fechaIngreso, String area, String cargo, String salarioMensual, String porcentajeAd) { super(dNI, nombre, apellidos, fechaNacimiento, direccion, ciudadProcedencia, codEmpleado, horasExtra, fechaIngreso, area, cargo); this.salarioMensual = salarioMensual; this.porcentajeAd = porcentajeAd; } public String getSalarioMensual() { return salarioMensual; } public void setSalarioMensual(String salarioMensual) { this.salarioMensual = salarioMensual; } public String getPorcentajeAd() { return porcentajeAd; } public void setPorcentajeAd(String porcentajeAd) { this.porcentajeAd = porcentajeAd; } @Override public String toString(){ return String.format("Empleado Planilla %s\nSalario Mensual: %s\n" + "Porcentaje adicional por hora extra: %s\n" ,super.toString(),this.getSalarioMensual(), this.getPorcentajeAd()); } @Override public void Registrar(){ System.out.println("Ingrese datos del Empleado Planilla..."); super.Registrar(); this.setSalarioMensual(entrada.next()); this.setPorcentajeAd(entrada.next()); } } <file_sep>package Dep; public class Cita extends Paciente { protected String fecha; protected String codOctor; protected String tipoServicio; Cita(){} public Cita(String dNI, String nombre, String apellidos, String numeroHistoria, String sexo, String fecha, String codOctor, String tipoServicio) { super(dNI, nombre, apellidos, numeroHistoria, sexo); this.fecha = fecha; this.codOctor = codOctor; this.tipoServicio = tipoServicio; } public String getFecha() { return fecha; } public void setFecha(String fecha) { this.fecha = fecha; } public String getCodOctor() { return codOctor; } public void setCodOctor(String codOctor) { this.codOctor = codOctor; } public String getTipoServicio() { return tipoServicio; } public void setTipoServicio(String tipoServicio) { this.tipoServicio = tipoServicio; } } <file_sep>package Dep; public class EmpleadoEventual extends Empleado{ protected String honorariosHora; protected String horasNormales;//normales mas extras protected String fechaFinal; EmpleadoEventual(){} public EmpleadoEventual(String dNI, String nombre, String apellidos, String fechaNacimiento, String direccion, String ciudadProcedencia, String codEmpleado, String horasExtra, String fechaIngreso, String area, String cargo, String honorariosHora, String horasNormales, String fechaFinal) { super(dNI, nombre, apellidos, fechaNacimiento, direccion, ciudadProcedencia, codEmpleado, horasExtra, fechaIngreso, area, cargo); this.honorariosHora = honorariosHora; this.horasNormales = horasNormales; this.fechaFinal = fechaFinal; } public int obtenerHorasTotales(){ return 0;//obtenerHorasNormales()+super.obtenerHorasExtra(); } public String getHonorariosHora() { return honorariosHora; } public void setHonorariosHora(String honorariosHora) { this.honorariosHora = honorariosHora; } public String getHorasNormales() { return horasNormales; } public void setHorasNormales(String horasNormales) { this.horasNormales = horasNormales; } public String getFechaFinal() { return fechaFinal; } public void setFechaFinal(String fechaFinal) { this.fechaFinal = fechaFinal; } @Override public String toString(){ return String.format("Empleado eventual: %s\n Honorario: %s\n" + "Horas Totales: %s\n Fecha Final: %s\n" ,super.toString(),this.getHonorariosHora(), this.obtenerHorasTotales(),this.getFechaFinal()); } @Override public void Registrar(){ System.out.println("Ingrese datos del Empleado Eventual..."); super.Registrar(); this.setHonorariosHora(entrada.next()); this.setHorasNormales(entrada.next()); this.setFechaFinal(entrada.next()); } }
957f97abd00be1c0c08d0383ba87402051bbd25a
[ "Java" ]
7
Java
ricardopajarito/Departamento-programacion2
46d9396f58a38cc8c26e9ef15163c961abf891e1
62b64186ddb4fd5e83479d4b379ad7ae53524cb3
refs/heads/master
<repo_name>crunchcubes/angular-admin<file_sep>/src/app/modules/default/no-auth-guard.service.ts //https://scotch.io/tutorials/protecting-angular-v2-routes-with-canactivatecanactivatechild-guards import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router'; import { Observable } from 'rxjs'; import { UserService } from '../../core'; @Injectable() export class NoAuthGuard implements CanActivate { isLoggedIn:boolean = true; constructor( private router: Router, private userService: UserService ) {} canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean { return true; } canActivateChild( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean { return true; } } <file_sep>/src/app/modules/project/project.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { FormControl, ReactiveFormsModule } from '@angular/forms'; import {BaseComponent} from '../../core/base.component'; import {UserService, ProjectService} from '../../core'; //import { DataTable, DataTableResource } from 'angular6-data-table'; import { User, Project } from '../../core'; @Component({ selector: 'app-project', templateUrl: './project.component.html' }) export class ProjectComponent extends BaseComponent { private projects: [Project]; constructor ( private userService: UserService, private projectService: ProjectService, private router: Router ) {super()} ngOnInit() { this.projectService.getAll() .subscribe(projects => { this.projects = projects; }); } } <file_sep>/src/app/modules/auth/no-auth-guard.service.ts //https://scotch.io/tutorials/protecting-angular-v2-routes-with-canactivatecanactivatechild-guards import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router'; import { Observable, of } from 'rxjs'; import { UserService } from '../../core'; @Injectable() export class NoAuthGuard implements CanActivate { isLoggedIn:boolean = true; constructor( private router: Router, private userService: UserService ) {} /*canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<boolean> { //console.log(this.userService.isAuthenticated); return this.userService.isAuthenticated.pipe(take(1), map(isAuth => !isAuth)); }*/ /*canActivate(next:ActivatedRouteSnapshot, state:RouterStateSnapshot) { return this.userService.isLoggedIn().map(e => { if (e) { return true; } }).catch(() => { this.router.navigate(['/login']); return Observable.of(false); }); } */ /* [::KEEP::] canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean { return true; }*/ canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean { return true; } canActivateChild( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean { return true; } } <file_sep>/src/app/core/services/index.ts export * from './api.service'; export * from './auth-guard.service'; export * from './no-auth-guard.service'; export * from './jwt.service'; export * from './task.service'; export * from './project.service'; export * from './user.service'; export * from './team.service'; export * from './script.service'; export * from './utility.service'; export * from './dependency-resolver.service'; <file_sep>/src/app/core/services/utility.service.ts import { Injectable, Output, EventEmitter } from '@angular/core'; @Injectable() export class UtilityService { private title:string; constructor () {} @Output() onTitleChanged: EventEmitter<any> = new EventEmitter(); setNavigation(title: string, items:any[]) { this.title = title; this.onTitleChanged.emit({sender: this, value: {title: title, items: items}}); } getTitle(): string{ return this.title; } }<file_sep>/src/app/shared/index.ts //export * from './article-helpers'; //export * from './buttons'; //export * from './layout'; //export * from './list-errors.component'; export * from './shared.module'; export * from './content-header/content-header.component'; export * from './sidebar/sidebar.component'; export * from './message/message.component'; export * from './notification/notification.component'; export * from './user-menu/user-menu.component'; export * from './navbar/navbar.component'; //export * from './show-authed.directive'; <file_sep>/src/app/modules/task/task.module.ts import { ModuleWithProviders, NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; //import {FormsModule, ReactiveFormsModule} from '@angular/forms'; import { TaskComponent } from './task.component'; import { TaskAuthResolver } from './task-auth-resolver.service'; import { SharedModule } from '../../shared'; import { TaskRoutingModule } from './task-routing.module'; import { CommonModule } from "@angular/common"; import { TaskNewComponent } from './task-new/task-new.component'; import { TaskEditComponent } from './task-edit/task-edit.component'; //import { NoAuthGuard } from './no-auth-guard.service'; @NgModule({ imports: [ CommonModule, SharedModule, TaskRoutingModule, /*ReactiveFormsModule, FormsModule*/ ], declarations: [ TaskComponent, TaskNewComponent, TaskEditComponent ], providers: [ //TaskAuthResolver, //NoAuthGuard ] }) export class TaskModule {} <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { CoreModule } from './core/core.module'; import { AppComponent } from './app.component'; //import { routing } from "./app.routing"; [::KEEP::] - Example of routing with component only //import { DashboardComponent } from './modules/dashboard/dashboard.component'; import { TaskModule } from './modules/task/task.module'; import { DashboardModule } from './modules/dashboard/dashboard.module'; import { AuthModule } from './modules/auth/auth.module'; import { SidebarComponent, NavbarComponent, NotificationComponent, MessageComponent, UserMenuComponent, ContentHeaderComponent, SharedModule } from './shared'; import { AppRoutingModule } from './app-routing.module'; import {UtilityService } from './core'; import {FormsModule, ReactiveFormsModule} from '@angular/forms'; @NgModule({ declarations: [ AppComponent, NavbarComponent, SidebarComponent, MessageComponent, NotificationComponent, UserMenuComponent, ContentHeaderComponent, NavbarComponent, UserMenuComponent ], imports: [ BrowserModule, FormsModule, CoreModule, SharedModule, //AuthModule, //TaskModule, //DashboardModule, ReactiveFormsModule, AppRoutingModule ], providers: [UtilityService], bootstrap: [ AppComponent, SidebarComponent, NavbarComponent, ContentHeaderComponent, MessageComponent, NotificationComponent, UserMenuComponent ] }) export class AppModule {}<file_sep>/src/app/modules/team/team.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { FormControl, ReactiveFormsModule } from '@angular/forms'; import {BaseComponent} from '../../core/base.component'; import {UserService, TeamService} from '../../core'; //import { DataTable, DataTableResource } from 'angular6-data-table'; import { Input } from '@angular/core'; import { Team } from '../../core'; import {NgbModal,NgbModalRef, ModalDismissReasons, NgbModalOptions, NgbModalConfig } from '@ng-bootstrap/ng-bootstrap'; import {NgbdModalContent } from './modal-content.component'; @Component({ selector: 'app-team', templateUrl: './team.component.html', providers: [NgbModalConfig, NgbModal] }) export class TeamComponent extends BaseComponent { private teams: [Team]; private closeResult:string; private modalRef: NgbModalRef; constructor ( private userService: UserService, private teamService: TeamService, private router: Router, private modalService: NgbModal, private config: NgbModalConfig ) { super(); config.backdrop = 'static'; config.keyboard = false; } open(content) { this.modalRef = this.modalService.open(NgbdModalContent); this.modalRef.componentInstance.name = 'World'; this.modalRef.result.then((result) => { this.closeResult = `Closed with: ${result}`; }, (reason) => { this.closeResult = `Dismissed ${this.getDismissReason(reason)}`; }); } private getDismissReason(reason: any): string { console.log('>>>> getDismissReason'); if (reason === ModalDismissReasons.ESC) { return 'by pressing ESC'; } else if (reason === ModalDismissReasons.BACKDROP_CLICK) { return 'by clicking on a backdrop'; } else { return `with: ${reason}`; } } ngOnInit() { this.setNavigation( 'Teams', [{name: 'Team', link: '/team', type : 'active'}] ); } } //https://ng-bootstrap.github.io/#/components/modal/examples //https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/ //https://stackblitz.com/angular/xxlxmbednyv?file=app%2Fmodal-component.ts<file_sep>/src/app/core/services/task.service.ts import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { ApiService } from './api.service'; import { map } from 'rxjs/operators'; import { Task } from '../models'; @Injectable() export class TaskService { constructor ( private apiService: ApiService ) {} getAll(): Observable<[Task]> { return this.apiService.get('/task/get-all') .pipe(map((data: {tasks: [Task]}) => data.tasks)); } get(taskId): Observable<Task> { return this.apiService.get(`/task/${taskId}`) .pipe(map((data: {task: Task}) => data.task)); } add(payload): Observable<Task> { return this.apiService .post( '/task/create', { task: { body: payload } } ).pipe(map(response => response)); } update(payload): Observable<Task> { return this.apiService .post( '/task/update', { task: { body: payload } } ).pipe(map(response => response)); } } <file_sep>/python-server/server.py #!/usr/bin/python from http.server import BaseHTTPRequestHandler,HTTPServer from os import curdir, sep import os import pathlib PORT_NUMBER = 8080 HOST_NAME = '0.0.0.0' #This class will handles any incoming request from #the browser class HTTPHandler(BaseHTTPRequestHandler): def do_OPTIONS(self): self.send_response(200, "ok") self.send_header('Access-Control-Allow-Origin', '*') self.send_header('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS,POST,PUT') self.send_header("Access-Control-Allow-Headers", "X-Requested-With") self.send_header("Access-Control-Allow-Headers", "Content-Type") self.send_header('Access-Control-Allow-Credentials', 'true') self.send_header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization"); #self.send_header('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers') self.end_headers() def do_POST(self): self.do_GET() def handle_http(self, status_code, path): self.send_response(status_code) self.send_header('Content-type', 'text/html') self.end_headers() content = ''' <html><head><title>Python Server</title></head> <body><p>The requested file could not be found</p> <p>Path: {}</p> </body></html> '''.format(path) return bytes(content, 'UTF-8') #Handler for the GET requests def do_GET(self): if self.path=="/": self.path="/index.html" try: #Check the file extension required and #set the right mime type mimetype = '' ext = pathlib.Path(self.path).suffix types = { '.html': 'text/html', '.jpg': 'image/jpg', '.png': 'image/png', '.js': 'application/javascript', '.css': 'text/css', '.json': 'application/json', '': 'application/json' } if ext in types: mimetype = types[ext] print(mimetype); #Open the static file requested and send it f = open(curdir + sep + self.path, 'rb') #self.send_response(200) self.send_response(200, "ok") self.send_header('Access-Control-Allow-Origin', '*') self.send_header('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS,POST,PUT') self.send_header("Access-Control-Allow-Headers", "X-Requested-With") self.send_header("Access-Control-Allow-Headers", "Content-Type") # self.end_headers() self.send_header('Content-type',mimetype) self.end_headers() self.wfile.write(f.read()) f.close() else: #return bytes('Regregu', 'UTF-8') response = self.handle_http(400, self.path) self.wfile.write(response) return except IOError: self.send_error(404,'File Not Found: %s' % self.path) try: #Create a web server and define the handler to manage the #incoming request server = HTTPServer((HOST_NAME, PORT_NUMBER), HTTPHandler) print ('Started httpserver on port ' , PORT_NUMBER) #Wait forever for incoming htto requests server.serve_forever() except KeyboardInterrupt: print ('^C received, shutting down the web server') server.socket.close()<file_sep>/src/app/modules/profile/profile.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { FormControl, ReactiveFormsModule } from '@angular/forms'; import {BaseComponent} from '../../core/base.component'; import {UserService} from '../../core'; //import { DataTable, DataTableResource } from 'angular-6-data-table'; import { Profile } from '../../core'; @Component({ selector: 'app-profile', templateUrl: './profile.component.html' }) export class ProfileComponent extends BaseComponent { private teams: [Profile]; constructor ( private userService: UserService, private router: Router ) {super()} ngOnInit() { this.setNavigation( 'Profiles', [{name: 'Profile', link: '/team', type : 'active'}] ); } } <file_sep>/src/app/shared/task-schedule/task-schedule.component.ts import { Component, OnInit } from '@angular/core'; import { initializeCalendar } from '../../../assets/external-js/functions'; import {ScriptService} from '../../core/services/script.service' @Component({ selector: 'app-task-schedule', templateUrl: './task-schedule.component.html' }) export class TaskScheduleComponent implements OnInit { constructor(private script: ScriptService) { } ngOnInit() { this.script.load(/*'momentjs', */'fullcalendar', ).then(data => { console.log('script loaded ', data); initializeCalendar(); }).catch(error => console.log(error)); } } <file_sep>/src/app/modules/default/default.module.ts import { ModuleWithProviders, NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { DefaultComponent } from './default.component'; import { NoAuthGuard } from './no-auth-guard.service'; import { SharedModule } from '../../shared'; import { DefaultRoutingModule } from './default-routing.module'; @NgModule({ imports: [ SharedModule, DefaultRoutingModule ], declarations: [ DefaultComponent ], providers: [ NoAuthGuard ] }) export class DefaultModule {} <file_sep>/src/app/core/models/index.ts export * from './task.model'; export * from './errors.model'; export * from './profile.model'; export * from './user.model'; export * from './project.model'; export * from './team.model'; <file_sep>/src/app/shared/content-header/content-header.component.ts import { Component, HostBinding, OnInit } from '@angular/core'; import {DependencyResolverService} from '../../core'; @Component({ selector: 'app-content-header', templateUrl: './content-header.component.html' }) export class ContentHeaderComponent implements OnInit { title:string; items:any; constructor() { } ngOnInit() { this.title = ''; this.items = []; console.log('ContentHeaderComponent>>> '); DependencyResolverService.getUtilityService().onTitleChanged.subscribe(args => { this.title = args.value.title; this.items = args.value.items; }); } } <file_sep>/src/app/modules/user/user.module.ts import { ModuleWithProviders, NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { CommonModule } from "@angular/common"; import { UserComponent } from './user.component'; import { UserAuthResolver } from './user-auth-resolver.service'; import { SharedModule } from '../../shared'; import { UserRoutingModule } from './user-routing.module'; import { DataTableModule } from 'angular-6-datatable'; import { MatButtonModule, MatFormFieldModule, MatInputModule, MatRippleModule, MatTableModule } from '@angular/material'; const modules = [ MatButtonModule, MatFormFieldModule, MatInputModule, MatRippleModule, MatTableModule ]; @NgModule({ imports: [ CommonModule, SharedModule, UserRoutingModule, modules ], declarations: [ UserComponent ], providers: [ //NoAuthGuard ] }) export class UserModule {} <file_sep>/src/app/modules/task/task-new/task-new.component.ts import { Component, OnInit } from '@angular/core'; import { FormControl, ReactiveFormsModule } from '@angular/forms'; import {Router} from "@angular/router"; import {ProjectService, TaskService } from '../../../core'; import { Project } from '../../../core'; import {BaseComponent} from '../../../core/base.component'; import { initializeFormElements } from '../../../../assets/external-js/functions'; @Component({ selector: 'app-task-new', templateUrl: './task-new.component.html', styleUrls: ['./task-new.component.css'] }) export class TaskNewComponent extends BaseComponent { private taskNameControl: FormControl; private projects: [Project]; newTask:any; constructor ( private projectService: ProjectService, private taskService: TaskService, private router: Router, ) { super(); this.taskNameControl = new FormControl(); } ngOnInit() { super.ngOnInit(); this.setNavigation( 'New Task', [ {name: 'Task', link: '/task'}, {name: 'New Task', link: '/task-new', type : 'active'} ] ); this.projectService.getAll() .subscribe(projects => { this.projects = projects; initializeFormElements(); }); } addTask() { const taskName = this.taskNameControl.value; this.newTask = { projectId:0, taskName:"New Task", taskDescription:"Task Description" }; this.taskService.add(this.newTask) .subscribe(response => { console.log(response); if(response){ this.router.navigate(['task']); } }); } } <file_sep>/src/app/core/services/team.service.ts import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { ApiService } from './api.service'; import { Team } from '../models'; @Injectable() export class TeamService { constructor ( private apiService: ApiService ) {} getAll(): Observable<[Team]> { return this.apiService.get('/team/get-all') .pipe(map((data: {teams: [Team]}) => data.teams)); } get(teamId): Observable<Team> { return this.apiService.get(`/team/${teamId}`) .pipe(map((data: {team: Team}) => data.team)); } add(payload): Observable<Team> { return this.apiService .post( '/team/create', { team: { body: payload } } ).pipe(map(response => response)); } update(payload): Observable<Team> { return this.apiService .post( '/team/update', { team: { body: payload } } ).pipe(map(response => response)); } } <file_sep>/src/app/core/services/project.service.ts import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { ApiService } from './api.service'; import { map } from 'rxjs/operators'; import { Project } from '../models'; @Injectable() export class ProjectService { constructor ( private apiService: ApiService ) {} getAll(): Observable<[Project]> { return this.apiService.get('/project/get-projects') .pipe(map((data: {projects: [Project]}) => data.projects)); } } <file_sep>/src/app/core/models/bread-crumb.model.ts export interface BreadCrumb { items: any[]; }<file_sep>/src/app/app.routing.ts import { Routes, RouterModule } from "@angular/router"; const routes: Routes = [ //{ path: "", redirectTo: "home", pathMatch: "full" }, //{ path: "task", component: TaskComponent }, //{ path: "**", component: DashboardComponent } ] export const routing = RouterModule.forRoot(routes); <file_sep>/src/app/modules/dashboard/dashboard.component.ts import { Component, OnInit } from '@angular/core'; import {BaseComponent} from '../../core/base.component'; @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html' }) export class DashboardComponent extends BaseComponent { constructor() { super() } ngOnInit() { super.ngOnInit(); this.setNavigation( 'Dashboard', [{name: 'Dashboard', link: '/', type : 'active'}] ); } } //https://stackoverflow.com/questions/34489916/how-to-load-external-scripts-dynamically-in-angular <file_sep>/src/app/modules/task/task-edit/task-edit.component.ts import { Component, OnInit } from '@angular/core'; import { FormControl, ReactiveFormsModule } from '@angular/forms'; import {Router, ActivatedRoute} from "@angular/router"; import {ProjectService, TaskService } from '../../../core'; import { Task, Project } from '../../../core'; import {BaseComponent} from '../../../core/base.component'; import { initializeFormElements } from '../../../../assets/external-js/functions'; @Component({ selector: 'app-task-edit', templateUrl: './task-edit.component.html' }) export class TaskEditComponent extends BaseComponent { private taskNameControl: FormControl; private projects: [Project]; task: Task = {} as Task; //newTask:any; title:string; constructor ( private projectService: ProjectService, private taskService: TaskService, private router: Router, private route: ActivatedRoute ) { super(); this.taskNameControl = new FormControl(); } ngOnInit() { super.ngOnInit(); var taskId: string = ''; this.setNavigation( 'Edit Task', [ {name: 'Task', link: '/task'}, {name: 'Edit Task', link: '/task-new', type : 'active'} ] ); this.projectService.getAll() .subscribe(projects => { this.projects = projects; //initializeFormElements(); }); this.route.paramMap.subscribe(params => { let id = params.get('id') console.log(id); this.taskService.get(id) .subscribe(task => { this.task = task; }); }) } private updateTask() { //[::KEEP::]// const taskName = this.taskNameControl.value; var newTask:any = { taskId: null, projectId: this.task.projectId, taskName: this.task.taskName, taskDescription: this.task.taskDescription }; this.taskService.update(newTask) .subscribe(response => { if(response){ this.router.navigate(['task']); } }); console.log(newTask); } } <file_sep>/src/app/modules/default/default.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import {UserService } from '../../core'; @Component({ selector: 'app-default', templateUrl: './default.component.html' }) export class DefaultComponent implements OnInit { constructor( private route: ActivatedRoute, private router: Router, private userService: UserService, ) { } ngOnInit() { if (this.userService.isLoggedIn()) { this.router.navigate(['/dashboard']); }else{ this.router.navigate(['auth/login']); } } } <file_sep>/src/app/modules/task/task.component.ts //Reference: https://medium.com/dailyjs/3-ways-to-communicate-between-angular-components-a1e3f3304ecb import { Component} from '@angular/core'; //import 'rxjs/add/operator/map'; import {TaskService} from '../../core'; import {BaseComponent} from '../../core/base.component'; import { Task } from '../../core'; import { Router } from '@angular/router'; @Component({ selector: 'app-task', templateUrl: './task.component.html', styleUrls: ['./task.component.css'] }) export class TaskComponent extends BaseComponent { tasks: [Task]; constructor(private taskService: TaskService, private router: Router) {super()} ngOnInit() { super.ngOnInit(); this.setNavigation( 'My Tasks', [{name: 'Task', link: '/task', type : 'active'}] ); this.taskService.getAll() .subscribe(tasks => { this.tasks = tasks; this.loaded = true; console.log(tasks) }); } selectTask(taskId:string){ this.router.navigate([`/task/edit/${taskId}`, {}], { skipLocationChange: false }); } } <file_sep>/src/app/modules/user/user.component.ts import { Component, ViewChild, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { FormControl, ReactiveFormsModule } from '@angular/forms'; import {BaseComponent} from '../../core/base.component'; import {UserService, ProjectService} from '../../core'; //import { DataTable, DataTableResource } from 'angular6-data-table'; //import { DataTableResourceCustom } from './data-table-resources-custom'; import {MatPaginator, MatSort, MatTableDataSource} from '@angular/material'; import { User, Project } from '../../core'; export interface UserData { id: string; name: string; progress: string; color: string; } @Component({ selector: 'app-default', templateUrl: './user.component.html' }) export class UserComponent extends BaseComponent { private users:any = []; private itemCount = 0; private limit = 0; private itemResource:any; displayedColumns = ['id', 'name', 'progress', 'color']; dataSource: MatTableDataSource<UserData>; @ViewChild(MatPaginator) paginator: MatPaginator; @ViewChild(MatSort) sort: MatSort; constructor ( private userService: UserService, private projectService: ProjectService, private router: Router ) { super(); const users: UserData[] = []; for (let i = 1; i <= 100; i++) { users.push(createNewUser(i)); } // Assign the data to the data source for the table to render this.dataSource = new MatTableDataSource(users); } ngOnInit() { // this.itemResource.count().then(count => this.itemCount = count); this.userService.getUsers() .subscribe(users => { this.users = users; this.loaded = true; console.log(this.users); //this.itemResource = new DataTableResourceCustom(this.users); this.itemResource.count().then(count => {this.itemCount = count, this.limit = 10}); }); } reloadItems(params) { if(this.itemResource != null){ this.itemResource.query(params).then(items => this.users = items); } } /************************************************************************** */ /** * Set the paginator and sort after the view init since this component will * be able to query its view for the initialized paginator and sort. */ ngAfterViewInit() { this.dataSource.paginator = this.paginator; this.dataSource.sort = this.sort; } applyFilter(filterValue: string) { filterValue = filterValue.trim(); // Remove whitespace filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches this.dataSource.filter = filterValue; } } /** Builds and returns a new User. */ function createNewUser(id: number): UserData { const name = NAMES[Math.round(Math.random() * (NAMES.length - 1))] + ' ' + NAMES[Math.round(Math.random() * (NAMES.length - 1))].charAt(0) + '.'; return { id: id.toString(), name: name, progress: Math.round(Math.random() * 100).toString(), color: COLORS[Math.round(Math.random() * (COLORS.length - 1))] }; } /** Constants used to fill up our data base. */ const COLORS = ['maroon', 'red', 'orange', 'yellow', 'olive', 'green', 'purple', 'fuchsia', 'lime', 'teal', 'aqua', 'blue', 'navy', 'black', 'gray']; const NAMES = ['Maia', 'Asher', 'Olivia', 'Atticus', 'Amelia', 'Jack', 'Charlotte', 'Theodore', 'Isla', 'Oliver', 'Isabella', 'Jasper', 'Cora', 'Levi', 'Violet', 'Arthur', 'Mia', 'Thomas', 'Elizabeth']; //https://stackblitz.com/angular/dnbermjydavk?file=app%2Ftable-overview-example.ts <file_sep>/src/app/core/services/dependency-resolver.service.ts //https://codecraft.tv/courses/angular/dependency-injection-and-providers/providers/ //https://codecraft.tv/courses/angular/dependency-injection-and-providers/injectors/ import { Injectable, Injector } from '@angular/core'; import { UtilityService } from './utility.service'; @Injectable() export class DependencyResolverService { private static injector:Injector = Injector.create([ { provide: UtilityService, useClass: UtilityService, deps: [] } ]) constructor() {} public static getUtilityService():UtilityService { return DependencyResolverService.injector.get(UtilityService); } }<file_sep>/src/app/core/models/task.model.ts export interface Task { taskId: string; taskName: string; taskDescription: string; projectId: string; projectName: string; } <file_sep>/src/app/modules/team/team.module.ts import { ModuleWithProviders, NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { CommonModule } from "@angular/common"; import { TeamComponent } from './team.component'; import { SharedModule } from '../../shared'; import { TeamRoutingModule } from './team-routing.module'; import {NgbModule} from '@ng-bootstrap/ng-bootstrap'; import {NgbModal, ModalDismissReasons, NgbActiveModal, NgbModalConfig} from '@ng-bootstrap/ng-bootstrap'; import {NgbdModalContent } from './modal-content.component'; @NgModule({ imports: [ CommonModule, SharedModule, TeamRoutingModule, NgbModule.forRoot() ], declarations: [ TeamComponent, NgbdModalContent, ], providers: [ NgbActiveModal, NgbModalConfig, NgbModal ], entryComponents: [NgbdModalContent] }) export class TeamModule {} <file_sep>/src/app/app-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule, PreloadAllModules } from '@angular/router'; import { DefaultModule } from './modules/default/default.module'; import { AuthModule } from './modules/auth/auth.module'; import { TaskModule } from './modules/task/task.module'; import { DashboardModule } from './modules/dashboard/dashboard.module'; import { NotFoundModule } from './modules/not-found/not-found.module'; import { UserModule } from './modules/user/user.module'; import { ProjectModule } from './modules/project/project.module'; import { TeamModule } from './modules/team/team.module'; import { ProfileModule } from './modules/profile/profile.module'; const routes: Routes = [ { path: '', loadChildren: () => DefaultModule, }, { path: 'dashboard', loadChildren: () => DashboardModule }, { path: 'auth', loadChildren: () => AuthModule, }, { path: 'dashboard', loadChildren: () => DashboardModule }, { path: 'task', loadChildren: () => TaskModule, }, { path: 'user', loadChildren: () => UserModule, }, { path: 'project', loadChildren: () => ProjectModule, }, { path: 'team', loadChildren: () => TeamModule, }, { path: 'profile', loadChildren: () => ProfileModule, }, { path: '**', loadChildren: () => NotFoundModule, } ]; @NgModule({ imports: [RouterModule.forRoot(routes, { // preload all modules; preloadingStrategy: PreloadAllModules })], exports: [RouterModule] }) export class AppRoutingModule {}<file_sep>/src/assets/external-js/functions.d.ts export declare function initializeCalendar(); export declare function initializeFormElements();<file_sep>/python-server/user/login { "user": { "iss": "scotch.io", "exp": 1300819380, "name": "<NAME>", "admin": true, "token":"<KEY>" } }<file_sep>/src/app/core/base.component.ts import {OnInit } from '@angular/core'; import {DependencyResolverService} from '../core'; export class BaseComponent implements OnInit { protected loaded: boolean; constructor() { } setNavigation(title:string, items:any[]){ DependencyResolverService.getUtilityService().setNavigation(title, this.getBreadCrumb(items)); } getTitle():string{ return DependencyResolverService.getUtilityService().getTitle(); } getBreadCrumb(items:any[]){ let mergeItems = [{name: 'Home', link: '', type : ''}].concat(items); return mergeItems; } ngOnInit() { } }
431cfbb635ff195e326f2d919c05f59fcbf6bac3
[ "Python", "TypeScript", "Shell" ]
34
TypeScript
crunchcubes/angular-admin
670657f1c7390ecbaaffccb3baa074a159a26c28
c1b3ff7a0831ec804a6823abe4158556192982d0
refs/heads/master
<file_sep>import { SudokuCellPosition } from "./SudokuCellPosition"; describe( 'SudokuCellPosition', () => { describe( '.row', () => { it( 'returns 0 for too low out of range values', () => { let cellPosition = new SudokuCellPosition( 0 ); expect( cellPosition.row ).toBe( 0 ); }); it( 'returns 0 for too high out of range values', () => { let cellPosition = new SudokuCellPosition( 82 ); expect( cellPosition.row ).toBe( 0 ); }); it( 'returns 1 for cellIndex 1', () => { let cellPosition = new SudokuCellPosition( 1 ); expect( cellPosition.row ).toBe( 1 ); }); it( 'returns 2 for cellIndex 10', () => { let cellPosition = new SudokuCellPosition( 10 ); expect( cellPosition.row ).toBe( 2 ); }); it( 'returns 2 for cellIndex 18', () => { let cellPosition = new SudokuCellPosition( 18 ); expect( cellPosition.row ).toBe( 2 ); }); }); describe( '.column', () => { it( 'returns 0 for too low out of range values', () => { let cellPosition = new SudokuCellPosition( 0 ); expect( cellPosition.column ).toBe( 0 ); }); it( 'returns 0 for too high out of range values', () => { let cellPosition = new SudokuCellPosition( 82 ); expect( cellPosition.column ).toBe( 0 ); }); it( 'returns 1 for cellIndex 1', () => { let cellPosition = new SudokuCellPosition( 1 ); expect( cellPosition.column ).toBe( 1 ); }); it( 'returns 2 for cellIndex 11', () => { let cellPosition = new SudokuCellPosition( 11 ); expect( cellPosition.column ).toBe( 2 ); }); it( 'returns 1 for cellIndex 9', () => { let cellPosition = new SudokuCellPosition( 9 ); expect( cellPosition.column ).toBe( 9 ); }); }); describe( '.square', () => { it( 'returns 0 for too low out of range values', () => { let cellPosition = new SudokuCellPosition( 0 ); expect( cellPosition.square ).toBe( 0 ); }); it( 'returns 0 for too high out of range values', () => { let cellPosition = new SudokuCellPosition( 82 ); expect( cellPosition.square ).toBe( 0 ); }); it( 'returns 1 for cellIndex 1' , () => { let cellPosition = new SudokuCellPosition( 1 ); expect( cellPosition.square ).toBe( 1 ); }); it( 'returns 2 for cellIndex 4' , () => { let cellPosition = new SudokuCellPosition( 4 ); expect( cellPosition.square ).toBe( 2 ); }); it( 'returns 1 for cellIndex 19' , () => { let cellPosition = new SudokuCellPosition( 28 ); expect( cellPosition.square ).toBe( 4 ); }); }); }); <file_sep>import { CellSolver } from '../CellSolver'; import { Utility } from "../../../Utility"; export class RowCellSolver extends CellSolver { private _row: string; constructor( sudoku: string ) { super( sudoku ); } public solve( cellIndex: number): number { if( this.isAlreadySolved( cellIndex ) === true ) throw new Error('The cell you are trying to solve is already solved.'); let rowIndex = Utility.cellPosition( cellIndex ).row; this._row = this._slicer.sliceRow( rowIndex ); if( this.hasOneUnsolvedCellInRow() === false ) return 0; let i = 0; while( this._row.includes( i.toString() ) ) i++; return i; } private hasOneUnsolvedCellInRow(): boolean { return this._row.indexOf('0') === this._row.lastIndexOf('0'); } } <file_sep>import { CellSolver } from "../CellSolver"; import { Utility } from "../../../Utility"; export class ColumnCellSolver extends CellSolver { private _column: string; canSolve(index: number): boolean { if( this._sudoku.charAt( index-1 ) === '0' ) { let columnIndex = index % 9; let slicer = Utility.slicer( this._sudoku ); this._column = slicer.sliceColumn( columnIndex ); if( this._column.indexOf('0') === this._column.lastIndexOf('0') ) return true; } return false; } solve(index: number): number { let columnIndex = index % 9; let slicer = Utility.slicer( this._sudoku ); this._column = slicer.sliceColumn( columnIndex ); for( let i=1; i<10; i++) { if( this._column.includes( i.toString() ) === false ) return i; } } } <file_sep>export class SudokuCellPosition { private _index; private _row = 0; private _column = 0; private _square = 0; constructor( index: number ) { this._index = index; if( this.isOutOfBounds() === false ) { this.calculateRow(); this.calculateColumn(); // NOTE: run calculateSquare AFTER _row and _column are set this.calculateSquare(); } } get row(): number { return this._row; } get column(): number { return this._column; } get square(): number { return this._square; } private calculateRow(): void { this._row = Math.ceil( this._index / 9 ); } private calculateColumn(): void { if( this._index % 9 !== 0 ) this._column = this._index % 9; else // if( this._index % 9 === 0 ) this._column = 9; } private calculateSquare(): void { this._square = Math.ceil(this.column / 3) + Math.floor( this._row / 3 ) * 3 ; } private isOutOfBounds(): boolean { return this._index < 1 || this._index > 81; } } <file_sep> export class SudokuMutator { static mutate( sudoku: string, index: number, value: number ): string { let beforeIndex = sudoku.substring( 0, index ); let afterIndex = sudoku.substring( index + 1 );; return beforeIndex + value + afterIndex; } } <file_sep>import { SudokuTreeNode } from './SudokuTree'; describe( 'SudokuTree', () => { it( 'getSudoku() should return its initial sudoku', () => { let sudoku = '123456789789123456456789123312845967697312845845697312231574698968231574574968231'; let treeNode = new SudokuTreeNode( sudoku ); expect( treeNode.sudoku ).toBe( sudoku ); }); it( 'getSudoku() should return its initial sudoku (2)', () => { let sudoku = '835729416497561238261843759149387562573692841962415397358976124914258673726134985'; let treeNode = new SudokuTreeNode( sudoku ); expect( treeNode.sudoku ).toBe( sudoku ); }); it( 'getSudoku() should have one child with the value of 1 added', () => { let sudoku = '123456789789123456456789123312845967697312845845697312231574698968231574574968230'; let solution = '123456789789123456456789123312845967697312845845697312231574698968231574574968231'; let treeNode = new SudokuTreeNode( sudoku ); let childNodes = treeNode.children; expect( childNodes.length ).toBe( 1 ); expect( childNodes[0].children.length ).toBe( 0 ); expect( childNodes[0].sudoku ).toBe( solution ); }); it( 'getSudoku() should have one child with the value of 1 added at a different position', () => { let sudoku = '023456789789123456456789123312845967697312845845697312231574698968231574574968231'; let solution = '123456789789123456456789123312845967697312845845697312231574698968231574574968231'; let treeNode = new SudokuTreeNode( sudoku ); let childNodes = treeNode.children; expect( childNodes.length ).toBe( 1 ); expect( childNodes[0].children.length ).toBe( 0 ); expect( childNodes[0].sudoku ).toBe( solution ); }); it( 'getSudoku() should have one child with a different value', () => { let sudoku = '103456789789123456456789123312845967697312845845697312231574698968231574574968231'; let solution = '123456789789123456456789123312845967697312845845697312231574698968231574574968231'; let treeNode = new SudokuTreeNode( sudoku ); let childNodes = treeNode.children; expect( childNodes.length ).toBe( 1 ); expect( childNodes[0].children.length ).toBe( 0 ); expect( childNodes[0].sudoku ).toBe( solution ); }); }) <file_sep>import { SquareCellSolver } from "./CellSolver/SquareSolver/SquareSolver"; import { RowCellSolver } from "./CellSolver/RowSolver/RowCellSolver"; import { ColumnCellSolver } from "./CellSolver/ColumnSolver/ColumnCellSolver"; export class SudokuSolver { // facade private _sudoku; constructor( sudoku: string ) { this._sudoku = sudoku; } columnSquareSolver() { return new ColumnCellSolver(this._sudoku ); } rowCellSolver() { return new RowCellSolver( this._sudoku ); } squareCellSolver() { return new SquareCellSolver( this._sudoku ); } } <file_sep>import { RowCellSolver } from './RowCellSolver'; describe( 'RowCellSolver', () => { it( 'does not solve an empty sudoku', () => { let sudoku = '000000000000000000000000000000000000000000000000000000000000000000000000000000000'; let solver = new RowCellSolver( sudoku ); expect( solver.solve( 1 ) ).toBe( 0 ); }); it( 'throws error when a value is already solved', () => { let sudoku = '123456780000000000000000000000000000000000000000000000000000000000000000000000000'; let solver = new RowCellSolver( sudoku ); expect( () => { solver.solve( 1 ) } ).toThrow( new Error('The cell you are trying to solve is already solved.') ); }); it( 'solves sudokuRow no 1', () => { let sudoku = '023456789000000000000000000000000000000000000000000000000000000000000000000000000'; let solver = new RowCellSolver( sudoku ); expect( solver.solve( 1 ) ).toBe( 1 ); }); it( 'solve sudokuRow no 1 with a value other than 1', () => { let sudoku = '013456789000000000000000000000000000000000000000000000000000000000000000000000000'; let solver = new RowCellSolver( sudoku ); expect( solver.solve( 1 ) ).toBe( 2 ); }); it( 'solve sudokuRow other than no 1', () => { let sudoku = '000000000013456789000000000000000000000000000000000000000000000000000000000000000'; let solver = new RowCellSolver( sudoku ); expect( solver.solve( 10 ) ).toBe( 2 ); }); it( 'solve sudokuRow no 1 using a value from a different column', () => { let sudoku = '913456780000000000000000000000000000000000000000000000000000000000000000000000000'; let solver = new RowCellSolver( sudoku ); expect( solver.solve( 9 ) ).toBe( 2 ); }); }); <file_sep>import { CellSolver } from "../CellSolver"; import { Utility } from "../../../Utility"; export class SquareCellSolver extends CellSolver { private _square: string; constructor( sudoku: string ) { super( sudoku ); } public solve( cellIndex: number ): number { let squareIndex = Utility.cellPosition( cellIndex ).square; this._square = this._slicer.sliceSquare( squareIndex ); // TODO: test out of bounds / invalid index // TODO: test isALreadySOlved ( see row for example ) if( this.hasOneUnsolvedCellInSquare() === false ) return 0; let i = 0; while( this._square.includes( i.toString() ) ) i++; return i; } private hasOneUnsolvedCellInSquare(): boolean { return this._square.indexOf('0') === this._square.lastIndexOf('0'); } } <file_sep>import { SudokuValidator } from './SudokuValidator'; describe( 'SudokuValidator', () => { // NOTE: SudokuValidator should only check if the structural integrity is violated. NOT if the sudoku can be solved it( 'should validate if an empty 9x9 sudoku', () => { // 81 length let sudoku = '000000000000000000000000000000000000000000000000000000000000000000000000000000000'; let validator = new SudokuValidator( sudoku ); expect( validator.validate() ).toBeTruthy(); }); it( 'should invalidate a sudokustring with an invalid length (e.g. 80)', () => { let sudoku = '00000000000000000000000000000000000000000000000000000000000000000000000000000000'; let validator = new SudokuValidator( sudoku ); expect( validator.validate() ).toBeFalsy(); }); it( 'should validate a sudokuRow if it contains no identical values', () => { let sudoku = '100000000000000000000000000000000000000000000000000000000000000000000000000000000'; let validator = new SudokuValidator( sudoku ); expect( validator.validate() ).toBeTruthy(); }); it( 'should invalidate a sudokuRow if it contains identical values (1)', () => { let sudoku = '110000000000000000000000000000000000000000000000000000000000000000000000000000000'; let validator = new SudokuValidator( sudoku ); expect( validator.validate() ).toBeFalsy(); }); it( 'should invalidate a sudokuRow if it contains identical values in the last row (2)', () => { let sudoku = '000000000000000000000000000000000000000000000000000000000000000000000000000000011'; let validator = new SudokuValidator( sudoku ); expect( validator.validate() ).toBeFalsy(); }); it( 'should invalidate a sudokuRow if it contains identical values other than 1', () => { let sudoku = '000000000000000000000000000000000000000000000000000000000000000000000000000000022'; let validator = new SudokuValidator( sudoku ); expect( validator.validate() ).toBeFalsy(); }); it( 'should invalidate a sudokuColumn if it contains identical values', () => { let sudoku = '100000000100000000000000000000000000000000000000000000000000000000000000000000000'; let validator = new SudokuValidator( sudoku ); expect( validator.validate() ).toBeFalsy(); }); it( 'should invalidate a sudokuColumn if it contains identical values in column 2', () => { let sudoku = '010000000010000000000000000000000000000000000000000000000000000000000000000000000'; let validator = new SudokuValidator( sudoku ); expect( validator.validate() ).toBeFalsy(); }); it( 'should invalidate a sudokuSquare if it contains identical values in square 1', () => { let sudoku = '100000000010000000000000000000000000000000000000000000000000000000000000000000000'; let validator = new SudokuValidator( sudoku ); expect( validator.validate() ).toBeFalsy(); }); it( 'should invalidate a sudokuSquare other than 1', () => { let sudoku = '200000000020000000000000000000000000000000000000000000000000000000000000000000000'; let validator = new SudokuValidator( sudoku ); expect( validator.validate() ).toBeFalsy(); }); }); <file_sep>import { SudokuSlicer9x9 } from './SudokuSlicer'; describe( 'SudokuSlicer', () => { describe( '.sliceRow', () => { it( '(1) should return row one (1)', () => { let sudoku = '100000000000000000000000000000000000000000000000000000000000000000000000000000000'; let slicer = new SudokuSlicer9x9( sudoku ); expect( slicer.sliceRow( 1 ) ).toBe( '100000000' ); }); it( '(1) should return row one (2)', () => { let sudoku = '205000000000000000000000000000000000000000000000000000000000000000000000000000000'; let slicer = new SudokuSlicer9x9( sudoku ); expect( slicer.sliceRow( 1 ) ).toBe( '205000000' ); }); it( '(9) should return row nine', () => { let sudoku = '000000000000000000000000000000000000000000000000000000000000000000000000000000123'; let slicer = new SudokuSlicer9x9( sudoku ); expect( slicer.sliceRow( 9 ) ).toBe( '000000123' ); }); }); describe( '.sliceColumn', () => { it( 'should return row one #1', () => { let sudoku = '100000000000000000000000000000000000000000000000000000000000000000000000000000000'; let slicer = new SudokuSlicer9x9( sudoku ); expect( slicer.sliceColumn( 1 ) ).toBe( '100000000' ); }); it( 'should return row one #2', () => { let sudoku = '010000000000000000000000000000000000000000000000000000000000000000000000000000000'; let slicer = new SudokuSlicer9x9( sudoku ); expect( slicer.sliceColumn( 1 ) ).toBe( '000000000' ); }); it( 'should return row nine', () => { let sudoku = '000000000000000000000000000000000000000000000000000000000000000000000000000000001'; let slicer = new SudokuSlicer9x9( sudoku ); expect( slicer.sliceColumn( 9 ) ).toBe( '000000001' ); }); }); describe( '.sliceColumn', () => { it( 'should return square one #1', () => { let sudoku = '100000000000000000000000000000000000000000000000000000000000000000000000000000000'; let slicer = new SudokuSlicer9x9( sudoku ); expect( slicer.sliceSquare( 1 ) ).toBe( '100000000' ); }); it( 'should return square one #2', () => { let sudoku = '100000000010000000000000000000000000000000000000000000000000000000000000000000000'; let slicer = new SudokuSlicer9x9( sudoku ); expect( slicer.sliceSquare( 1 ) ).toBe( '100010000' ); }); it( 'should return square nine', () => { let sudoku = '000000000000000000000000000000000000000000000000000000000000000000000001000000101'; let slicer = new SudokuSlicer9x9( sudoku ); expect( slicer.sliceSquare( 9 ) ).toBe( '000001101' ); }); }); }); <file_sep>import { Utility } from '../../Utility'; export abstract class CellSolver { protected _sudoku: string; protected _slicer; protected _solution: number; constructor( sudoku: string ) { this._sudoku = sudoku; this._slicer = Utility.slicer( sudoku ); } abstract solve( index: number ): number; protected isAlreadySolved( cellIndex ): boolean { return this._sudoku.charAt( cellIndex - 1 ) !== '0'; } } <file_sep>import { Utility } from '../Utility'; export class SudokuTreeNode { // this is a composite generating a tree of all possible paths to a solution for a sudoku private _sudoku; // _parent = null; private _children: Array<SudokuTreeNode> = []; constructor( sudoku: string ){ this._sudoku = sudoku; if( this._sudoku.includes('0') ){ // check if isSolved let index = this._sudoku.indexOf('0'); for( let value=1; value<10 ; value++ ) { let childSudoku = Utility.mutate( this._sudoku, index, value ); if( Utility.validate( childSudoku ) ) { this.addChild( childSudoku ); } } } else { // console.log( this._sudoku ); } } get sudoku(): string { return this._sudoku; } get children() { return this._children; } public addChild( sudoku ) { this._children.push( new SudokuTreeNode( sudoku ) ); } // removeChild } // cannot stop iteration with a huge amount of solutions ( e.g. an empty sudoku ) <file_sep>import { ColumnCellSolver } from './ColumnCellSolver'; describe( 'ColumnCellSolver', () => { it( 'does not solve an empty sudoku', () => { let sudoku = '000000000000000000000000000000000000000000000000000000000000000000000000000000000'; let solver = new ColumnCellSolver( sudoku ); expect( solver.canSolve( 1 ) ).toBeFalsy(); }); it( 'does not solve a sudoku when a value is already solved', () => { let sudoku = '100000000000000000000000000000000000000000000000000000000000000000000000000000000'; let solver = new ColumnCellSolver( sudoku ); expect( solver.canSolve( 1 ) ).toBeFalsy(); }); it( 'solve returns 1 if sudoku is solved', () => { let sudoku = '000000000200000000300000000400000000500000000600000000700000000800000000900000000'; let solver = new ColumnCellSolver( sudoku ); expect( solver.canSolve( 1 ) ).toBeTruthy(); expect( solver.solve( 1 ) ).toBe( 1 ); }); it( 'solve returns 2 if sudoku is solved', () => { let sudoku = '000000000100000000300000000400000000500000000600000000700000000800000000900000000'; let solver = new ColumnCellSolver( sudoku ); expect( solver.canSolve( 1 ) ).toBeTruthy(); expect( solver.solve( 1 ) ).toBe( 2 ); }); it( 'solve returns can also solve different columns', () => { let sudoku = '200000000100000000000000000400000000500000000600000000700000000800000000900000000'; let solver = new ColumnCellSolver( sudoku ); expect( solver.canSolve( 19 ) ).toBeTruthy(); expect( solver.solve( 19 ) ).toBe( 3 ); }); }); <file_sep>import { RecursiveSudokuSolver } from './SudokuSolver'; describe( 'SudokuSolver', () => { it( 'should return an empty array with an invalid sudoku', () => { let sudoku = '110000000000000000000000000000000000000000000000000000000000000000000000000000000'; let solver = new RecursiveSudokuSolver( sudoku ); expect( solver.solve() ).toEqual( [] ); }); // it( 'should return one solution for a solved sudoku', () => { // // }); }); <file_sep>import { Utility } from '../../Utility'; export abstract class SudokuSolver { // abstract factory protected _sudoku: string; protected _solver: SudokuSolver; constructor( sudoku: string ) { this._sudoku = sudoku; } abstract solve(); // solve( algorithm: string = 'recursive'): Array<string> { // switch( algorithm ) { // case 'recursive': // this._solver = new RecursiveSudokuSolver( this._sudoku ); // } // // return this._solver.solve(); // } } export class RecursiveSudokuSolver extends SudokuSolver { // uses a tree structure from composite private _solutions = []; solve(): Array<string> { if( Utility.validate( this._sudoku ) === false ) { return this._solutions; } } // composite??? // should I seperate creating a tree from applying solution // create a leaf if added value is valid // iterate over structure to retreive the solutions // each branch / leaf has a solution } class RecursiveSudokuComposite { private _sudokuState: string; private _parent: RecursiveSudokuComposite; private _children: Array<RecursiveSudokuComposite>; // store as {1: RecursiveSudokuComposite, 2: RecursiveSudokuComposite, 3: null, etc... } ??? constructor( sudoku: string ) { this._sudokuState = sudoku; } protected add( parent: RecursiveSudokuComposite ): void { // if solution is valid add to parent // then check if there are valid children for this } protected remove( parent: RecursiveSudokuComposite ): void {} public get_children(){}; // remove if no children after 1-9 are tested // LEAFS are solutions maybe use an Observer to log them??? // another Observer to backlog from solution up to the initial sudokuState = just call parent() until none exist??? May be easier, but have to keep the entire structure in memory then. } class RecursiveSudokuLeaf { private _sudokuState: string; private _parent: RecursiveSudokuComposite; private _children: Array<RecursiveSudokuComposite>; // store as {1: RecursiveSudokuComposite, 2: RecursiveSudokuComposite, 3: null, etc... } ??? constructor( sudoku: string ) { this._sudokuState = sudoku; } protected add( parent: RecursiveSudokuComposite ): void { // if solution is valid add to parent // then check if there are valid children for this } protected remove( parent: RecursiveSudokuComposite ): void {} // child removes parent or parent removes child ( garbage collection if invalid??? ) ? public get_children(): Array<RecursiveSudokuLeaf> { return []; }; // remove if no children after 1-9 are tested // LEAFS are solutions maybe use an Observer to log them??? // another Observer to backlog from solution up to the initial sudokuState = just call parent() until none exist??? May be easier, but have to keep the entire structure in memory then. } <file_sep>// top-level facade for all Sudoku // also defines operations class Sudoku { // create( ... ): string // sudokustring // parameters could define complexity? unsolved cells and possible solutions possibly impossible combination.. // maybe get sudokus from a db? // or obtain from tree and count 'splits' // solve( sudoku ): Array<string> // a series of sudokustrings that are valid solutions } <file_sep>export abstract class SudokuSlicer { protected _sudoku: string; constructor( sudoku: string ) { this._sudoku = sudoku; } abstract sliceRow( index: number ): string; abstract sliceColumn( index: number ): string; abstract sliceSquare( index: number ): string; } export class SudokuSlicer9x9 extends SudokuSlicer { sliceSquare( index: number ): string { let square = ''; index--; let rowPosition = Math.floor( index / 3 )*27; let columnPosition = index % 3 * 3; let topLeftCorner = rowPosition + columnPosition; for( let i=0; i<9;i++ ) { let stringPosition = topLeftCorner + i + Math.floor(i/3)*6; square += this._sudoku.charAt( stringPosition ); } return square; } sliceColumn( index: number ): string { index--; let column = ''; for( let i=0; i<9; i++ ) { column += this._sudoku.charAt( i*9+index ); } return column; } sliceRow( index: number ): string { let lastChar = 9*index; let firstChar = 9*index - 9; return this._sudoku.slice( firstChar, lastChar ); } } <file_sep>import { Utility } from '../Utility'; export class SudokuValidator { protected _sudoku; protected _slicer; private _validator; public constructor( sudoku: string ) { this._sudoku = sudoku; } public validate(): boolean { if( this.setValidator() === false ) return false; if( this.validRows() === false ) return false; if( this.validColumns() === false ) return false; if( this.validSquares() === false ) return false; else return true; } protected validRows(): boolean { return this._validator.validRows(); } protected validColumns(): boolean { return this._validator.validColumns(); } protected validSquares(): boolean { return this._validator.validSquares(); } private setValidator(): boolean { if( this._sudoku.length === 81 ) { this._validator = new SudokuValidator9x9( this._sudoku ); return true; } else { console.error( 'this sudokurepresentation has an invalid length' ); return false; } } } class SudokuValidator9x9 extends SudokuValidator { constructor( sudoku: string ) { super( sudoku ); this._slicer = Utility.slicer( this._sudoku ); } protected validRows(): boolean { let validCharacters = [ '1', '2', '3', '4', '5', '6', '7', '8', '9' ]; for( let i=0; i<validCharacters.length; i++ ) { if( this.validCharacterInRows( validCharacters[i] ) === false ) { return false; } } return true; } protected validColumns(): boolean { let validCharacters = [ '1', '2', '3', '4', '5', '6', '7', '8', '9' ]; for( let i=0; i<validCharacters.length; i++ ) { if( this.validCharacterInColumns( validCharacters[i] ) === false ) { return false; } } return true; } protected validSquares(): boolean { let validCharacters = [ '1', '2', '3', '4', '5', '6', '7', '8', '9' ]; for( let i=0; i<validCharacters.length; i++ ) { if( this.validCharacterInSquares( validCharacters[i] ) === false ) { return false; } } return true; } private validCharacterInRows( character: string ): boolean { for( let i=1; i<10; i++ ) { let row = this._slicer.sliceRow( i ); if( this.validCharacterInArea( character, row ) === false ) return false; } return true; } private validCharacterInColumns( character: string ): boolean { for( let i=1; i<10; i++ ) { let column = this._slicer.sliceColumn( i ); if( this.validCharacterInArea( character, column ) === false ) return false; } return true; } private validCharacterInSquares( character: string ) { for( let i=1; i<10; i++ ) { let column = this._slicer.sliceSquare( i ); if( this.validCharacterInArea( character, column ) === false ) return false; } return true; } private validCharacterInArea( character: string, area: string ): boolean { return area.indexOf( character ) === area.lastIndexOf( character ); } } <file_sep>import { SquareCellSolver } from "./SquareSolver"; describe( 'SquareSolver', () => { it( 'does not solve an empty sudoku', () => { let sudoku = '000000000000000000000000000000000000000000000000000000000000000000000000000000000'; let solver = new SquareCellSolver( sudoku ); expect( solver.solve( 1 ) ).toBe( 0 ); }); it( 'does not solve a fully solved square', () => { let sudoku ='123000000456000000789000000000000000000000000000000000000000000000000000000000000'; let solver = new SquareCellSolver( sudoku ); expect( solver.solve( 1 ) ).toBe( 0 ); }); it( 'solves sudokuSquare no 1', () => { let sudoku = '023000000456000000789000000000000000000000000000000000000000000000000000000000000'; let solver = new SquareCellSolver( sudoku ); expect( solver.solve( 1 ) ).toBe( 1 ); }); it( 'solves sudokuSquare no 1 with a value other than 1', () => { let sudoku = '013000000456000000789000000000000000000000000000000000000000000000000000000000000'; let solver = new SquareCellSolver( sudoku ); expect( solver.solve( 1 ) ).toBe( 2 ); }); it( 'solves sudokusquare no 2', () => { let sudoku = '000023000000456000000789000000000000000000000000000000000000000000000000000000000'; let solver = new SquareCellSolver( sudoku ); expect( solver.solve( 4 ) ).toBe( 1 ); }); }); <file_sep>import { SudokuMutator } from './SudokuMutator'; describe( 'SudokuMutator', () => { it( 'be able to mutate the first value', () => { let sudoku = '000000000000000000000000000000000000000000000000000000000000000000000000000000000'; let mutatedSudoku = '100000000000000000000000000000000000000000000000000000000000000000000000000000000'; expect( SudokuMutator.mutate( sudoku, 0, 1 ) ).toBe( mutatedSudoku ); }); it( 'be able to mutate the second value', () => { let sudoku = '000000000000000000000000000000000000000000000000000000000000000000000000000000000'; let mutatedSudoku = '010000000000000000000000000000000000000000000000000000000000000000000000000000000'; expect( SudokuMutator.mutate( sudoku, 1, 1 ) ).toBe( mutatedSudoku ); }); it( 'be able to mutate values other than 1', () => { let sudoku = '000000000000000000000000000000000000000000000000000000000000000000000000000000000'; let mutatedSudoku = '020000000000000000000000000000000000000000000000000000000000000000000000000000000'; expect( SudokuMutator.mutate( sudoku, 1, 2 ) ).toBe( mutatedSudoku ); }); }); // what if a mutator tries to mutate a taken value??? // return false would be odd // should that occur ever? // Maybe for undo operations? // what if a mutation results to an invalid sudoku // external or internal isValid check? External.. can call validator? // do I perform the check always? Yes. // do I need alternate external behavior after checking isValid? Yes if not valid code may take another course... So isValid should be called externally // may even be useful solving sudokus? only run isValid() when asked for performance reasons? // also invalid trying to overwrite occupied index if unable isValid() // idea undo functionality undo to the last valid state ( changes from view ) // possibly ask if sudoku isSolved??? // Sudoku isValid and no 0's in string. // ask if a position isTaken() <file_sep>import { SudokuSlicer, SudokuSlicer9x9 } from './SudokuSlicer/SudokuSlicer'; import{ SudokuValidator } from './SudokuValidator/SudokuValidator'; import { SudokuMutator } from './SudokuMutator/SudokuMutator'; import { SudokuTreeNode } from './SudokuTree/SudokuTree'; import { SudokuCellPosition } from './CellPosition/SudokuCellPosition'; // all utility classes should exclusively be called through this facade export { SudokuSlicer9x9 } from './SudokuSlicer/SudokuSlicer'; export class Utility { public static slicer( sudoku: string ): SudokuSlicer { return new SudokuSlicer9x9( sudoku ); } public static validate( sudoku: string ): boolean { // Validator only has one method to validate a sudoku so there is a minor implementation let _validator = new SudokuValidator( sudoku ); return _validator.validate(); } public static mutate( sudoku, index, value ): string { return SudokuMutator.mutate( sudoku, index, value ); } public static generateTree( sudoku: string ) { // take extreme care not to process big trees return new SudokuTreeNode( sudoku ); } public static cellPosition( cellIndex: number ): SudokuCellPosition { return new SudokuCellPosition( cellIndex ); } }
50c6b3b09e3ee1ce0a11d242851887ec08357c57
[ "TypeScript" ]
22
TypeScript
RMo-Sloth/Sudoku
aa025ffc53d309b7d29c3f19ceb70225dcaa49a8
de22d4ecc10fbea65bf756c9eed5d0413985fffa
refs/heads/master
<file_sep>import React from 'react' import { Link } from 'gatsby' import styles from './header.module.css' const Header = () => ( <div className={styles.navigationOuter}> <div className={styles.navigationInner}> <ul className={styles.headerul}> <li className={styles.headerli}><Link to="/" style={{ color: 'black', textDecoration: 'none', }} >Home</Link></li> <li className={styles.headerli}><Link to="/services" style={{ color: 'black', textDecoration: 'none', }} >Services</Link></li> <li className={styles.headerli}> <span className={styles.logo}> Paul's Motor Inc </span> </li> <li className={styles.headerli}><Link to="/about" style={{ color: 'black', textDecoration: 'none', }} >About</Link></li> <li className={styles.headerli}><Link to="/contact-us" style={{ color: 'black', textDecoration: 'none', }} >Contact Us</Link></li> </ul> </div> </div> ) export default Header <file_sep>import React from 'react' import Layout from '../components/layout' import "../styles/layout-overide.css" const IndexPage = () => ( <Layout> <div className="section1"> <div className="section1Header"> <h1>Paul's Motor Inc in Vancouver, WA</h1> <h1>Auto Repair Done by Professionals</h1> </div> <div className="section1Body"> <h2>Experience and Trust</h2> <p>Established in 1994, Paul's Motor Inc has had over 24 years of experience with used car sales and automotive repair. We understand what it takes to provide dependable auto service and repairs at a fair price to ensure our customers' needs are met. This has helped build loyalty and trust with customers who happily return to us with their auto repair needs over and over again. </p> <h2>Auto Repair and Maintenance</h2> <p>While initially specializing in Jeep Cherokees, Paul's Motor has expanded to repair and service all kinds of makes and models. Some of these brands include Volkwagen, Honda, Toyota, Kia, Ford, Lexus, Subaru and many more. Whether you need your brake pads replaced, oil changed or engine repaired, we will do our best to ensure your vehicle is fixed to your satisfaction. </p> </div> </div> </Layout> ) export default IndexPage <file_sep>import React from 'react' import {Link} from 'gatsby' import styles from './cover.module.css' const Cover = () => ( <div className={styles.cover}> <div className={styles.coverContent} > <h1>Quality Auto Repair.</h1> <h2>Offering high-quality auto repair and used car sales.</h2> <h2> <Link to='/services' style={{ color: 'white', }} >Click here to find out more!</Link> </h2> </div> </div> ) export default Cover;
0107860862fee08ea2020152fa16f5611a2db2bb
[ "JavaScript" ]
3
JavaScript
sashademyanik/pauls-motor
a96687db5f392c8023456c79f6b9fb7a75c820c3
e56900561c48a81d1a5288970c1a12492052c5d3
refs/heads/master
<file_sep>from flask import Flask my_app = Flask(__name__) @my_app.route('/') def root(): return "hello world route" @my_app.route('/route1') def route1(): return "you have reached route 1" @my_app.route('/route2') def route2(): return "you have reached route 2" if __name__ == '__main__': my_app.debug = True my_app.run()
c69540ae3b24f0b1ea78103b43c8c587a10d919e
[ "Python" ]
1
Python
henryz2000-stuycs/flask-intro
a1f755afc74fe0216991d54c985c2bf50215d490
1f039b5b7cb912cd1f29fda5343293dc6249d498
refs/heads/master
<repo_name>Lucardoo/LojaLPW<file_sep>/loja/admin/produtos/criar.php <?php require_once('../inc/conexao.php'); require_once ($base_path . 'inc/cabecalho.php'); if(isset($_SESSION['nome'])) { ?> <form class="form-signin" action="<?php echo $base_url.'produtos/adiciona.php'; ?>" method="post"> <div class="form-label-group"> <input type="text" step="0.010" name="nome" class="form-control" placeholder=" Nome"> <br><br> </div> <div class="form-label-group"> <input type="number" step="0.01" name="preco" class="form-control" placeholder=" Preço"> <br><br> </div> <div class="form-label-group"> <textarea name="descricao" rows="10" cols="155" placeholder=" Escreva a descrição"></textarea> <br><br> </div> <button class="btn btn-lg btn-primary btn-block" type="submit" name="botao"><font style="vertical-align: inherit;"><font style="vertical-align: inherit;">Adicionar Produto</font></font></button> <a href="<?php echo $base_url.'produtos/index.php'; ?>" class="btn btn-secondary btn-lg btn-block">Voltar</a> </form> <?php } else { header('Location: '.$base_url.'index.php'); } require_once($base_path . 'inc/rodape.php'); ?><file_sep>/loja/inc/conexao.php <?php session_start(); $base_url = 'http://localhost/loja/'; $conexao = pg_connect('host=localhost port=5432 dbname=lojalpw user=postgres password=<PASSWORD>'); if(!$conexao){ echo 'nao rolou'; }<file_sep>/loja/admin/produtos/editar.php <?php require_once('../inc/conexao.php'); require_once ($base_path . 'inc/cabecalho.php'); if(isset($_SESSION['nome'])) { $id=$_GET['id']; $sql="SELECT * FROM produtos WHERE id='$id'"; $res=pg_query($conexao,$sql); $arr=pg_fetch_array($res); ?> <form class="form-signin" action="<?php echo $base_url.'produtos/altera.php'; ?>" method="post"> <input type="hidden" name="id" value="<?php echo $arr['id']; ?>"> <div class="form-label-group"> <input type="text" step="0.010" name="nome" class="form-control" value="<?php echo $arr['nome']; ?>"> <br><br> </div> <div class="form-label-group"> <input type="number" step="0.01" name="preco" class="form-control" value="<?php echo $arr['preco']; ?>"> <br><br> </div> <div class="form-label-group"> <textarea name="descricao" rows="10" cols="155"><?php echo $arr['descricao']; ?></textarea> <br><br> </div> <button class="btn btn-lg btn-primary btn-block" type="submit" name="botao"><font style="vertical-align: inherit;"><font style="vertical-align: inherit;">Alterar Produto</font></font></button> <a href="<?php echo $base_url.'produtos/index.php'; ?>" class="btn btn-secondary btn-lg btn-block">Voltar</a> </form> <?php } else { header('Location: '.$base_url.'index.php'); } require_once($base_path . 'inc/rodape.php'); ?><file_sep>/loja/admin/produtos/altera.php <?php require_once('../inc/conexao.php'); $id=$_POST['id']; $nome=$_POST['nome']; $preco=$_POST['preco']; $descricao=$_POST['descricao']; $sql = "UPDATE produtos SET nome='$nome', preco='$preco', descricao='$descricao' WHERE id='$id'"; $altera=pg_query($conexao,$sql); header('Location: '.$base_url.'produtos/index.php'); ?><file_sep>/loja/admin/produtos/excluir.php <?php require_once('../inc/conexao.php'); if(isset($_SESSION['nome'])) { $id=$_GET['id']; $sql="DELETE FROM produtos WHERE id='$id'"; $res=pg_query($conexao,$sql); header('Location: '.$base_url.'produtos/index.php'); } else { header('Location: '.$base_url.'index.php'); } ?><file_sep>/loja/admin/produtos/adiciona.php <?php require_once('../inc/conexao.php'); $nome=$_POST['nome']; $preco=$_POST['preco']; $descricao=$_POST['descricao']; $sql="INSERT INTO produtos(nome,preco,descricao) VALUES ('$nome','$preco','$descricao')"; $adiciona=pg_query($conexao,$sql); header('Location: '.$base_url.'produtos/index.php'); ?>
294ff40ffd17e9cc3ac60ff04c20db40cc709635
[ "PHP" ]
6
PHP
Lucardoo/LojaLPW
9c70812b2345c8ed52a4dac35988fb8b19f9fb5b
7be3cc76c8486364d94474d1da866d9d50c2ab23
refs/heads/master
<file_sep># generator-rrr [![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Dependency Status][daviddm-image]][daviddm-url] [![Coverage percentage][coveralls-image]][coveralls-url] > react redux router ## Installation First, install [Yeoman](http://yeoman.io) and generator-rrr using [npm](https://www.npmjs.com/) (we assume you have pre-installed [node.js](https://nodejs.org/)). ```bash npm install -g yo npm install -g generator-rrr ``` Then generate your new project: ```bash yo rrr ``` ## Getting To Know Yeoman Yeoman has a heart of gold. He&#39;s a person with feelings and opinions, but he&#39;s very easy to work with. If you think he&#39;s too opinionated, he can be easily convinced. Feel free to [learn more about him](http://yeoman.io/). ## License Apache-2.0 © [<NAME>](http://kkpoon.github.io) [npm-image]: https://badge.fury.io/js/generator-rrr.svg [npm-url]: https://npmjs.org/package/generator-rrr [travis-image]: https://travis-ci.org/kkpoon/generator-rrr.svg?branch=master [travis-url]: https://travis-ci.org/kkpoon/generator-rrr [daviddm-image]: https://david-dm.org/kkpoon/generator-rrr.svg?theme=shields.io [daviddm-url]: https://david-dm.org/kkpoon/generator-rrr [coveralls-image]: https://coveralls.io/repos/kkpoon/generator-rrr/badge.svg [coveralls-url]: https://coveralls.io/r/kkpoon/generator-rrr <file_sep>'use strict'; var yeoman = require('yeoman-generator'); var chalk = require('chalk'); var yosay = require('yosay'); module.exports = yeoman.generators.Base.extend({ prompting: function () { var done = this.async(); // Have Yeoman greet the user. this.log(yosay( 'Welcome to the stellar ' + chalk.red('generator-rrr') + ' generator!' )); var prompts = [ { type: 'list', name: 'progLang', message: 'Which programming language you would use in this project?', choices: ["ES6", "TypeScript", "CoffeeScript"], default: "ES6" }, { type: "confirm", name: "useFlowType", message: "Do you use flowtype?", default: true, when: function(answers) { return answers.progLang === "ES6"; } } ]; this.prompt(prompts, function (props) { this.props = props; // To access props later use this.props.someOption; done(); }.bind(this)); }, writing: function () { this.config.set("progLang", this.props.progLang); this.fs.copy( this.templatePath('dummyfile.txt'), this.destinationPath('dummyfile.txt') ); }, install: function () { this.installDependencies(); } });
753e85c8ca6a3a1e398d6e58e24da4ba012717bf
[ "Markdown", "JavaScript" ]
2
Markdown
kkpoon/generator-rrr
e2f7a2b5ae4ba3d484b454916fd0f4aa4f4100d6
9d97517dea17df0171c4c1f0e1afc8288d5890c9
refs/heads/master
<repo_name>kellymurray/simple-js-challenges<file_sep>/functional-javascript-solutions/README.md My solutions to NodeSchool.io's Functional JavaScript course for reference when students are completing course. <file_sep>/README.md # simple-js-challenges Simple JavaScript challenges for kids and beginning learners. <file_sep>/simple-build-a-story.js //inspired by teamtreehouse.com //collect words from user var myNouns = prompt("Please give me a noun."); var myVerbs = prompt("Please give me a verb."); var myAdjs = prompt("Please give me an adjective."); //join variables into the story var myStory = "Once upon a time there was a " + myAdjs + " and brave " + myNouns + " who decided to " + myVerbs + "!"; document.write(myStory); <file_sep>/javascripting-solutions/README.md My solutions to NodeSchool.io's JavaScripting course for reference when students are completing course. <file_sep>/javascripting-solutions/function-arguments.js function math(num1, num2, num3) { var total1 = num2 * num3; var total2 = num1 + total1; return total2; } console.log(math(53, 61, 67));
aaf183c29793d7f551409d8f466bdde866bcb97c
[ "Markdown", "JavaScript" ]
5
Markdown
kellymurray/simple-js-challenges
f4074e518a56a0a93fb8605543e24d653a0cc8da
9f11f4cd3bc78ecf746137261fbc2743e8a0788b
refs/heads/master
<file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { LoginFormComponent } from './login-form/login-form.component'; import { LoginRegisterComponent } from './login-register/login-register.component'; import { LoginForgotPasswordComponent } from './login-forgot-password/login-forgot-password.component'; import { LoginVerifyEmailComponent } from './login-verify-email/login-verify-email.component'; const routes: Routes = [ { path: '', component: LoginFormComponent }, { path: 'registrar', component: LoginRegisterComponent }, { path: 'esqueci-senha', component: LoginForgotPasswordComponent }, { path: 'verifica-email', component: LoginVerifyEmailComponent } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class LoginRoutingModule { } <file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { ProjectListComponent } from './project-list/project-list.component'; import { ProjectFormComponent } from './project-form/project-form.component'; import { ProjectComponent } from './project/project.component'; import { ProjectFaseFormComponent } from './project-fase-form/project-fase-form.component'; import { ProjectFaseListComponent } from './project-fase-list/project-fase-list.component'; import { ProjectFaseComponent } from './project-fase/project-fase.component'; const routes: Routes = [ // Lista de Projetos { path: '', component: ProjectListComponent }, // Cadastrar Projeto { path: 'cadastrar-projeto', component: ProjectFormComponent }, // Mostrar Projeto { path: ':id_projeto', component: ProjectComponent }, // Editar Projeto { path: ':id_projeto/editar', component: ProjectFormComponent }, // Cadastrar Fase do Projeto { path: ':id_projeto/cadastrar-fase', component: ProjectFaseFormComponent }, // Mostrar Fases do Projeto { path: ':id_projeto/fases', component: ProjectFaseListComponent }, // Mostrar Fase do Projeto { path: ':id_projeto/:numero_fase', component: ProjectFaseComponent }, // Editar Fase do Projeto { path: ':id_projeto/:numero_fase/editar', component: ProjectFaseFormComponent }, ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class ProjectsRoutingModule { } <file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { ProjectFaseFormComponent } from './project-fase-form.component'; describe('ProjectFaseFormComponent', () => { let component: ProjectFaseFormComponent; let fixture: ComponentFixture<ProjectFaseFormComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ ProjectFaseFormComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ProjectFaseFormComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>import { Component, OnInit } from '@angular/core'; import { AuthService } from '../auth/auth.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-login-form', templateUrl: './login-form.component.html', styleUrls: ['./login-form.component.css'] }) export class LoginFormComponent implements OnInit { constructor( private authService: AuthService, private router: Router) { } img: string; ngOnInit() { const user = localStorage.getItem('user'); console.log(user); if (user) { this.router.navigate(['/projetos']); } this.img = `./../assets/images/brq-digital-solutions.png`; } login(email: string, senha: string) { const loginUser = this.authService.login(email, senha).then( data => { console.log(data); this.router.navigate(['/projetos']); }, error => { console.error(error); } ); console.log(loginUser); } } <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-project-fase-list', templateUrl: './project-fase-list.component.html', styleUrls: ['./project-fase-list.component.css'] }) export class ProjectFaseListComponent implements OnInit { constructor() { } ngOnInit() { } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { LoginRoutingModule } from './login-routing.module'; import { LoginFormComponent } from './login-form/login-form.component'; import { LoginRegisterComponent } from './login-register/login-register.component'; import { LoginForgotPasswordComponent } from './login-forgot-password/login-forgot-password.component'; import { LoginVerifyEmailComponent } from './login-verify-email/login-verify-email.component'; @NgModule({ declarations: [LoginFormComponent, LoginRegisterComponent, LoginForgotPasswordComponent, LoginVerifyEmailComponent], imports: [ CommonModule, LoginRoutingModule ] }) export class LoginModule { } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector: 'app-project-fase-form', templateUrl: './project-fase-form.component.html', styleUrls: ['./project-fase-form.component.css'] }) export class ProjectFaseFormComponent implements OnInit { id_fase: string; url: string; constructor(private router: Router) {} ngOnInit() { this.id_fase = this.router.url.replace('/projetos/', ''); this.url = this.id_fase.replace('/cadastrar-fase', ''); } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ProjectsRoutingModule } from './projects-routing.module'; import { ProjectFormComponent } from './project-form/project-form.component'; import { ProjectListComponent } from './project-list/project-list.component'; import { MenuComponent } from '../../components/menu/menu.component'; import { ProjectComponent } from './project/project.component'; import { ProjectFaseFormComponent } from './project-fase-form/project-fase-form.component'; import { ProjectFaseListComponent } from './project-fase-list/project-fase-list.component'; import { ProjectFaseComponent } from './project-fase/project-fase.component'; @NgModule({ declarations: [ ProjectListComponent, ProjectFormComponent, MenuComponent, ProjectComponent, ProjectFaseFormComponent, ProjectFaseListComponent, ProjectFaseComponent ], imports: [ CommonModule, ProjectsRoutingModule ] }) export class ProjectsModule { } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector: 'app-project', templateUrl: './project.component.html', styleUrls: ['./project.component.css'] }) export class ProjectComponent implements OnInit { url: string; novaFase: string; constructor(private router: Router) {} ngOnInit() { this.url = this.router.url.replace('/projetos/', ''); this.novaFase = this.router.url + '/cadastrar-fase'; } } <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-menu', templateUrl: './menu.component.html', styleUrls: ['./menu.component.css'] }) export class MenuComponent implements OnInit { img: string; constructor() { } ngOnInit() { this.img = `./../assets/images/brq-digital-solutions.png`; } }
f63f3a24c5273f598ffd2f9b4a97bd51a5fda2b6
[ "TypeScript" ]
10
TypeScript
EdsonFragnan/myteam
a617d7701f2cad3a9e658a986126e8357be236d3
0010da4c6851d0d4a3dc5535e20832b0fddce3a4
refs/heads/master
<file_sep>package com.lobinary.normal.cav.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import com.lobinary.normal.cav.dto.CAVDto; public class DateBaseUtil { String drivename = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://172.16.17.32:3306/lobinary"; String user = "root"; String password = "<PASSWORD>"; String insql; String upsql; String delsql; String sql = "select * from cav"; Connection conn = null; ResultSet rs = null; public Connection ConnectMysql() { try { if(conn==null||conn.isClosed()){ Class.forName(drivename); conn = (Connection) DriverManager.getConnection(url, user, password); if (!conn.isClosed()) { System.out.println("cav mysql数据库连接成功"); } else { System.out.println("cav mysql数据库连接失败"); } } } catch (Exception ex) { ex.printStackTrace(); } return conn; } public void CutConnection(Connection conn) throws SQLException { try { if (rs != null) ; if (conn != null) ; } catch (Exception e) { e.printStackTrace(); } finally { rs.close(); conn.close(); } } class user {// 内部类,其字段对应用来存放、提取数据库中的数据 int userid; String username = ""; String password = ""; String email = ""; // 通过set方法,往类的实例里“存放”数据 // 通过get方法,从类的实例里“获得”数据,然后再通过插入数据库 public void setId(int userid) { this.userid = userid; } public void setName(String username) { this.username = username; } public void setPassword(String password) { this.password = password; } public void setEmail(String email) { this.email = email; } public Integer getId() { return userid; } public String getName() { return username; } public String getPassword() { return password; } public String getEmail() { return email; } } public static void main(String[] args) { DateBaseUtil db = new DateBaseUtil(); // CAVDto cav = new CAVDto(); // cav.setName("测试名称"); // cav.setImagelocalpath("暂无"); // System.out.println(db.InsertSql(cav)); db.SelectSql("select * from cav limit 2"); } // 插入、删除、更新的方法是一样的,不一样的是数据库参数 public boolean InsertSql(CAVDto cav) { ConnectMysql(); try { //INSERT INTO `lobinary`.`cav` (`id`, `name`, `number`, `date`, `time`, `director`, `makers`, `publisher`, `series`, `type`, `actor`, `detailurl`, `imageurl`, `imagelocalpath`) VALUES ('1', 'testName', '1235', '日期', '时间', '导演', '制造商', '出版商', '系列号', '类型', '演员', '详细地址', '图片地址', '本地图片位置'); insql = "insert into cav(name, number, date, time, director, makers, publisher, series, type, actor, detailurl, imageurl, imagelocalpath)" + " values(?,?,?,?,?,?,?,?,?,?,?,?,?)"; // 上面的方法比下面的方法有优势,一方面是安全性,另一方面我忘记了…… // insql="insert into user(userid,username,password,email) values(user.getId,user.getName,user.getPassword,user.getEmail)"; PreparedStatement ps = conn.prepareStatement(insql); // .preparedStatement(insql); // PreparedStatement ps=(PreparedStatement) // conn.prepareStatement(insql); ps.setString(1, cav.getName()); ps.setString(2, cav.getNumber()); ps.setString(3, cav.getDate()); ps.setString(4, cav.getTime()); ps.setString(5, cav.getDirector()); ps.setString(6, cav.getMakers()); ps.setString(7, cav.getPublisher()); ps.setString(8, cav.getSeries()); ps.setString(9, cav.getType()); ps.setString(10, cav.getActor()); ps.setString(11, cav.getDetailurl()); ps.setString(12, cav.getImageurl()); ps.setString(13, cav.getImagelocalpath()); int result = ps.executeUpdate(); // ps.executeUpdate();无法判断是否已经插入 if (result > 0){ // System.out.println(cav.getName() + "插入结果为:" + result); return true; } } catch (Exception e) { e.printStackTrace(); } return false; } // 与其他操作相比较,查询语句在查询后需要一个查询结果集(ResultSet)来保存查询结果 public List<CAVDto> SelectSql(String sql) { List<CAVDto> cavList = new ArrayList<CAVDto>(); try { ConnectMysql(); Statement statement = conn.createStatement(); rs = statement.executeQuery(sql); while (rs.next()) { long id = rs.getInt("id"); String name = rs.getString("name"); String number = rs.getString("number"); String date = rs.getString("date"); String time = rs.getString("time"); String director = rs.getString("director"); String makers = rs.getString("makers"); String publisher = rs.getString("publisher"); String series = rs.getString("series"); String type = rs.getString("type"); String actor = rs.getString("actor"); String detailurl = rs.getString("detailurl"); String imageurl = rs.getString("imageurl"); String imagelocalpath = rs.getString("imagelocalpath"); CAVDto cav = new CAVDto(); cav.setId(id); cav.setName(name); cav.setNumber(number); cav.setDate(date); cav.setTime(time); cav.setDirector(director); cav.setMakers(makers); cav.setPublisher(publisher); cav.setSeries(series); cav.setType(type); cav.setActor(actor); cav.setDetailurl(detailurl); cav.setImageurl(imageurl); cav.setImagelocalpath(imagelocalpath); cavList.add(cav); } } catch (Exception e) { e.printStackTrace(); } return cavList; } public boolean UpdateSql(String upsql) { try { ConnectMysql(); PreparedStatement ps = conn.prepareStatement(upsql); int result = ps.executeUpdate();// 返回行数或者0 if (result > 0) return true; } catch (SQLException ex) { ex.printStackTrace(); // Logger.getLogger(ConnectDatabase.class.getName()).log(Level.SEVERE, null, ex); } return false; } public boolean DeletSql(String delsql) { try { PreparedStatement ps = conn.prepareStatement(upsql); int result = ps.executeUpdate(delsql); if (result > 0) return true; } catch (SQLException ex) { // Logger.getLogger(ConnectDatabase.class.getName()).log(Level.SEVERE, null, ex); } return false; } }<file_sep>package com.lobinary.normal.cav.service; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.lobinary.normal.cav.dao.CAVDao; import com.lobinary.normal.cav.dto.CAVDto; import com.lobinary.normal.cav.util.HttpUtil; public class WebService { public CAVDao cavDao = new CAVDao(); public int start = 1642; public int end = 5244; public int threadNum = 1; public void service() throws SocketTimeoutException{ for(int thread = 1;thread <= threadNum;thread++){ new Thread(){ @Override public void run() { while(true){ int pageNum = getPageNum(); boolean isSuccess = false; int times = 1; while(!isSuccess){ long startTime = System.currentTimeMillis(); try { isSuccess = go(pageNum); } catch (SocketTimeoutException e) { // e.printStackTrace(); } long endTime = System.currentTimeMillis(); System.out.println("第" + pageNum +"页处理,第" + times + "次执行" + (endTime-startTime) + "毫秒,结果为:" + isSuccess); times ++; } } } }.start(); } // String test = "alt=\"蜜のめぐり逢い 森下まゆみ\" src=\"http://pics.dmm.co.jp/digital/video/oae00091/oae00091ps.jpg"; // System.out.println(test.substring(test.indexOf("src=\"") + 5)); // System.out.println(cl.get(1)); } public synchronized int getPageNum(){ start = start + 1; return start - 1; } public boolean go(int i) throws SocketTimeoutException{ try { // Thread.sleep(5000); List<String> cl = catchDataFromWebsite(i); for(String s:cl){ boolean result = cavDao.insert(analysisData(s)); } return true; } catch (Exception e) { // e.printStackTrace(); return false; } } public CAVDto analysisData(String s){ CAVDto cav = new CAVDto(); // System.out.println(s); String name = s.substring(s.indexOf("title=\"") + 7, s.indexOf("\" target=\"_blank\">")); cav.setName(name); cav.setNumber(catchStringFromString(s, "番号:</span>", "</li>")); cav.setDate(catchStringFromString(s, "发行时间:</span>", "</li>")); cav.setTime(catchStringFromString(s, "影片时长:</span>", "</li>")); cav.setDirector(catchStringFromString(s, "的所有作品\">", "</a></li>")); String makers = catchStringFromString(s, "制作商:", "<li><span class=\"classTitle\">发行商"); cav.setMakers(catchStringFromString(makers, "的所有作品\">", "</a></li>")); String publisher = catchStringFromString(s, "发行商:", "<li><span class=\"classTitle\">系列:"); cav.setPublisher(catchStringFromString(publisher, "的所有作品\">", "</a></li>")); cav.setSeries(catchStringFromString(s, "系列:</span>", "</li>")); String type = catchStringFromString(s, "影片类别:</span>", "</li>"); String[] types = type.split("</a>"); String tpyeTemp = ""; for(String t :types){ if(t.contains(">")){ tpyeTemp = tpyeTemp + t.substring(t.indexOf(">") + 1) + ";"; }else{ // System.out.println("无效t:" + t); } } cav.setType(tpyeTemp); String actorTemp = ""; if(s.contains("#888888;\">")){ String[] actors = s.split("#888888;\">"); for(String a :actors){ if(a.contains("番号")){ // System.out.println("顶端数据,予以pass"); }else{ actorTemp = actorTemp + a.substring(0,a.indexOf("</span>")) + ";"; } } }else{ // System.out.println("未发现演员"); } cav.setActor(actorTemp); cav.setDetailurl(s.substring(s.indexOf("<a href=\"") + 9, s.indexOf("\" title=\""))); String imageUrl = catchStringFromString(s, "<img", "/></a>").replace("\"", "").replace(" ", ""); cav.setImageurl(imageUrl.substring(imageUrl.indexOf("src=\"") + 5)); cav.setImagelocalpath(""); return cav; } /** * 捕获数据从网站 * @return * @throws SocketTimeoutException */ public List<String> catchDataFromWebsite(int page) throws SocketTimeoutException{ List<String> contentsList = new ArrayList<String>(); Map<String,String> paramMap = new HashMap<String,String>(); //http://instsee.com/default.aspx?time=published&p1= //http://instsee.com/default.aspx?time=published&p1=&page=2 //http://instsee.com/default.aspx?time=published&p1=&page=3 String s = HttpUtil.sendPostRequest("http://instsee.com/default.aspx?time=published&p1=&page=" + page, paramMap, "UTF-8", "UTF-8"); String contentStr = ""; try { contentStr = s.substring(s.indexOf("<div id=\"list_games\">")); } catch (Exception e) { // System.out.println("发生错误:网站返回数据为:"); // System.out.println(s); } contentStr = contentStr.substring(0, contentStr.indexOf("<div id=\"listpager\" class=\"pagination\">")); String[] contents = contentStr.split("<div class=\"list_game\">"); // System.out.println(contents[0]); // System.out.println("========================="); // System.out.println(contents[19]); for(String content:contents){ if(content.contains("番号")){ contentsList.add(content); } } // System.out.println("从" + contents.length + "条数据中获取到" + contentsList.size() + "条有效数据"); return contentsList; } public static void main(String[] args) throws SocketTimeoutException { WebService ws = new WebService(); ws.service(); } /** * 从字符串中根据前后缀,获取中间字符串 * @param pre * @param rear */ public static String catchStringFromString(String str,String pre,String rear) { String result = ""; try { int start = str.indexOf(pre); int end = start + str.substring(start).indexOf(rear); if(start<end){ result = str.substring(start+pre.length(),end); } } catch (Exception e) { System.out.println("从字符串中捕获参数异常,异常原因为:" + e); } return result; } } <file_sep>package com.boce.test; import java.util.ArrayList; import java.util.List; /** * 本测试用于证明传入方法体中的List在方法体中如果被改变,是否外部参数会随着改变 * 实验证明,改变方法体中传入的list,外部的list也会跟着改变 * @author Boce * */ public class ListTest { public static void main(String[] args) { ListTest lt = new ListTest(); List<User> userList = new ArrayList<User>(); User u = new User(); u.setName("boce"); u.setAge(8); userList.add(u); System.out.println(userList.get(0).getName()); List<User> userListed = lt.changeList(userList); System.out.println(userList.get(0).getName()); System.out.println(userListed.get(0).getName()); } public List<User> changeList(List<User> list){ list.get(0).setName("changed"); return list; } } <file_sep>package com.lobinary.apc.constants; /** * * <pre> * 状态码常量类 * * 状态码分配规则: * 123456 状态码长度为6位 * 1代表所属类别 * 23代表所属子类别 [00为公共 ] * 4代表状态码属性 [1.状态型 4.异常型] * 56代表子变量 * * </pre> * @author lobinary * @since 2015年10月11日 下午10:16:54 * @version V1.0.0 描述 : 创建该文件 * */ public enum CodeDescConstants { //1***** 公共状态码 //1004** 公用公共状态码 PUB_SYSTEM_EXCEPTION("100400","系统异常"), //1011** 公用状态码 PUB_DEALING("101100","处理中"), PUB_DEAL_SUCCESS("101101","处理成功"), PUB_DEAL_FAIL("101102","处理失败"), PUB_SUBMIT_SUCCESS("101103","提交成功"), PUB_SUBMIT_FAIL("101104","提交失败"), PUB_UPLOAD_SUCCESS("101105","上传成功"), PUB_UPLOAD_FAIL("101106","上传失败"), //2***** 业务型状态码 //2001** 业务公共 状态码 SERVICE_EXECUTE_SUCCESS("200101","业务执行成功"), //2004** 业务公共 异常码 SERVICE_NULL_BUSINESS("200401","无此业务"), //3***** 远程信息交互状态码 //4***** 数据库状态码 //5***** //9***** 工具类状态码 //901*** 文件类状态码 FILE_EXCEPTION("901400","文件工具类异常"), //90140* ~ 90144* 找文件型异常 FILE_READ_EXCEPTION("901401","读取文件内容发生未知错误"), FILE_READ_UNFOUNT("901402","文件未找到"), //90145* ~ 90149* 写文件型异常 FILE_WRITE_EXCEPTION("901450","写入文件内容发生未知错误"), //902*** 日期类状态码 DATE_EXCEPTION("902400","日期工具类异常"), //903*** 字符串类状态码 //904*** 数字类状态码 ; ; private String code; //响应码 private String desc; //响应描述 private CodeDescConstants(String code,String desc){ this.code=code; this.desc=desc; } public String getCode(){ return code; } public String getDesc(){ return desc; } }
d196fe08b1f103b904b3ce12ca71efd24291d015
[ "Java" ]
4
Java
ljrxxx/Lobinary
9252798dceaad84f745888fef21b21269cc611e1
f93e6f6a40c70765ef48de8a22684a22fda9af54
refs/heads/master
<repo_name>getsolus/plasma-desktop-branding<file_sep>/mkrelease.sh #!/bin/bash set -e rm -rf build meson --prefix /usr build ninja dist -C build # Bump in tandem with meson.build, run script once new tag is up. VERSION="4" TAR="plasma-desktop-branding-${VERSION}.tar.xz" mv build/meson-dist/$TAR . # Automatically sign the tarball with GPG key of user running this script gpg --armor --detach-sign $TAR gpg --verify "${TAR}.asc" <file_sep>/solus-desktoptheme/Solus/layout-templates/solus.desktop.defaultPanel/contents/layout.js // This is based on the Plasma default panel which is licensed under LGPLv2+ var panel = new Panel var panelScreen = panel.screen var freeEdges = {"bottom": true, "top": true, "left": true, "right": true} for (i = 0; i < panelIds.length; ++i) { var tmpPanel = panelById(panelIds[i]) if (tmpPanel.screen == panelScreen) { if (tmpPanel.id != panel.id) { freeEdges[tmpPanel.location] = false; } } } if (freeEdges["bottom"] == true) { panel.location = "bottom"; } else if (freeEdges["top"] == true) { panel.location = "top"; } else if (freeEdges["left"] == true) { panel.location = "left"; } else if (freeEdges["right"] == true) { panel.location = "right"; } else { panel.location = "top"; } panel.height = 2 * Math.floor(gridUnit * 2.5 / 2) const maximumAspectRatio = 21/9; if (panel.formFactor === "horizontal") { const geo = screenGeometry(panelScreen); const maximumWidth = Math.ceil(geo.height * maximumAspectRatio); if (geo.width > maximumWidth) { panel.alignment = "center"; panel.minimumLength = maximumWidth; panel.maximumLength = maximumWidth; } } var kicker = panel.addWidget("org.kde.plasma.kicker") kicker.currentConfigGroup = ["Shortcuts"] kicker.writeConfig("global", "Alt+F1") panel.addWidget("org.kde.plasma.pager") panel.addWidget("org.kde.plasma.icontasks") panel.addWidget("org.kde.plasma.marginsseparator") var langIds = ["as", // Assamese "bn", // Bengali "bo", // Tibetan "brx", // Bodo "doi", // Dogri "gu", // Gujarati "hi", // Hindi "ja", // Japanese "kn", // Kannada "ko", // Korean "kok", // Konkani "ks", // Kashmiri "lep", // Lepcha "mai", // Maithili "ml", // Malayalam "mni", // Manipuri "mr", // Marathi "ne", // Nepali "or", // Odia "pa", // Punjabi "sa", // Sanskrit "sat", // Santali "sd", // Sindhi "si", // Sinhala "ta", // Tamil "te", // Telugu "th", // Thai "ur", // Urdu "vi", // Vietnamese "zh_CN", // Simplified Chinese "zh_TW"] // Traditional Chinese if (langIds.indexOf(languageId) != -1) { panel.addWidget("org.kde.plasma.kimpanel"); } panel.addWidget("org.kde.plasma.systemtray") panel.addWidget("org.kde.plasma.minimizeall") panel.addWidget("org.kde.plasma.digitalclock") <file_sep>/env/50-solus-defaults.sh # Begin /usr/share/xdg/plasma-workspace/env/50-solus-defaults.sh # Load agent if it isn't already if [ -z "${SSH_AGENT_PID}" ]; then eval `ssh-agent -s` fi # Set ksshaskpass as the SSH_ASKPASS client if [ -f /usr/bin/ksshaskpass ]; then export SSH_ASKPASS="/<PASSWORD>" fi # End /usr/share/xdg/plasma-workspace/env/50-solus-defaults.sh
0098943e09eb9286d87febc410363ecad9d477d3
[ "JavaScript", "Shell" ]
3
Shell
getsolus/plasma-desktop-branding
3a698b5b62cdfa8bd5ee8bcca2b33e4371ea15b8
edf8c39b3cb70576f6f45efa1ec44a57ee6269ea
refs/heads/master
<file_sep>import React, {useEffect} from 'react'; import PropTypes from 'prop-types'; import {useDispatch, useSelector} from 'react-redux'; import CardItem from './components/CartItem'; import { Grid, Typography, Card, CardHeader, CardContent, CardMedia, } from '@material-ui/core'; import {addToCart, removeFromCart} from '../../actions/cartActions'; const Cart = ({match, location, history}) => { const productId = match.params.id; const qty = location.search ? Number (location.search.split ('=')[1]) : 1; //grabs qty data from route const dispatch = useDispatch (); const cart = useSelector (state => state.cart); const {cartItems} = cart; useEffect ( () => { if (productId) { dispatch (addToCart (productId, qty)); } }, [dispatch, productId, qty] ); const removeFromCartHandler = id => { dispatch (removeFromCart (id)); }; // const checkoutHandler = () => { // history.push('/login?redirect=shipping') // } // const cartTotal = cartItems // .map (item => { // return item.sale_price * item.qty; // }) // .reduce ((a, b) => { // return a + b; // }); const getCartTotal = () => { let totalsArray = cartItems.map (item => { return item.sale_price * item.qty; }); const sum = (acc, val) => { return acc + val; }; const cartTotal = totalsArray.reduce (sum, 0); return cartTotal; }; const showCartItems = cartItems.map (item => { return ( <Grid item sm={4} key={item.product_id}> <CardItem name={item.name} img={item.product_img} description={item.description} sale_price={item.sale_price} rating={item.rating} qty={item.qty} onClick={() => removeFromCartHandler (item.product_id)} /> </Grid> ); }); return ( <Grid> <Grid> <Typography> Cart </Typography> </Grid> <Grid container> {showCartItems} </Grid> <Grid container> <Typography> Total Cost:{getCartTotal ()} </Typography> </Grid> </Grid> ); }; Cart.propTypes = {}; export default Cart; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import {Header, Footer} from '../../layout-components'; import {makeStyles} from '@material-ui/styles'; const useStyles = makeStyles (theme => ({ main: { minHeight: '90vh', // marginLeft: '10vw', // marginRight: '10vw', // marginTop: '5vh', }, })); const LandingLayout = ({children}) => { const classes = useStyles (); return ( <div> <Header /> <main className={classes.main}> {children} </main> <Footer /> </div> ); }; LandingLayout.propTypes = { children: PropTypes.node, }; export default LandingLayout; <file_sep>export const imageOne = 'https://res.cloudinary.com/ddj5orpun/image/upload/v1604023269/the-shop/alf-williamsen-e_IP-9e7-Rs-unsplash_3_hmroq4_ilimpg_bgvgw0.jpg'; export const imageTwo = 'https://res.cloudinary.com/ddj5orpun/image/upload/v1604017094/the-shop/alf-williamsen-e_IP-9e7-Rs-unsplash_2_kv4zku.jpg'; export const imageThree = 'https://res.cloudinary.com/ddj5orpun/image/upload/v1604019239/the-shop/sebastian-pociecha-5eUO24bIIqY-unsplash_po7f96.jpg'; export const imageFour = 'https://res.cloudinary.com/ddj5orpun/image/upload/v1604022699/the-shop/alf-williamsen-e_IP-9e7-Rs-unsplash_3_hmroq4_1_fkxfes.jpg'; export const imageFive = 'https://res.cloudinary.com/ddj5orpun/image/upload/v1604520667/the-shop/matt-rogers-9NcMCSLYGtA-unsplash_jdptwo.jpg'; <file_sep>import {createStore, combineReducers, applyMiddleware} from 'redux'; import thunk from 'redux-thunk'; import {composeWithDevTools} from 'redux-devtools-extension'; import { productListReducer, productDetailsReducer, } from './reducers/productReducers'; import {cartReducer} from './reducers/cartReducers'; const reducer = combineReducers ({ productList: productListReducer, productDetails: productDetailsReducer, cart: cartReducer, }); const cartItemsFromStorage = localStorage.getItem ('cartItems') ? JSON.parse (localStorage.getItem ('cartItems')) : []; //stores items in cart into store const initialState = { cart: { cartItems: cartItemsFromStorage, }, }; const middleware = [thunk]; const store = createStore ( reducer, initialState, composeWithDevTools (applyMiddleware (...middleware)) ); export default store; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import {CircularProgress, Grid, Typography} from '@material-ui/core'; import {makeStyles} from '@material-ui/styles'; const useStyles = makeStyles (theme => ({ root: { marginTop: '40vh', }, })); const LoadingSpinner = props => { const classes = useStyles (); return ( <Grid className={classes.root} container direction="row" justify="center" alignItems="center" > <CircularProgress /> </Grid> ); }; LoadingSpinner.propTypes = {}; export default LoadingSpinner; <file_sep>export {default as Main} from './Main'; export {default as LandingLayout} from './LandingLayout'; <file_sep>import React, {useEffect, useState} from 'react'; import PropTypes from 'prop-types'; import {useDispatch, useSelector} from 'react-redux'; import {useParams} from 'react-router-dom'; import {getProductDetails} from '../../actions/productActions'; import {makeStyles} from '@material-ui/styles'; import { Grid, Typography, Card, CardHeader, CardContent, CardMedia, Fade, Button, Select, FormControl, MenuItem, InputLabel, TextField, } from '@material-ui/core'; import LoadingSpinner from '../../components/LoadingSpinner'; const useStyles = makeStyles (theme => ({ card: {}, img: { height: '65vh', }, formControl: { margin: theme.spacing (2), minWidth: 120, }, })); const Product = ({history, match}) => { const [qty, setQty] = useState (1); const {id} = useParams (); const classes = useStyles (); const dispatch = useDispatch (); useEffect ( () => { dispatch (getProductDetails (id)); }, [dispatch, id] ); const {loading, error, product} = useSelector (state => state.productDetails); const addToCartHandler = () => { history.push(`/cart/${match.params.id}?qty=${qty}`) } return loading ? <LoadingSpinner /> : error ? <Typography>Error!</Typography> : <Grid container direction="row" spacing={2}> <Grid item md={8}> <Card className={classes.card}> <CardHeader title={product.name} /> {product.product_img ? <Fade in={true}> <CardMedia className={classes.img} image={product.product_img} /> </Fade> : <Grid className={classes.img} />} <CardContent> <Typography> {product.description} </Typography> </CardContent> </Card> </Grid> <Grid item md={4} container direction="column" spacing={2}> <Grid item> <Card> <CardHeader title="Sizes WIP" /> <CardContent> <Typography> 8 </Typography> <Typography> 9 </Typography> <Typography> 10 </Typography> </CardContent> </Card> </Grid> <Grid item> <Card> <CardContent> <Grid container direction="column"> <Grid> <Typography> Price: {product.sale_price} </Typography> </Grid> <Grid> <Typography> STATUS: IN STOCK </Typography> </Grid> <Grid> <TextField label="Qty" select variant="outlined" className={classes.formControl} value={qty} onChange={e => setQty (e.target.value)} > {[ ...Array (product.number_in_stock).keys (), ].map (x => ( <MenuItem key={x + 1} value={x + 1}> {x + 1} </MenuItem> ))} </TextField> </Grid> <Grid> <Button onClick={addToCartHandler}> <Typography> ADD TO CART </Typography> </Button> </Grid> </Grid> </CardContent> </Card> </Grid> </Grid> </Grid>; }; Product.propTypes = {}; export default Product; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import {makeStyles} from '@material-ui/styles'; import { Grid, Typography, Card, CardHeader, CardContent, CardMedia, Button, CardActionArea, // Divider, } from '@material-ui/core'; const useStyles = makeStyles (theme => ({ img: { height: '50vh', }, })); const Item = ({id, name, img, description, sale_price, onClick, children}) => { const classes = useStyles (); return ( <Card className={classes.card}> <CardActionArea onClick={onClick}> <CardHeader title={name} /> <CardMedia className={classes.img} image={img} /> <CardContent> <Typography> {sale_price} </Typography> </CardContent> </CardActionArea> {children} </Card> ); }; Item.propTypes = {}; export default Item; <file_sep>import React, {useEffect} from 'react'; import {Router} from 'react-router-dom'; import {createBrowserHistory} from 'history'; import {ThemeProvider} from '@material-ui/styles'; // import validate from 'validate.js'; //redux import {Provider} from 'react-redux'; // import store from './store'; // import {loadUser} from './actions/auth'; // import setAuthToken from './utils/setAuthToken'; import theme from './theme'; import 'react-perfect-scrollbar/dist/css/styles.css'; // import './assets/scss/index.scss'; // import validators from './common/validators'; import Routes from './Routes'; const browserHistory = createBrowserHistory (); const App = () => { // useEffect(() => { // setAuthToken(localStorage.token) // store.dispatch(loadUser()) // }, []) return ( <ThemeProvider theme={theme}> <Router history={browserHistory}> <Routes /> </Router> </ThemeProvider> ); }; export default App; /** * temp: * * <Provider store={store}> <ThemeProvider theme={theme}> <Router history={browserHistory}> <Routes /> </Router> </ThemeProvider> </Provider> * * */ <file_sep> export {default as Landing} from './Landing' export {default as Products} from './Products' export {default as Product} from './Product' export {default as Cart} from './Cart' <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import { Grid, Typography, Card, CardContent, CardMedia, Divider, Link, Button, } from '@material-ui/core'; import {makeStyles} from '@material-ui/styles'; // import {useSelector, useDispatch} from 'react-redux'; // import {useParams} from 'react-router-dom'; import {useHistory} from 'react-router-dom'; import { // imageOne, // imageTwo, // imageThree, // imageFour, imageFive, } from '../../constants/imageConstants'; const useStyles = makeStyles (theme => ({ landing: { maxWidth: '100vw', overflow: 'hidden', }, card: { backgroundColor: theme.palette.blueGrey.main, }, landingImage: { // background: 'linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5))', // backgroundSize: 'cover', height: '95vh', }, overlay: { position: 'absolute', // top: '13vh', bottom: '1px', paddingLeft: '70%', height: '100vh', }, relativeGrid: { position: 'relative', }, overlayTagline: { display: 'flex', flexDirection: 'row', justifyContent: 'center', alignItems: 'center', width: '400px', height: '100px', opacity: '90%', }, overlayText: { display: 'flex', flexDirection: 'row', justifyContent: 'center', alignItems: 'center', background: 'white', width: '300px', height: '100px', opacity: '75%', }, })); const Landing = props => { const classes = useStyles (); let history = useHistory (); const routeToProducts = () => { history.push (`/products`); }; return ( <Grid className={classes.landing}> <Grid container direction="column"> <Card className={classes.relativeGrid}> <CardMedia className={classes.landingImage} image={imageFive} /> <Grid container direction="column" justify="center" alignItems="center" className={classes.overlay} > <Grid> <Typography variant="h1" color="textSecondary" className={classes.overlayTagline} > Walking on air... </Typography> </Grid> <Grid> <Link onClick={routeToProducts}> <Button> <Typography variant="h3" color="textPrimary" className={classes.overlayText} > BUY NOW </Typography> </Button> </Link> </Grid> </Grid> </Card> </Grid> <Grid container direction="column" justify="flex-start" alignItems="stretch" spacing={3} > <Grid item /> <Grid item> <Card className={classes.card}> <CardContent> <Typography variant="h1" color="textSecondary"> Bruh </Typography> </CardContent> </Card> </Grid> <Grid item> <Card className={classes.card}> <CardContent> <Typography variant="h1" color="textSecondary"> Bruh </Typography> </CardContent> </Card> </Grid> <Grid item /> </Grid> </Grid> ); }; Landing.propTypes = {}; export default Landing; <file_sep>import React, {useEffect} from 'react'; import {useDispatch, useSelector} from 'react-redux'; import {useHistory} from 'react-router-dom'; import {getProducts} from '../../actions/productActions'; import {makeStyles} from '@material-ui/styles'; import PropTypes from 'prop-types'; import { Grid, Typography, Box, // Card, // CardContent, // CardMedia, // Divider, } from '@material-ui/core'; import Item from '../../components/Item'; import LoadingSpinner from '../../components/LoadingSpinner'; const useStyles = makeStyles (theme => ({ root: {}, headerText: { paddingBottom: theme.spacing (3), }, })); const Products = props => { const classes = useStyles (); let history = useHistory (); const dispatch = useDispatch (); const {loading, error, products} = useSelector (state => state.productList); useEffect ( () => { dispatch (getProducts ()); }, [dispatch] ); const showProducts = products.map (product => { const routeToProduct = () => { history.push (`/products/${product.id}`); }; return ( <Grid item sm={4} key={product.id}> <Item name={product.name} img={product.product_img} description={product.description} sale_price={product.sale_price} rating={product.rating} onClick={routeToProduct} /> </Grid> ); }); return ( <Grid className={classes.root}> <Box className={classes.headerText}> <Typography variant="h1"> Latest Products </Typography> </Box> {loading ? <LoadingSpinner /> : error ? <Typography>Error!!</Typography> : <Grid container direction="row" spacing={2}> {showProducts} </Grid>} </Grid> ); }; Products.propTypes = {}; export default Products; <file_sep>import axios from 'axios'; import { CART_ADD_ITEM, CART_REMOVE_ITEM, CART_SAVE_SHIPPING_ADDRESS, CART_SAVE_PAYMENT_METHOD, } from '../constants/cartConstants'; export const addToCart = (id, qty) => async (dispatch, getState) => { const {data} = await axios.get (`/api/v1/products/${id}`); dispatch ({ type: CART_ADD_ITEM, payload: { product_id: data.id, name: data.name, product_img: data.product_img, sale_price: data.sale_price, number_in_stock: data.number_in_stock, qty, }, }); localStorage.setItem ( 'cartItems', JSON.stringify (getState ().cart.cartItems) ); }; export const removeFromCart = id => (dispatch, getState) => { dispatch ({ type: CART_REMOVE_ITEM, payload: id, }); localStorage.setItem ( 'cartItems', JSON.stringify (getState ().cart.cartItems) ); }; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import {makeStyles} from '@material-ui/styles'; import {useHistory} from 'react-router-dom'; import Box from '@material-ui/core/Box'; import Container from '@material-ui/core/Container'; import { Grid, Button, AppBar, Toolbar, Typography, CssBaseline, useScrollTrigger, } from '@material-ui/core'; import ShoppingCartIcon from '@material-ui/icons/ShoppingCart'; import PersonIcon from '@material-ui/icons/Person'; const useStyles = makeStyles (theme => ({ appBar: { backgroundColor: theme.palette.white, }, })); function ElevationScroll (props) { const {children} = props; // Note that you normally won't need to set the window ref as useScrollTrigger // will default to window. // This is only being set here because the demo is in an iframe. const trigger = useScrollTrigger ({ disableHysteresis: true, threshold: 0, }); return React.cloneElement (children, { elevation: trigger ? 4 : 0, }); } const Header = props => { let history = useHistory (); const routeToCart = () => { history.push (`/cart`); }; const classes = useStyles (); return ( <React.Fragment> <CssBaseline /> <ElevationScroll {...props}> <AppBar className={classes.appBar}> <Toolbar> <Grid container justify="flex-end" spacing={2}> <Grid item> <Button onClick={routeToCart}> <ShoppingCartIcon /> </Button> </Grid> <Grid item> <Button> <PersonIcon /> </Button> </Grid> </Grid> </Toolbar> </AppBar> </ElevationScroll> <Toolbar /> </React.Fragment> ); }; Header.propTypes = {}; export default Header;
944fc49230268a6b0f21b050b29d0bc3bcd4942f
[ "JavaScript" ]
14
JavaScript
tvo007/the-shop-fe
1081ffe02d32bc59ee5db3f314cefafccc47baf2
f957e38ae2ae0a231e9892899196612c88dc3a8c
refs/heads/master
<repo_name>tranvuongduy2003/express-lesson<file_sep>/controller/product.controller.js var db = require('../db'); module.exports.products = function(req, res) { var page = parseInt(req.query.page) || 1; var perPage = 8; var dropQuantity = (page - 1)*perPage; if (page === 1) { var hidePrevious = "disabled"; ++page; } if ((page + 1)*perPage >= db.get('products').value().length) { var hideNext = "disabled"; } if (page*perPage >= db.get('products').value().length) { --page; } res.render('products/index', { products: db.get('products').drop(dropQuantity).take(perPage).value(), page: page, hidePrevious: hidePrevious, hideNext: hideNext }); }
f6cf60cfcd2f264206e14c8519072e305ed716bb
[ "JavaScript" ]
1
JavaScript
tranvuongduy2003/express-lesson
21eec085cb503895c9b130558625410893e3164d
af7901fbc98b8abcd4887274144117d0260c8cdf