Search Results

Search found 1175 results on 47 pages for 'robert mao'.

Page 5/47 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • bash: how to know NUM option in grep -A -B "on the fly" ?

    - by Michael Mao
    Hello everyone: I am trying to analyze my agent results from a collection of 20 txt files here. If you wonder about the background info, please go see my page, what I am doing here is just one step. Basically I would like to take only my agent's result out of the messy context, so I've got this command for a single file: cat run15.txt | grep -A 50 -E '^Agent Name: agent10479475' | grep -B 50 '^==' This means : after the regex match, continue forward by 50 lines, stop, then match a line separator starts with "==", go back by 50 lines, if possible (This would certainly clash the very first line). This approach depends on the fact that the hard-coded line number counter 50, would be just fine to get exactly one line separator. And this would not work if I do the following code: cat run*.txt | grep -A 50 -E '^Agent Name: agent10479475' | grep -B 50 '^==' The output would be a mess... My question is: how to make sure grep knows exactly when to stop going forward, and when to stop getting backward? Any suggestion or hint is much appreciated.

    Read the article

  • [Java] Nested methods vs "piped" methods, which is better?

    - by Michael Mao
    Hi: Since uni, I've programming in Java for 3 years, although I am not fully dedicated to this language, I have spent quite some time in it, nevertheless. I understand both ways, just curious which style do you prefer. public class Test{ public static void main(String[] args) { System.out.println(getAgent().getAgentName()); } private static Agent getAgent() { return new Agent(); }} class Agent{ private String getAgentName() { return "John Smith"; }} I am pretty happy with nested method calls such like the following public class Test{ public static void main(String[] args) { getAgentName(getAgent()); } private static void getAgentName(Agent agent) { System.out.println(agent.getName()); } private static Agent getAgent() { return new Agent(); }} class Agent { public String getName(){ return "John Smith"; }} They have identical output I saw "John Smith" twice. I wonder, if one way of doing this has better performance or other advantages over the other. Personally I prefer the latter, since for nested methods I can certainly tell which starts first, and which is after. The above code is but a sample, The code that I am working with now is much more complicated, a bit like a maze... So switching between the two styles often blows my head in no time.

    Read the article

  • How to use the correct Google OpenID url to login to my site?

    - by Michael Mao
    Hello everyone: I am trying to implement OpenID as one preferred option to my next web app here The code is taken from this tutorial and works if I use my openID from myopenid.com However, I believe most people would just love to use their everyday email address as their openID, as far as I know, Google, Yahoo, and some other big players have already done this in their systems. My question is: how could I find the correct "url" to enter in the form to login? I used my Google OpenID account for StackOverflow and it works just fine. I try to copy my openID like this: www.google.com/accounts/o8/id?id=aitoawllano10bzdzp3ht0diffry0qt6_j2ls-m And paste it directly into my form, but it doesn't work. I also tried to remove the url parameter, but that won't do, either. Thanks a lot in advance for any tips and suggestions.

    Read the article

  • AccessControlException: access denied - caller function failed to load properties file

    - by Michael Mao
    Hi all: I am having a jar archive environment which is gonna call my class in a folder like this: java -jar "emarket.jar" ../tournament 100 My compiled class is deployed into the ../tournament folder, this command runs well. After I changed my code to load a properties file, it gets the following exception message: Exception in thread "main" java.security.AccessControlException: access denied (java.io.FilePermission agent.properties read) at java.security.AccessControlContext.checkPermission(Unknown Source) at java.security.AccessController.checkPermission(Unknown Source) at java.lang.SecurityManager.checkPermission(Unknown Source) at java.lang.SecurityManager.checkRead(Unknown Source) at java.io.FileInputStream.<init>(Unknown Source) at java.io.FileInputStream.<init>(Unknown Source) at Agent10479475.getPropertiesFromConfigFile(Agent10479475.java:110) at Agent10479475.<init>(Agent10479475.java:100) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at java.lang.Class.newInstance0(Unknown Source) at java.lang.Class.newInstance(Unknown Source) at emarket.client.EmarketSandbox.instantiateClientObjects(EmarketSandbox.java:92) at emarket.client.EmarketSandbox.<init>(EmarketSandbox.java:27) at emarket.client.EmarketSandbox.main(EmarketSandbox.java:166) I am wondering why this security checking will fail. I issue the getPropertitiesFromConfigFile() function inside my class's default constructor, like this: public class Agent10479475 extends AbstractClientAgent { //default constructor public Agent10479475() { //set all properties to their default values in constructor FT_THRESHOLD = 400; FT_THRESHOLD_MARGIN = 50; printOut("Now loading properties from a config file...", ""); getPropertiesFromConfigFile(); printOut("Finished loading",""); } private void getPropertiesFromConfigFile() { Properties props = new Properties(); try { props.load(new FileInputStream("agent.properties")); FT_THRESHOLD = Long.parseLong(props.getProperty("FT_THRESHOLD")); FT_THRESHOLD_MARGIN = Long.parseLong(props.getProperty("FT_THRESHOLD_MARGIN ")); } catch(java.io.FileNotFoundException fnfex) { printOut("CANNOT FIND PROPERTIES FILE :", fnfex); } catch(java.io.IOException ioex) { printOut("IOEXCEPTION OCCURED :", ioex); } } } My class is loading its own .properties file under the same folder. why would the Java environment complains about such a denial of access? Must I config the emarket.client.EmarketSandbox class, which is not written by me and stored inside the emarket.jar, to access my agent.properties file? Any hints or suggestions is much appreciated. Many thanks in advance.

    Read the article

  • CSS precedence order? My lecture slides are correct or not?

    - by Michael Mao
    Hi all: I've noticed that there are a couple of similar questions and answers at SO already, but let me clarify my specific question here first: I've got lecture slides which states like this: To be frank, I haven't heard of this rule of css precedence myself, and I googled to find something with similar topic but not quite like that : here To have a test myself, I've made a test page on my own server here After running it on FireFox 3.6.3, I am sure it does not show the way as it should be, according to the statement in lecture slides: imported stylesheet ? am I doing it wrong? I cannot see its effect using FireBug it says that embedded stylesheet has a higher precedence over linked/imported stylesheets, however, it doesn't work, if I put the linked/imported tag AFTER that. inline style vs html attributes ? I've got an image where I firstly set its inline style to control the width and height, then use direct html attributes width/height to try modifying that, but failed... Below is the source code : <html> <head> <style type="text/css"> #target { border : 2px solid green; color : green; } </style> <link rel="stylesheet" href="./linked.css" type="text/css" media="screen" /> </head> <body> <div id="target">A targeted div tag on page.</div> <img src="cat.jpg" alt="" style="width : 102px; height : 110px;" width="204px" height="220px" /> </body> </html> Can any experienced CSS guys help me figure out if the slide is correct or not? Frankly speaking, I am puzzled myself, as I can clearly see some other "incorrect" statements here and there amongst the slides, such as JavaScript is on client-side (how about server-side JavaScript?) and "Embedded styles are in the head section of a web page "(what the heck? I am not allowed to put it inside the body tag?) Sorry about this silly question, the exam is on TOMORROW, and I now see a lot of things to think about :)

    Read the article

  • Cygwin bash syntax error - but script run perfectly well in Ubuntu

    - by Michael Mao
    #!/bin/bash if test "$#" == "4"; then echo "$*"; else echo "args-error" >&2; fi; This little code snippet troubles me a lot when I tried to run it on both Ubuntu and Cygwin. Ubuntu runs bash version 4.0+ whereas Cygwin runs 3.2.49; But I reckon version collision shall not be the cause of this, this code runs well under fedora 10 which is also using bash version 3.+ So basically I am wondering if there is a way to code my script once and for all so there are not to have this awful issue later on. Many thanks in advance.

    Read the article

  • Use Java Annotation not to run a method

    - by Michael Mao
    Hi all: I've got a method in my class only for testing purpose : private void printOut(String msg, Object value) { System.out.println(msg + value); } It is a wrapper method for System.out.println(); So I hope, with the use of Annotation, I can choose not to run this method during productive environment while still keep those diagnostic output ready if I am to switch back to debugging environment. Which Annotation shall I put on top of the method name?

    Read the article

  • Problem to generate nested ul lists using PHP

    - by Michael Mao
    Hi all: I am working on a front-end web app where a nested unordered list would be used for the jQuery plugin mcdropdown. Here is the data structure from PHP: a nested array of arrays : Array ( [0] => Array ( [fullpath] => ../foil/alphanumeric/ [depth] => 0 ) [1] => Array ( [fullpath] => ../foil/alphanumeric/letters/ [depth] => 1 ) [2] => Array ( [fullpath] => ../foil/alphanumeric/numbers/ [depth] => 1 ) [3] => Array ( [fullpath] => ../foil/alphanumeric/numbers/symbols/ [depth] => 2 ) ) Basically, I took the excellent answer from this question on SO, modified it a bit : global $fullpaths; // $fullpaths contains the above data structure in print_r $result = ''; $currentDepth = -1; while(!empty($fullpaths)) { $currentNode = array_shift($fullpaths); if($currentNode['depth'] > $currentDepth) { $result .='<ul>'; } if($currentNode['depth'] < $currentDepth) { $result .=str_repeat('</ul>', $currentDepth - $currentNode['depth']); } $result .= '<li>'. $currentNode['fullpath'] .'</li>'; $currentDepth = $currentNode['depth']; if(empty($fullpaths)) { $result .= str_repeat('</ul>', 1 + $currentDepth); } } print $result; and got the following output: <ul> <li>../foil/alphanumeric/</li> <ul> <li>../foil/alphanumeric/letters/</li> <li>../foil/alphanumeric/numbers/</li> <ul> <li>../foil/alphanumeric/numbers/symbols/</li> </ul> </ul> </ul> Which cannot be accepted by the mcdropdown jQuery plugin, it expects something like this: <li rel="1"> 'Alphanumeric' <ul> <li rel="2">'Letters'</li> <li rel="3">'Numbers' <ul> <li rel="4">'Symbols'</li> </ul> </li> </ul> </li> To be frank, I don't quite understand how the answer from that question works, I have been trying to modify that solution to cope with my situation, but still failed. Any help and suggestion is much appropriated in advance.

    Read the article

  • HTML wrapper div over embedded flash object cannot be "clickable" by jQuery

    - by Michael Mao
    Hi all: I've been trying to do as the client requested : redirect to campaign page then to destination page once a customer clicks on the top banner in swf format. You can check what's been done at :http://ausdcf.org If you are using Firefox, Chrome or Safari, I suspect you can reach the destination page. However, if you are using IE or Opera, I doubt it. I think to cause of such a weird problem is: The swf ojbects don't have a link to url, SO I have to hack the theme template file like this : <div id="header">'; /* * A quick and dirty way to put some swf into PHP, and rotate among them ... */ //available banners $banners = array( 'http://localhost/smf/flash/banner_fertalign_1.swf', 'http://localhost/smf/flash/banner_fertalign_2.swf', 'http://localhost/smf/flash/banner_fertalign_3.swf' ); //get random banner srand((double) microtime() * 1000000); $rand = rand(0,count($banners)-1); echo '<div id="top_banner_clickable">'; echo '<div id="top_banner_wrapper">'; echo '<object width="400" height="60">'; echo '<param name="wmode" value="transparent">'; echo '<embed wmode="transparent" src="'.$banners[$rand].'" '; echo 'width="400" height="60" type="application/x-shockwave-flash"'; echo 'pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" />'; echo '</object>'; echo '</div>'; echo '</div>'; And the related jQuery code is like this: /* master.js */ $(document).ready(function() { $("#top_banner_clickable").click(function() { window.location ="http://ausdcf.org/campaign/"; }); }); I absolutely know nothing about Flash or embedded objects. I guess that's the cause of this problem. Plus, I don't know why it works with some browsers but not all... I even tried to add a z-index to the wrapper div in css like this: #top_banner_clickable { z-index : 100; } No this wouldn't do, either... Is there a way to go around this issue? Many thanks in advance.

    Read the article

  • Failed to obtain JDBC Driver for MySQL under Tomcat environment

    - by Michael Mao
    Hi all: I've been trying to obtain the Driver class for JDBC connection to MySQL. The workstation is running on Linux, Fedora 10. I have manually set up the classpath variable for Java by CLI like this: bash-3.2$ echo $CLASSPATH /home/cmao/public_html/jsp/mysql-connector-java-5.1.12-bin.jar This shows that I've added the lastest mysql connection jar archive to my CLASSPATH variable. I've created a test JSP page which can be found here And source code for this page is: <%@page language="java"%> <%@page import="java.sql.*"%> <%@page import="java.util.*"%> <html> <head> <title>UTS JDBC MySQL connection test page</title> </head> <body> <% Connection con = null; out.print("Java version is : " + System.getProperty("java.version") + "<br />"); out.print("Tomcat version is : " + application.getServerInfo() + "<br />"); out.print("Servlet version is: " + application.getMajorVersion() + "<br />"); out.print("JSP version is : " + JspFactory.getDefaultFactory().getEngineInfo().getSpecificationVersion() +"<br />"); //out.print("Java classpath is : " + System.getProperty("java.class.path")+ "<br />"); //out.print("JSP classpath is : " + appliaction.getAttribute("org.apache.catalina.jsp_classpath") + "<br />"); //out.print("Tomcat classpath is : " + System.getProperty("org.apache.tomcat.common.classpath") + "<br />"); try { Class c = Class.forName("com.mysql.jdbc.Driver"); } catch(Exception e) { out.println("Error! Failed to obtain JDBC driver for MySQL... Missing class \"com.mysql.jdbc.Driver\"<br />"); } %> </body> </html> None of those commented out line would work, various Jsper Expetions would be thrown. You can check those Error pages from the following links: classpath Error page catalina Error page tomcat Error page It seems, from my limited knowledge of JSP and Servlet, the Tomcat environment "ignores" my Java CLASSPATH? In which case I cannot configure the MySQL JDBC package to let my Servlets(a JSP is but a Servlet anyway) work. I am not sure how to fix this issue. would it be better if I use an IDE like Eclipse or NetBeans and create a real Java "web app" so that everything can be "self-configured" by the usage of a web.config XML configuration file? So that I can certainly bypass this Tomcat environment restriction? Many thanks for the suggestions in advance.

    Read the article

  • Simplest way to automatically alter "const" value in Java during compile time

    - by Michael Mao
    Hi all: This is a question corresponds to my uni assignment so I am very sorry to say I cannot adopt any one of the following best practices in a short time -- you know -- assignment is due tomorrow :( link to Best way to alter const in Java on StackOverflow Basically the only task (I hope so) left for me is the performance tuning. I've got a bunch of predefined "const" values in my single-class agent source code like this: //static final values private static final long FT_THRESHOLD = 400; private static final long FT_THRESHOLD_MARGIN = 50; private static final long FT_SMOOTH_PRICE_IDICATOR = 20; private static final long FT_BUY_PRICE_MODIFIER = 0; private static final long FT_LAST_ROUNDS_STARTTIME = 90; private static final long FT_AMOUNT_ADJUST_MODIFIER = 5; private static final long FT_HISTORY_PIRCES_LENGTH = 10; private static final long FT_TRACK_DURATION = 5; private static final int MAX_BED_BID_NUM_PER_AUC = 12; I can definitely alter the values manually and then compile the code to give it another go around. But the execution time for a thorough "statistic analysis" usually requires over 2000 times of execution, which will typically lasts more than half an hour on my own laptop... So I hope there is a way to alter values using other ways than dig into the source code to change the "const" values there, so I can automatically distributed compiled code to other people's PC and let them run the statistic analysis instead. One other reason for a automatically value adjustment is that I can try using my own agent to defeat itself by choosing different "const" values. Although my values are derived from previous history and statistical results, they are far from the most optimized values. I hope there is a easy way so I can quickly adopt that so to have a good sleep tonight while the computer does everything for me... :) Any hints on this sort of stuff? Any suggestion is welcomed and much appreciated.

    Read the article

  • Javascript : assign variable in if condition statement, good practice or not?

    - by Michael Mao
    Hi all: I moved one years ago from classic OO languages such like Java to Javascript. The following code is definitely not recommended (or even not correct) in Java: if(dayNumber = getClickedDayNumber(dayInfo)) { alert("day number found"); } function getClickedDayNumber(dayInfo) { dayNumber = dayInfo.indexOf("fc-day"); if(dayNumber != -1) //substring found { //normally any calendar month consists of "40" days, so this will definitely pick up its day number. return parseInt(dayInfo.substring(dayNumber+6, dayNumber+8)); } else return false; } Basically I just found out that I can assign a variable to a value in an if condition statement, and immediately check the assigned value as if it is boolean. For a safer bet, I usually separate that into two lines of code, assign first then check the variable, but now that I found this, I am just wondering whether is it good practice or not in the eyes of experienced javascript developers? Many thanks in advance.

    Read the article

  • bash: hwo to know NUM option in grep -A -B "on the fly" ?

    - by Michael Mao
    Hello everyone: I am trying to analyze my agent results from a collection of 20 txt files here. If you wonder about the background info, please go see my page, what I am doing here is just one step. Basically I would like to take only my agent's result out of the messy context, so I've got this command for a single file: cat run15.txt | grep -A 50 -E '^Agent Name: agent10479475' | grep -B 50 '^==' This means : after the regex match, continue forward by 50 lines, stop, then match a line separator starts with "==", go back by 50 lines, if possible (This would certainly clash the very first line). This approach depends on the fact that the hard-coded line number counter 50, would be just fine to get exactly one line separator. And this would not work if I do the following code: cat run*.txt | grep -A 50 -E '^Agent Name: agent10479475' | grep -B 50 '^==' The output would be a mess... My question is: how to make sure grep knows exactly when to stop going forward, and when to stop getting backward? Any suggestion or hint is much appreciated.

    Read the article

  • Perl : get substring which matches refex error

    - by Michael Mao
    Hi all: I am very new to Perl, so please bear with my simple question: Here is the sample output: Most successful agents in the Emarket climate are (in order of success): 1. agent10896761 ($-8008) 2. flightsandroomsonly ($-10102) 3. agent10479475hv ($-10663) Most successful agents in the Emarket climate are (in order of success): 1. agent10896761 ($-7142) 2. agent10479475hv ($-8982) 3. flightsandroomsonly ($-9124) I am interested only in agent names as well as their corresponding balances, so I am hoping to get the following output: agent10896761 -8008 flightsandroomsonly -10102 agent10479475hv -10663 agent10896761 -7142 agent10479475hv -8982 flightsandroomsonly -9124 For later processes. This is the code I've got so far: #!/usr/bin/perl -w open(MYINPUTFILE, $ARGV[0]); while(<MYINPUTFILE>) { my($line) = $_; chomp($line); # regex match test if($line =~ m/agent10479475/) { if($line =~ m/($-[0-9]+)/) { print "$1\n"; } } if($line =~ m/flightsandroomsonly/) { print "$line\n"; } } The second regex match has nothing wrong, 'cause that is printing out the whole line. However, for the first regex match, I've got some other output such like: $ ./compareResults.pl 3.txt 2. flightsandroomsonly ($-10102) 0479475 0479475 3. flightsandroomsonly ($-9124) 1. flightsandroomsonly ($-8053) 0479475 1. flightsandroomsonly ($-6126) 0479475 If I "escape" the braces like this if($line =~ m/\($-[0-9]+\)/) { print "$1\n"; } Then there is never a match for the first regex... So I stuck with a problem of making that particular regex work. Any hints for this? Many thanks in advance.

    Read the article

  • Perl : how to interrupt/resume loop by user hitting a key?

    - by Michael Mao
    Hi all: This is for debugging purpose. I've got a for loop that generates some output to Cygwin bash's CLI. I know that I can redirect outputs to text files and use Perl or even just a normal text editor to inspect the values printed out for a particular iteration, just feel that a bit painful. What I am now thinking is, to place a special subroutine inside the for loop, so that it would be "interrupted" at the beginning of each iteration, and Perl script should only resume to run after user/programmer hits a key(the Enter Key from keyboard?) In this way I can directly inspect the values printed out during each iteration. Is there a simple way to do this, without using additional libraries/CPAN ? Many thanks to the hints/suggestions in advance.

    Read the article

  • Should I add try/catch around when casting on an attribute of JSP implicit object?

    - by Michael Mao
    Hi all: Basically what I mean is like this: List<String[]> routes = (List<String[]>)application.getAttribute("routes"); For the above code, it tries to get an attribute named "routes" from the JSP implicit object - application. But as everyone knows, after this line of code, routes may very well contains a null - which means this application hasn't got an attribute named "routes". Is this "casting on null" good programming practice in Java or not? Basically I try to avoid exceptions such as java.io.InvalidCastException I reckon things like this are more as "heritage" of Java 1.4 when generic types were not introduced to this language. So I guess everything stored in application attributes as Objects (Similar to traditional ArrayList). And when you do "downcast", there might be invalid casts. What would you do in this case? Update: Just found that although in the implicit object application I did store a List of String arrays, when I do this : List<double[]> routes = (List<double[]>)application.getAttribute("routes"); It doesn't produce any error... And I felt not comfortable already... And even with this code: out.print(routes.get(0)); It does print out something strange : [Ljava.lang.String;@18b352f Am I printing a "pointer to String"? I can finally get an exception like this: out.print(routes.get(0)[1]); with error : java.lang.ClassCastException: [Ljava.lang.String; Because it was me to add the application attribute, I know which type should it be cast to. I feel this is not "good enough", what if I forget the exact type? I know there are still some cases where this sort of thing would happen, such as in JSP/Servlet when you do casting on session attributes. Is there a better way to do this? Before you say:"OMG, why you don't use Servlets???", I should justify my reason as this: - because my uni sucks, its server can only work with Servlets generated by JSP, and I don't really want to learn how to fix issues like that. look at my previous question on this , and this is uni homework, so I've got no other choice, forget all about war, WEB-INF,etc, but "code everything directly into JSP" - because the professors do that too. :)

    Read the article

  • what makes a Tomcat5.5 cannot be "aware" of new Java Web Applications?

    - by Michael Mao
    This is for uni homework, but I reckon it is more a generic problem to the Tomcat Server(version 5.5.27) on my uni. The problem is, I first did a skeleton Java Web Application (Just a simple Servlet and a welcome-file, nothing complicated, no lib included) using NetBeans 6.8 with the bundled Tomcat 6.0.20 (localhost:8084/WSD) Then, to test and prove it is "portable" and "auto-deploy-able", I cleaned and built a WSD.war file and dropped it onto my Xampp Tomcat (localhost:8080/WSD). The war extracted everything accordingly and I can see identical output from this Tomcat. So far, so good. However, after I tried to drop to war onto uni server, funny thing happens: uni server Even though I've changed the war permission to 755, it is simply not "responding". I then copied the extracted files to uni server, the MainServlet cannot be recognized from within its Context Path "/WSD", basically nothing works, expect the static index.jsp. I tried several times to stop and restart uni Tomcat, it doesn't help? I wonder what makes this happen? Is there anything I did wrong with my approach? To be frank I paid no attention to a server not under my control, and I am unfortunately not a real active day-to-day Java Programmer now. I understand the fundamentals of MVC, Servelets, JSPs, JavaBeans, but I really feel frustrated by this, as I cannot see why... Or, should I ask, a Java Web Application, after cleaned and built by NetBeans6.8, is self-contained and self-configured so ready to be deployed to any Java Web Container? I know, I can certainly program everything in plain old JSP, but this is soooo... unacceptable to myself... Update : I am now wondering if there is any free Tomcat Hosting so that I would like to see if my war file and/or my web app can go with them without any configuration at all?

    Read the article

  • PHP check http referer for form submitted by AJAX, secure?

    - by Michael Mao
    Hi all: This is the first time I am working for a front-end project that requires server-side authentication for AJAX requests. I've encountered problems like I cannot make a call of session_start as the beginning line of the "destination page", cuz that would get me a PHP Warning : Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\xampp\htdocs\comic\app\ajaxInsert Book.php:1) in C:\xampp\htdocs\comic\app\common.php on line 10 I reckon this means I have to figure out a way other than checking PHP session variables to authenticate the "caller" of this PHP script, and this is my approach : I have a "protected" PHP page, which must be used as the "container" of my javascript that posts the form through jQuery $.ajax(); method In my "receiver" PHP script, what I've got is: <?php define(BOOKS_TABLE, "books"); define(APPROOT, "/comic/"); define(CORRECT_REFERER, "/protected/staff/addBook.php"); function isRefererCorrect() { // the following line evaluates the relative path for the referer uri, // Say, $_SERVER['HTTP_REFERER'] returns "http://localhost/comic/protected/staff/addBook.php" // Then the part we concern is just this "/protected/staff/addBook.php" $referer = substr($_SERVER['HTTP_REFERER'], 6 + strrpos($_SERVER['HTTP_REFERER'], APPROOT)); return (strnatcmp(CORRECT_REFERER, $referer) == 0) ? true : false; } //http://stackoverflow.com/questions/267546/correct-http-header-for-json-file header('Content-type: application/json charset=UTF-8'); header('Cache-Control: no-cache, must-revalidate'); echo json_encode(array ( "feedback"=>"ok", "info"=>isRefererCorrect() )); ?> My code works, but I wonder is there any security risks in this approach? Can someone manipulate the post request so that he can pretend that the caller javascript is from the "protected" page? Many thanks to any hints or suggestions.

    Read the article

  • Should uni provide "correct answer" after programming assignment is due?

    - by Michael Mao
    Hi all: This is my very first subjective question. And I think it is programming related - the assignment is to be written in a programming language. I am not for "getting the full marks out of a subject". I am actually not for a "correct answer", but for a "better solution", so that I can compare, and can improve. I reckon it is good that I practice programming first and check the solution later to pick up the things I've done wrong/bad. Without a "benchmark" to against, this would be much harder. Unfortunately as far as I know, not all programming subjects taught in uni would kindly provide the students with a "correct answer" in the end, after the assignment is due. One bad metaphor for this is like someone asks you a question which they don't have a clear answer themselves and hope to take advantage of your answer as the basis for their answer. Personally, I feel having a assignment solution provided by the academic staff is essential to students. I do appreciate this, and I feel I might not be the only one. I am a very proactive student in uni. I learn more, I practice more, an assignment for me is more like a challenge to achieve "the best solution I can come up with", not something "I have to pass"... The cause of this question is that for the past few days I have crafted 500+ lines of Perl code, for a tiny assignment. I feel pain when I look at my solution(not finished yet) and I feel like I am an idiot doing some crap code. I know there must be a much better solution. And I reckon it is better for the lecturer in this subject to get me one, rather than asking for an answer here, even I would shamelessly add the link to my solution apart from the assignment requirements. I know in SO, there are a lot of tutors/lecturers for programming subjects/courses. I'd like to hear your words on this question.

    Read the article

  • For business people to manage, keep binary images in MySQL or just the urls?

    - by Michael Mao
    Hello everyone: I am working on a task to enable image uploading and auto-scaling(from full sized to thumbnail) by jQuery & PHP. I can naturally come up with two approaches : First, store both images as binary objects directly into MySQL; Second, store only urls to the images and keep the images somewhere on server. The images are for everyone to view, so there are no security restrictions, as far as I know. Personally I don't have any preference, however, at the end of the day, it is the business people that are going to manage the images as part of the system(CRUD). So I am wondering which seems to be a bit better for them? Of course I am building a easy-to-use, visualize web interface for the staff to control the process, but I am not sure if that is enough. Lessons told me that if I don't think for the future and seek the most flexible approach, the I will probably screw myself sooner or later. PS. The following link is what I've found so far, which is pretty cool, no flash involved :) Andrew Valum's ajax image upload jQuery plugin

    Read the article

  • PHP - error when insert date into MySQL

    - by Michael Mao
    Hello everyone: I've got a typical problem when trying to insert a date into MySQL. The column defined in MySQL is of type DATE. My PHP version is 5.3.0 Apart from this date-related issue, the rest of my code works just fine. And this is my PHP script to do this: $tablename = BOOKS_TABLE; $insert = mysql_query("INSERT INTO $tablename (barcode, book_name, volume_num,". " author, publisher, item_type, buy_price, buy_date) VALUES ". "(". "'" . $barcode . "', ". "'" . $bookname . "', ". "'" . $volumenum . "', ". "'" . $author . "', ". "'" . $publisher . "', ". "'" . $itemtype . "', ". "'" . $buyprice . "', ". "'" . getMySQLDateString($buydate). //"'STR_TO_DATE('".$buydate ."', '%d/%m/%Y'))'". //nothing changes in MySQL ")"); And this is the faulty function : function getMySQLDateString($buydate) //typical buydate : 04/21/2009 { $mysqlDateString = date('Y-m-d H:i:s', $strtotime($buydate)); return $mysqlDateString; } The first commented out line wouldn't do anything, the script is executed with no error, however, there is nothing changed in datebase after this. The current approach will cause a Fatal error saying function name must be a string in this line. Actually I followed this thread on SO, but just cannot pass the date into MySQL... Can anyone help me figure out which part is not right? How would you do it, in this case, to get it right? Sorry about such a journeyman-like question, thanks a lot in advance.

    Read the article

  • jQuery plugin to have Facebook styled search box with image thumbnails?

    - by Michael Mao
    Hello everyone: I will work on a search box with inspiration from Facebook where image thumbnails would be displayed besides the auto-suggested matches. This is the goal : link to sample image I wonder if there is any jQuery plugin that would just do this. I tried to search for a one but unable to find. If there is no plugin for this task, I'd like to know the basic plugins needed to implemented such an auto-suggest/image thumbnail display combination. Any suggestion and hint is welcomed. Thanks a lot!

    Read the article

  • Perl : In splice() type of arg1 must be array, cannot be scalar dereference. How to fix?

    - by Michael Mao
    I am trying to comprehend the reference/dereference system in Perl. What I am trying to do is to remove an element by using reference: my $ref= \@{$collection{$_[0]}}; # delete($$ref[$i]); # delete works, I've tested that already splice($$ref, $i, 1); # this wouldn't do. I first tried the delete() subroutine, it works; however, it doesn't shift the index after the removed elements forward by 1, so I cannot continue working on other stuff. I then Googled and found the splice() subroutine which does delete and shift in one go. But the error feedback tells me that "Type of arg 1 to splice must be array (not scalar dereference)..." I then tried something like this: splice(@{$$ref}, $i, 1); That resulted in another error like this: "Not a SCALAR reference at...(pointing at that line)" So I am a bit puzzled, how could I handle this issue? I prefer not using any CPAN or additional library for the solution, if possible.

    Read the article

  • How can I enable a debugging mode via a command-line switch for my Perl program?

    - by Michael Mao
    I am learning Perl in a "head-first" manner. I am absolutely a newbie in this language: I am trying to have a debug_mode switch from CLI which can be used to control how my script works, by switching certain subroutines "on and off". And below is what I've got so far: #!/usr/bin/perl -s -w # purpose : make subroutine execution optional, # which is depending on a CLI switch flag use strict; use warnings; use constant DEBUG_VERBOSE => "v"; use constant DEBUG_SUPPRESS_ERROR_MSGS => "s"; use constant DEBUG_IGNORE_VALIDATION => "i"; use constant DEBUG_SETPPING_COMPUTATION => "c"; our ($debug_mode); mainMethod(); sub mainMethod # () { if(!$debug_mode) { print "debug_mode is OFF\n"; } elsif($debug_mode) { print "debug_mode is ON\n"; } else { print "OMG!\n"; exit -1; } checkArgv(); printErrorMsg("Error_Code_123", "Parsing Error at..."); verbose(); } sub checkArgv #() { print ("Number of ARGV : ".(1 + $#ARGV)."\n"); } sub printErrorMsg # ($error_code, $error_msg, ..) { if(defined($debug_mode) && !($debug_mode =~ DEBUG_SUPPRESS_ERROR_MSGS)) { print "You can only see me if -debug_mode is NOT set". " to DEBUG_SUPPRESS_ERROR_MSGS\n"; die("terminated prematurely...\n") and exit -1; } } sub verbose # () { if(defined($debug_mode) && ($debug_mode =~ DEBUG_VERBOSE)) { print "Blah blah blah...\n"; } } So far as I can tell, at least it works...: the -debug_mode switch doesn't interfere with normal ARGV the following commandlines work: ./optional.pl ./optional.pl -debug_mode ./optional.pl -debug_mode=v ./optional.pl -debug_mode=s However, I am puzzled when multiple debug_modes are "mixed", such as: ./optional.pl -debug_mode=sv ./optional.pl -debug_mode=vs I don't understand why the above lines of code "magically works". I see both of the "DEBUG_VERBOS" and "DEBUG_SUPPRESS_ERROR_MSGS" apply to the script, which is fine in this case. However, if there are some "conflicting" debug modes, I am not sure how to set the "precedence of debug_modes"? Also, I am not certain if my approach is good enough to Perlists and I hope I am getting my feet in the right direction. One biggest problem is that I now put if statements inside most of my subroutines for controlling their behavior under different modes. Is this okay? Is there a more elegant way? I know there must be a debug module from CPAN or elsewhere, but I want a real minimal solution that doesn't depend on any other module than the "default". And I cannot have any control on the environment where this script will be executed...

    Read the article

  • How to split the chance to display SWFs evenly among banner collection?

    - by Michael Mao
    Hi all: I am working on The ausdcf.org to try adding several banner ads in swf format to the top. Everything starts to work, but I've got several questions that need your help: The client chose not to go with Google AdManager, but prefer a "minimal approach" to do this task. What I am trying to do is sort of "mimicking" the way Google AdManager does for banners, that is, to split the chance of each particular swf to be shown to the visitor evenly among the banner collection. Definitely I can add some jQuery code to do this from client-side, a random number generator and if-else statement would work - just $.load() it! However, what if I'd like to make sure those disabled Javascript (is there any now btw?) still be able to see different swfs in each visit. Any suggestion on how to approach this? Many thanks in advance.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >