Thursday 30 June 2016

php - MAMP upgrade from MySQL 5.5 to 5.6



I am upgrading MySQL 5.5 to 5.6 for MAMP




Do I need to get a new .so file for php integration with 5.6



Configuration File (php.ini) Path /Applications/MAMP/bin/php/php5.3.14/conf



So, I added the change in php.ini in above directory to use /tmp/mysql.sock which is used by MySQL 5.6



But, even after this phpinfo page still shows MySQL 5.5 and also php code is always trying to connect to MySQL 5.5



I find that both MySQL 5.5 and MySQL 5.6 can run together on port 3306 since they work on different sock files. MySQL 5.6 has /tmp/mysql.sock and MySQL 5.5 has /Applications/MAMP/tmp/mysql/mysql.sock




Need to read from MySQL 5.6 instead of 5.5 database from php for upgrade..



EDIT



I tried created a Soft Link -
ln -s /Applications/MAMP/tmp/mysql/mysql.sock /tmp/mysql.sock



But this gives error in php ->
CDbConnection failed to open the DB connection: SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/Applications/MAMP/tmp/mysql/mysql.sock' (2)



Answer



Answer to this post solved it. All I had to do was change localhost to 127.0.0.1 in yii while configuring db module



yii error while excecuting custom command


c - How to initialize all members of an array to the same value?




I have a large array in C (not C++ if that makes a difference). I want to initialize all members to the same value. I could swear I once knew a simple way to do this. I could use memset() in my case, but isn't there a way to do this that is built right into the C syntax?


Answer



Unless that value is 0 (in which case you can omit some part of the initializer
and the corresponding elements will be initialized to 0), there's no easy way.



Don't overlook the obvious solution, though:



int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };



Elements with missing values will be initialized to 0:



int myArray[10] = { 1, 2 }; // initialize to 1,2,0,0,0...


So this will initialize all elements to 0:



int myArray[10] = { 0 }; // all elements 0



In C++, an empty initialization list will also initialize every element to 0.
This is not allowed with C:



int myArray[10] = {}; // all elements 0 in C++


Remember that objects with static storage duration will initialize to 0 if no
initializer is specified:



static int myArray[10]; // all elements 0



And that "0" doesn't necessarily mean "all-bits-zero", so using the above is
better and more portable than memset(). (Floating point values will be
initialized to +0, pointers to null value, etc.)


c++ - What does Visual Studio do with a deleted pointer and why?




A C++ book I have been reading states that when a pointer is deleted using the delete operator the memory at the location it is pointing to is "freed" and it can be overwritten. It also states that the pointer will continue to point to the same location until it is reassigned or set to NULL.



In Visual Studio 2012 however; this doesn't seem to be the case!



Example:



#include 

using namespace std;


int main()
{
int* ptr = new int;
cout << "ptr = " << ptr << endl;
delete ptr;
cout << "ptr = " << ptr << endl;

system("pause");

return 0;

}


When I compile and run this program I get the following output:



ptr = 0050BC10
ptr = 00008123
Press any key to continue....






Clearly the address that the pointer is pointing to changes when delete is called!



Why is this happening? Does this have something to do with Visual Studio specifically?



And if delete can change the address it is pointing to anyways, why wouldn't delete automatically set the pointer to NULL instead of some random address?


Answer



I noticed that the address stored in ptr was always being overwritten with 00008123...




This seemed odd, so I did a little digging and found this Microsoft blog post containing a section discussing "Automated pointer sanitization when deleting C++ objects".




...checks for NULL are a common code construct meaning that an existing check for NULL combined with using NULL as a sanitization value could fortuitously hide a genuine memory safety issue whose root cause really does needs addressing.



For this reason we have chosen 0x8123 as a sanitization value – from an operating system perspective this is in the same memory page as the zero address (NULL), but an access violation at 0x8123 will better stand out to the developer as needing more detailed attention.




Not only does it explain what Visual Studio does with the pointer after it is deleted, it also answers why they chose NOT to set it to NULL automatically!







This "feature" is enabled as part of the "SDL checks" setting. To enable/disable it go to: PROJECT -> Properties -> Configuration Properties -> C/C++ -> General -> SDL checks



To confirm this:



Changing this setting and rerunning the same code produces the following output:



ptr = 007CBC10
ptr = 007CBC10






"feature" is in quotes because in a case where you have two pointers to the same location, calling delete will only sanitize ONE of them. The other one will be left pointing to the invalid location...


javascript - Reading image capture files in PhoneGap

I'm working on a PhoneGap application that captures images using the camera and, later, uploads them. There are two modes of operation for camera in PhoneGap: raw base64 encoded data or a file URI.



The docs themselves say:




Note: The image quality of pictures taken using the camera on newer
devices is quite good. Encoding such images using Base64 has caused
memory issues on some of these devices (iPhone 4, BlackBerry Torch
9800). Therefore, using FILE_URI as the 'Camera.destinationType' is
highly recommended.





So I'm keen to use FILE_URI option. This works great and you can even show the images in IMG tags. The URL looks like this:




file://localhost/var/mobile/Applications/4FE4642B-944C-449BB-9BD6-1E442E47C7CE/tmp/photo_047.jpg




However, at some point later I want to read the contents of the file to upload to a server. I was going to do this using the FileReader type. This doesn't work and I think it's because I can't access the file at the URL above.




The error code I get back from readDataUrl is 1 > FileError.NOT_FOUND_ERR = 1;



Any ideas how I can get to the file? I tried just accessing the last part of the path (photo_047.jpg) based on another sample I saw but no luck.

c# - Call one constructor from another



I have two constructors which feed values to readonly fields.



public class Sample
{

public Sample(string theIntAsString)
{
int i = int.Parse(theIntAsString);
_intField = i;
}

public Sample(int theInt) => _intField = theInt;
public int IntProperty => _intField;

private readonly int _intField;

}


One constructor receives the values directly, and the other does some calculation and obtains the values, then sets the fields.



Now here's the catch:




  1. I don't want to duplicate the
    setting code. In this case, just one

    field is set but of course there may
    well be more than one.

  2. To make the fields readonly, I need
    to set them from the constructor, so
    I can't "extract" the shared code to
    a utility function.

  3. I don't know how to call one
    constructor from another.




Any ideas?


Answer



Like this:



public Sample(string str) : this(int.Parse(str)) { }

Purge or recreate a Ruby on Rails database




I have a dev Ruby on Rails database full of data. I want to delete everything and rebuild the database. I'm thinking of using something like:



rake db:recreate


Is this possible?


Answer



I know two ways to do this:



This will reset your database and reload your current schema with all:




rake db:reset db:migrate


This will destroy your db and then create it and then migrate your current schema:



rake db:drop db:create db:migrate


All data will be lost in both scenarios.



java - When to choose checked and unchecked exceptions



In Java (or any other language with checked exceptions), when creating your own exception class, how do you decide whether it should be checked or unchecked?




My instinct is to say that a checked exception would be called for in cases where the caller might be able to recover in some productive way, where as an unchecked exception would be more for unrecoverable cases, but I'd be interested in other's thoughts.


Answer



Checked Exceptions are great, so long as you understand when they should be used. The Java core API fails to follow these rules for SQLException (and sometimes for IOException) which is why they are so terrible.



Checked Exceptions should be used for predictable, but unpreventable errors that are reasonable to recover from.



Unchecked Exceptions should be used for everything else.



I'll break this down for you, because most people misunderstand what this means.





  1. Predictable but unpreventable: The caller did everything within their power to validate the input parameters, but some condition outside their control has caused the operation to fail. For example, you try reading a file but someone deletes it between the time you check if it exists and the time the read operation begins. By declaring a checked exception, you are telling the caller to anticipate this failure.

  2. Reasonable to recover from: There is no point telling callers to anticipate exceptions that they cannot recover from. If a user attempts to read from an non-existing file, the caller can prompt them for a new filename. On the other hand, if the method fails due to a programming bug (invalid method arguments or buggy method implementation) there is nothing the application can do to fix the problem in mid-execution. The best it can do is log the problem and wait for the developer to fix it at a later time.



Unless the exception you are throwing meets all of the above conditions it should use an Unchecked Exception.



Reevaluate at every level: Sometimes the method catching the checked exception isn't the right place to handle the error. In that case, consider what is reasonable for your own callers. If the exception is predictable, unpreventable and reasonable for them to recover from then you should throw a checked exception yourself. If not, you should wrap the exception in an unchecked exception. If you follow this rule you will find yourself converting checked exceptions to unchecked exceptions and vice versa depending on what layer you are in.




For both checked and unchecked exceptions, use the right abstraction level. For example, a code repository with two different implementations (database and filesystem) should avoid exposing implementation-specific details by throwing SQLException or IOException. Instead, it should wrap the exception in an abstraction that spans all implementations (e.g. RepositoryException).


javascript - Get clicked element onclick

var submenus = document.getElementsByClassName("submenu");
for (var i = 0; i < submenus.length; i++) {

submenus[i].onclick = function() {
toggle(submenus[i].nextSibling);
return false;
}
}

function toggle(el) {
if (el.style.display == 'block') {
el.style.display = 'none';
} else {

el.style.display = 'block';
}
}


Causes error: TypeError: submenus[i] is undefined



I assume submenus[i] is not in the scope of the function. How do I get the element clicked so I can toggle it's next sibling?

Wednesday 29 June 2016

java - Why exactly do subclass constructors have to explicitly call super class constructors?







Why exactly do subclass constructors have to explicitly call super class constructors? What is the reason for this?

marvel cinematic universe - Why was the Avengers movie called something different in the UK?


In the UK the movie is called "Avengers Assemble"


Why was it given a different name in that market?


Answer


The Avengers was given a somewhat different name because of the British TV show The Avengers. The new name was to help keep them separate and to avoid any confusion for audiences in the UK.


Wikipedia says:



In February 2012, Disney announced that the film's title would be
changed in the United Kingdom to avoid confusion with the British TV
series of the same name, as well as its 1998 film adaptation, but this
led to confusion over the film's actual title. Empire magazine
reported that the film would be titled Marvel Avengers Assemble
while The Hollywood Reporter said that it would be called simply
Avengers Assemble.



android - Error StrictMode$AndroidBlockGuardPolicy.onNetwork




I created android application and use JSON get data from server but I got the error show below:



android.os.NetworkOnMainThreadException

at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)


how can I fix this problem
Thank you


Answer



you have to insert 2 lines "StrictMode" on MainActivity Class, example's below:



public class MainActivity extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

try {
// JSON here
} catch (JSONException e2) {
// TODO Auto-generated catch block

e2.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


setContentView(R.layout.activity_main);
Intent intent=new Intent(this,HomeActivity.class);

startActivity(intent);
}
}


Aey.Sakon


Best way to connect to MySQL with PHP securely

I want some input on what you guys think is the most secure way to connect to a MySQL database using PHP. Currently the way I'm doing it is a utility PHP file that I include in the top of all my other PHP files. The utility PHP file is this:




    if(!defined('IN_PHP')){
die("hackerssss");
}
$mysql_host = "localhost";
$mysql_user = "root";
$mysql_pass = "root";
$mysql_db = cokertrading;
?>



Any suggestions?

r - shiny conditional panel not updating



I have an issue with conditional panel. I would like to show in sidebarPanel either DateRange OR SliderInput depending on the selected choice in the RadioButton, which is also in the sidebarPanel.



If you try to run the below example it will fail with following Error message:




Error : formal argument "condition" matched by multiple actual
arguments





If you comment out any of the two conditions you can see that the example variable has value a or b depending on the options chosen.



I'm pretty sure I'm missing something, but I cannot figure out what. I did look around and I couldn't find anything helpful.



library(shiny)

# Server ---------------------------------------------

server = shinyServer(function(input, output){

output$debug <- renderPrint({
input$example
})
})


# Ui -------------------------------------------------

ui = {
fluidPage(

sidebarPanel(
radioButtons('example', 'Select Examples: ', choices = c('a', 'b'), selected = 'a'),
conditionalPanel(
condition = "input.example == 'a'",
dateRangeInput('date', 'Select Date Range:',
start = Sys.Date() - 7,
end = Sys.Date(),
min = '2012-04-01',
max = Sys.Date()
)

,
condition = "input.example == 'b'",
sliderInput('date', 'Slide Date Range:', min = 1, max = 90, value = 14, step = 1)
)
),
mainPanel(verbatimTextOutput("debug")
)
)}



# App ------------------------------------------------

shinyApp(ui = ui, server = server)


Thanks


Answer



You need to specify two conditionalPanel objects, one for each condition.



library(shiny)


# Server ---------------------------------------------

server = shinyServer(function(input, output){
output$debug <- renderPrint({
input$example
})
})



# Ui -------------------------------------------------

ui = {
fluidPage(
sidebarPanel(
radioButtons('example', 'Select Examples: ', choices = c('a', 'b'),
selected = 'a'),
conditionalPanel(
condition = "input.example == 'a'",
dateRangeInput('date', 'Select Date Range:',

start = Sys.Date() - 7,
end = Sys.Date(),
min = '2012-04-01',
max = Sys.Date()
)
),
conditionalPanel(
condition = "input.example = 'b'",
sliderInput('date', 'Slide Date Range:', min = 1, max = 90, value = 14,
step = 1)

)
),
mainPanel(verbatimTextOutput("debug")
)
)}


# App ------------------------------------------------

shinyApp(ui = ui, server = server)


Draw a pie chart with Highcharts with datas error

I want to create a pie, using Highcharts.



The data are provided in a json format :
Here's the lines of my script :



    function myPie(d){
console.log(d);
chart = new Highcharts.Chart({
...

series: [{
type: 'pie',
name: 'Test',
innerSize: '80%',
data: d
}
]
...
});



The response at the console is Object { p0: "0.232697", p1: "0.259336", p2: "0.298506", p3: "0.177095", p4: "0.0323651" }



And I get nothing
What's wrong ?
How can I solve this problem.
Thanks for help.

java - Convert from enum ordinal to enum type



I've the enum type ReportTypeEnum that get passed between methods in all my classes but I then need to pass this on the URL so I use the ordinal method to get the int value. After I get it in my other JSP page, I need to convert it to back to an ReportTypeEnum so that I can continue passing it.



How can I convert ordinal to the ReportTypeEnum?



Using Java 6 SE.


Answer



To convert an ordinal into its enum represantation you might want to do this:




ReportTypeEnum value = ReportTypeEnum.values()[ordinal];


Please notice the array bounds.



Note that every call to values() returns a newly cloned array which might impact performance in a negative way. You may want to cache the array if it's going to be called often.



Code example on how to cache values().







This answer was edited to include the feedback given inside the comments


java - How to reference a method in javadoc?




How can I use the @link tag to link to a method?



I want to change



/**
* Returns the Baz object owned by the Bar object owned by Foo owned by this.
* A convenience method, equivalent to getFoo().getBar().getBaz()
* @return baz
*/
public Baz fooBarBaz()



to



/**
* Returns the Baz object owned by the Bar object owned by Foo owned by this.
* A convenience method, equivalent to {@link getFoo()}.{@link getBar()}.{@link getBaz()}
* @return baz
*/
public Baz fooBarBaz()



but I don't know how to format the @link tag correctly.


Answer



You will find much information about JavaDoc at the Documentation Comment Specification for the Standard Doclet, including the information on the




{@link package.class#member label}





tag (that you are looking for). The corresponding example from the documentation is as follows




For example, here is a comment that refers to the getComponentAt(int, int) method:



Use the {@link #getComponentAt(int, int) getComponentAt} method.




The package.class part can be ommited if the referred method is in the current class.







Other useful links about JavaDoc are:




Solve error an't connect to local MySQL server through socket '/usr/local/zend/mysql/tmp/mysql.sock' (2) in /Applications/MAMP/htdocs

I has problem with below error and i spent many time to solve it.



Warning: mysql_connect() [function.mysql-connect]: Can't connect to local MySQL server through socket '/usr/local/zend/mysql/tmp/mysql.sock' (2) in /Applications/MAMP/htdocs



This this are my environment MAC OSX 10.6.5 + MAMP PRO 1.9.4 + ZendStudio



And this is solution to solve an error




  1. create folder /usr/local/zend/mysql/tmp/ (if dose not exist)

  2. use terminal and copy this : sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /usr/local/zend/mysql/tmp/mysql.sock then enter



** this error because zend can't find mysql.sock. so we need to create Alias for it.

javascript - JQuery click event does not trigger




I am doing a project and i use ajax to load content into page.



my jquery function is :



function load_room() {
var sem = 0;


$.ajax({
url: 'ajax/room_ajax.php?option=2',
type: 'POST',
data: { 'sem': sem },
dataType: "json",
success: function (data) {
console.log(data[0]);
$("#room").html("");
for (var i = 0; i < data.length; i++) {
var x = i + 1;

$("#room").append("" + x + "" + data[i]['room_name'] + "edit");
};
}
});
}


The content load success fully but when i click on the edit
element it does not trigger the corresponding click event.
The code is like:




$('#edit').on('click', function(){
alert("hai")
});

Answer



You are binding event to element those are present in DOM the time on() is executed. Delegate event to static parent for elements added dynamically.



$('#room').on('click', "#edit", function(){
alert("hai")

});



Delegated events have the advantage that they can process events
from descendant elements that are added to the document at a later
time. By picking an element that is guaranteed to be present at the
time the delegated event handler is attached, you can use delegated
events to avoid the need to frequently attach and remove event
handlers.




php - SQL: Syntax error or access violation

Before I start, I looked at many other posts but none have actually helped.



I get an "SQLSTATE[42000]: Syntax error or access violation" error. This error is being cause by this line:




$sql2 = $database->query("SELECT * FROM `users` LIMIT $limit");


$limit is:



$limit = ($page_id-1)*$itemsPerPage.','.$itemsPerPage;


My full error:





Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-10,10' at line 1' in C:\xampp\htdocs\pdo\index.php:76 Stack trace: #0 C:\xampp\htdocs\pdo\index.php(76): PDO->query('SELECT * FROM `...') #1 {main} thrown in C:\xampp\htdocs\pdo\index.php on line 76




I've spent so long trying to work out this problem. I've tried executing the query without $limit. But that does not work.



Heres how I'm doing the for loop:



$limit = ($page_id-1)*$itemsPerPage.','.$itemsPerPage;

$sql2 = $database->query("SELECT * FROM `users` LIMIT $limit");

while($row = $sql2->fetch(PDO::FETCH_OBJ)) {
//My stuff in here
}


If theres any sort of way someone could help, that'd be great. Thanks!

r - Convert a list to a data frame



I have a nested list of data. Its length is 132 and each item is a list of length 20. Is there a quick way to convert this structure into a data frame that has 132 rows and 20 columns of data?



Here is some sample data to work with:




l <- replicate(
132,
list(sample(letters, 20)),
simplify = FALSE
)

Answer



Assuming your list of lists is called l:




df <- data.frame(matrix(unlist(l), nrow=length(l), byrow=T))


The above will convert all character columns to factors, to avoid this you can add a parameter to the data.frame() call:



df <- data.frame(matrix(unlist(l), nrow=132, byrow=T),stringsAsFactors=FALSE)

function - Without pointers, can I pass references as arguments in Python?




Since Python doesn't have pointers, I am wondering how I can pass a reference to an object through to a function instead of copying the entire object. This is a very contrived example, but say I am writing a function like this:




def some_function(x):
c = x/2 + 47
return c

y = 4
z = 12

print some_function(y)
print some_function(z)



From my understanding, when I call some_function(y), Python allocates new space to store the argument value, then erases this data once the function has returned c and it's no longer needed. Since I am not actually altering the argument within some_function, how can I simply reference y from within the function instead of copying y when I pass it through? In this case it doesn't matter much, but if y was very large (say a giant matrix), copying it could eat up some significant time and space.


Answer



Your understanding is, unfortunately, completely wrong. Python does not copy the value, nor does it allocate space for a new one. It passes a value which is itself a reference to the object. If you modify that object (rather than rebinding its name), then the original will be modified.



Edit



I wish you would stop worrying about memory allocation: Python is not C++, almost all of the time you don't need to think about memory.



It's easier to demonstrate rebinding via the use of something like a list:




def my_func(foo):
foo.append(3) # now the source list also has the number 3
foo = [3] # we've re-bound 'foo' to something else, severing the relationship
foo.append(4) # the source list is unaffected
return foo


original = [1, 2]
new = my_func(original)


print original # [1, 2, 3]
print new # [3, 4]


It might help if you think in terms of names rather than variables: inside the function, the name "foo" starts off being a reference to the original list, but then we change that name to point to a new, different list.


visual studio 2010 - C++ Fatal Error LNK1120: 1 unresolved externals



What is causing this error? I google'd it and first few solutions I found were that something was wrong with the library and the main function but both seem to be fine in my problem, I even retyped both! What could be causing this?



This might be helpful:



MSVCRTD.lib(crtexew.obj) : error LNK2019: unresolved external symbol WinMain@16 referenced in function __tmainCRTStartup




#include 
using namespace std;
int main()
{
const double A = 15.0,
B = 12.0,
C = 9.0;
double aTotal, bTotal, cTotal, total;
int numSold;


cout << "Enter The Number of Class A Tickets Sold: ";
cin >> numSold;
aTotal = numSold * A;

cout << "Enter The Number of Class B Tickets Sold: ";
cin >> numSold;
bTotal = numSold * B;

cout << "Enter The Number of Class C Tickets Sold: ";

cin >> numSold;
cTotal = numSold * C;

total = aTotal + bTotal + cTotal;

cout << "Income Generated" << endl;
cout << "From Class A Seats $" << aTotal << endl;
cout << "From Class B Seats $" << bTotal << endl;
cout << "From Class C Seats $" << cTotal << endl;
cout << "-----------------------" << endl;

cout << "Total Income: " << total << endl;

return 0;
}

Answer



From msdn




When you created the project, you made the wrong choice of application

type. When asked whether your project was a console application or a
windows application or a DLL or a static library, you made the wrong
chose windows application (wrong choice).



Go back, start over again, go to File -> New -> Project -> Win32
Console Application -> name your app -> click next -> click
application settings.



For the application type, make sure Console Application is selected
(this step is the vital step).




The main for a windows application is called WinMain, for a DLL is
called DllMain, for a .NET application is called
Main(cli::array ^), and a static library doesn't have a
main. Only in a console app is main called main



PHP / MySQL: Joining three tables and merging results











I have three tables:



Table #1: teacher



id
firstname
surname



Table #2: course



id
name


Table #3: courses_has_teachers



course_id
teacher_id



What I want to get, is the course info with the teacher(s) info. I have tried it with this query:



SELECT * FROM 
teacher, course, courses_has_teachers
WHERE
courses_has_teachers.teacher_id = teacher.id
AND
course.id = courses_has_teachers.course.id



I get what I want, BUT: if a course has more than one teacher, I want to combine the results. Instead of multiple rows with same course info, I want to get one simple row with course info and a list of teachers.



NOT like this:



Name      | Teacher
--------------------
Course 1 | Person 1
Course 1 | Person 2



BUT this:



Name      | Teacher
------------------------------
Course 1 | Person 1, Person 2


Could someone help me with this?



Answer



Use GROUP_CONCAT. try this one,



SELECT  a.name, GROUP_CONCAT(CONCAT(firstname, ' ', surname))
FROM course a
INNER JOIN courses_has_teachers b
ON a.id = b.course_id
INNER JOIN teacher c
ON b.teacher_id = c.iD
GROUP BY a.name


Tuesday 28 June 2016

unit testing - What is Mocking?




What is Mocking?                                                                                                    .


Answer



Prologue: If you look up the noun mock in the dictionary you will find that one of the definitions of the word is something made as an imitation.






Mocking is primarily used in unit testing. An object under test may have dependencies on other (complex) objects. To isolate the behavior of the object you want to replace the other objects by mocks that simulate the behavior of the real objects. This is useful if the real objects are impractical to incorporate into the unit test.



In short, mocking is creating objects that simulate the behavior of real objects.







At times you may want to distinguish between mocking as opposed to stubbing. There may be some disagreement about this subject but my definition of a stub is a "minimal" simulated object. The stub implements just enough behavior to allow the object under test to execute the test.



A mock is like a stub but the test will also verify that the object under test calls the mock as expected. Part of the test is verifying that the mock was used correctly.



To give an example: You can stub a database by implementing a simple in-memory structure for storing records. The object under test can then read and write records to the database stub to allow it to execute the test. This could test some behavior of the object not related to the database and the database stub would be included just to let the test run.



If you instead want to verify that the object under test writes some specific data to the database you will have to mock the database. Your test would then incorporate assertions about what was written to the database mock.


java - JUnit test for System.out.println()



I need to write JUnit tests for an old application that's poorly designed and is writing a lot of error messages to standard output. When the getResponse(String request) method behaves correctly it returns a XML response:



@BeforeClass

public static void setUpClass() throws Exception {
Properties queries = loadPropertiesFile("requests.properties");
Properties responses = loadPropertiesFile("responses.properties");
instance = new ResponseGenerator(queries, responses);
}

@Test
public void testGetResponse() {
String request = "request";
String expResult = "response";

String result = instance.getResponse(request);
assertEquals(expResult, result);
}


But when it gets malformed XML or does not understand the request it returns null and writes some stuff to standard output.



Is there any way to assert console output in JUnit? To catch cases like:



System.out.println("match found: " + strExpr);

System.out.println("xml not well formed: " + e.getMessage());

Answer



using ByteArrayOutputStream and System.setXXX is simple:



private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
private final PrintStream originalOut = System.out;
private final PrintStream originalErr = System.err;


@Before
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
}

@After
public void restoreStreams() {
System.setOut(originalOut);
System.setErr(originalErr);

}


sample test cases:



@Test
public void out() {
System.out.print("hello");
assertEquals("hello", outContent.toString());
}


@Test
public void err() {
System.err.print("hello again");
assertEquals("hello again", errContent.toString());
}


I used this code to test the command line option (asserting that -version outputs the version string, etc etc)




Edit:
Prior versions of this answer called System.setOut(null) after the tests; This is the cause of NullPointerExceptions commenters refer to.


java - how to set default method argument values?

Is it possible to set the default method parameter values in Java?



Example:
If there is a method



public int doSomething(int arg1, int arg2)
{
//some logic here
return 0;

}


is it possible to modify the given method in order to be able to call it with and without parameters?



example:



doSomething(param1, param2);
doSomething();



Thanks!

Get the price of an item on Steam Community Market with PHP and Regex



I'm trying to use PHP to get the Steam Community Market price of an item. I take a url (for example : http://steamcommunity.com/market/listings/730/StatTrak%E2%84%A2%20P250%20%7C%20Steel%20Disruption%20%28Factory%20New%29) and then I download the content with file_get_contents(). I tried to use this :



function getInnerHTML($string, $tagname, $closetagname) {
$pattern = "/<$tagname ?.*>(.*)<\/$closetagname>/";
preg_match($pattern, $string, $matches);

return $matches[1];
}


Using



getInnerHTML($str, 'span class="market_listing_price market_listing_price_with_fee"', 'span');


An example of what I can have with file_get_contents is this :






$1.92


$1.68






But it returns nothing.



Has anyone an idea ?


Answer



Not entirely sure why you'd want to do this the hard way and regex through HTML when there's a perfectly working call which returns JSON. Although the original answer is correct and answers the OP question directly, this provides a much easier and efficient way of getting the market value of an item.



GET:



http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name=StatTrak%E2%84%A2%20P250%20%7C%20Steel%20Disruption%20%28Factory%20New%29




JSON Response:



{
"success": true,
"lowest_price": "1,43€ ",
"volume": "562",
"median_price": "1,60€ "
}



Response Definitions :



success: boolean value, true if the call was successful or false if something went wrong or there are no listing for this item on the Steam market.



lowest_price: string value with currency symbol [pre-/ap]pended depending on the query parameters specified. See below for some additional parameter.



volume: integer value returned as a string (?) - the total number of this specific item which has been sold/bought.



median_price: string value with currency symbol [pre-/ap]pended. The average price at which the item has been sold. See the Steam marketplace item graph for a better understanding on how the median is calculated.




Query Parameters:



appid: The unique (statically defined) Steam application ID of the game/app, in our case 730 for Counter-Strike: Global Offensive. See Valve's development Wiki for a list of other appid's, though this list will most probably always be out of date as new apps are added to their platform frequently.



market_hash_name: The name of the item being queried against with the exterior included, retrieving these names can be found when querying against a users inventory, but that's a whole other API call.



currency: An integer value; the currency value and format to return the market values. You'll need to tweak and play around with these numbers as I cannot provide too much detail here. Generally I stick to using USD as a global price and use my own currency API to translate into other currencies.


php - Debugging Drupal's White Screen of Death?




I have a Drupal installation that previously worked perfectly on my localhost. However, now, after a formatted my computer, it just shows a blank screen (completely white).



So my question is, how can I see where things are going wrong, if I can't even log into the sever?



The only errors I can find are (taken from the Apache Error Logs):



[Tue May 17 05:05:04 2011] [notice] Parent: child process exited with status 255 -- Restarting.
[Tue May 17 05:05:04 2011] [notice] Digest: generating secret for digest authentication ...
[Tue May 17 05:05:04 2011] [notice] Digest: done
[Tue May 17 05:05:07 2011] [notice] Apache/2.2.11 (Win32) DAV/2 mod_ssl/2.2.11 OpenSSL/0.9.8i PHP/5.2.9 configured -- resuming normal operations

[Tue May 17 05:05:07 2011] [notice] Server built: Dec 10 2008 00:10:06
[Tue May 17 05:05:07 2011] [notice] Parent: Created child process 6992


There are no errors in Watchdog...



I am using Xamp 1.7.1 (PHP 5.2) and Drupal 6.



I just also need to mention that once I try and load the site on my local machine, apache also crashes! I added this:




error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);


And it still just shows the screen of death? Where can I actually see errors?



I also found this in apache access.log:



127.0.0.1 - - [17/May/2011:05:22:14 +0200] "GET /greekmerchant/src/ HTTP/1.1" 200 3

127.0.0.1 - - [17/May/2011:05:25:45 +0200] "GET /greekmerchant/src/update.php HTTP/1.1" 302 -
127.0.0.1 - - [17/May/2011:05:25:46 +0200] "GET /greekmerchant/src/update.php?op=info HTTP/1.1" 200 -


... after trying to access update.php. It also just goes to a white screen.



I have this in my sql config file:



[mysqld]
port= 3306

socket= "C:/xampp/mysql/mysql.sock"
basedir="C:/xampp/mysql"
tmpdir="C:/xampp/tmp"
datadir="C:/xampp/mysql/data"
skip-locking
key_buffer = 16M
max_allowed_packet = 128M
table_cache = 64
sort_buffer_size = 512K
net_buffer_length = 8K

read_buffer_size = 256K
read_rnd_buffer_size = 512K
myisam_sort_buffer_size = 8M
log_error="mysql_error.log"


And...



[mysqldump]
quick

max_allowed_packet = 128M


Also, my PHP memory is set to 1024MB.



Anyone got any idea why this is just dying? Is it really a memory problem? What else can I do to get errors shown to me? I still see nothing even after enabling error logging.



Update:



The website runs on my local machine if I delete the files folder. So, for some reason, when it has to access files in the files folder, it runs out of memory. Why? Or better yet, what could be causing this excessive use of memory?



Answer



There is a whole page in the Drupal handbooks dedicated to debugging the "White Screen of Death". In a nutshell, enable error reporting by adding the following at the top of your index.php file:



error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);


...and check the logs, which you've already started to do. Those two steps tend to pinpoint the problem, most of the time. If that doesn't point you towards a solution, continue down the handbook page, for lots more tips.




If I had to take a wild guess, I would say your case is probably an out-of-memory error.


php - warning problem: expects parameter 1 to be mysqli_result











I get the following warning listed below and I was wondering how do I fix it



Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given on line 65


The code is around this section of PHP code listed below. I can list the full code if needed.



// function to retrieve average and votes
function getRatingText(){

$dbc = mysqli_connect ("localhost", "root", "", "sitename");
$sql1 = "SELECT COUNT(*)
FROM articles_grades
WHERE users_articles_id = '$page'";

$result = mysqli_query($dbc,$sql1);
$total_ratings = mysqli_fetch_array($result);

$sql2 = "SELECT COUNT(*)
FROM grades

JOIN grades ON grades.id = articles_grades.grade_id
WHERE articles_grades.users_articles_id = '$page'";

$result = mysqli_query($dbc,$sql2);
$total_rating_points = mysqli_fetch_array($result);
if (!empty($total_rating_points) && !empty($total_ratings)){
$avg = (round($total_rating_points / $total_ratings,1));
$votes = $total_ratings;
echo $avg . "/10 (" . $votes . " votes cast)";
} else {

echo '(no votes cast)';
}
}

Answer



mysqli_query() returns FALSE if there was an error in the query. So you should test for it...



/* Select queries return a resultset */
if ($result = mysqli_query($dbc, "SELECT Name FROM City LIMIT 10")) {
printf("Select returned %d rows.\n", $result->num_rows);


/* free result set */
$result->close();
}


See this link for the mysqli_query reference
http://php.net/manual/en/mysqli.query.php


sql - Best way to get identity of inserted row?



What is the best way to get IDENTITY of inserted row?




I know about @@IDENTITY and IDENT_CURRENT and SCOPE_IDENTITY but don't understand the pros and cons attached to each.



Can someone please explain the differences and when I should be using each?


Answer




  • @@IDENTITY returns the last identity value generated for any table in the current session, across all scopes. You need to be careful here, since it's across scopes. You could get a value from a trigger, instead of your current statement.


  • SCOPE_IDENTITY() returns the last identity value generated for any table in the current session and the current scope. Generally what you want to use.


  • IDENT_CURRENT('tableName') returns the last identity value generated for a specific table in any session and any scope. This lets you specify which table you want the value from, in case the two above aren't quite what you need (very rare). Also, as @Guy Starbuck mentioned, "You could use this if you want to get the current IDENTITY value for a table that you have not inserted a record into."


  • The OUTPUT clause of the INSERT statement will let you access every row that was inserted via that statement. Since it's scoped to the specific statement, it's more straightforward than the other functions above. However, it's a little more verbose (you'll need to insert into a table variable/temp table and then query that) and it gives results even in an error scenario where the statement is rolled back. That said, if your query uses a parallel execution plan, this is the only guaranteed method for getting the identity (short of turning off parallelism). However, it is executed before triggers and cannot be used to return trigger-generated values.




javascript - Bind onclick to nodes in a loop




I have a function add_the_handler that binds an onclick event to each node. The following example prints "3" in every alert window, when I click on any node:




var add_the_handlers = function (nodes) {

var i;
for (i=0; i< nodes.length; i+=1) {

nodes[i].onclick = function (e) {
alert(i);
};
}

};


fiddle is here: http://jsfiddle.net/D886E/3/



Why doesn´t the nodes print the different values 1,2,3 in the alert windows?


Answer



Check this fiddle. Basically you need a function clojure to handle the attaching of the listeners to the appropriate index in the loop



var add_the_handlers = function (nodes) {


var i;

for (i = 0; i < nodes.length; i += 1) {
(function (i) {
nodes[i].onclick = function (e) {
alert(i);
};

})(i);

}
};

pnodes = document.getElementsByClassName("node");

add_the_handlers(pnodes);

In the BBC Planet Earth trailer - where is the sky diver jumping?

BBC created Planet Earth series a few years ago.


The trailer can be seen here - if you go to 0.25 (screenshot below) it shows a sky diver jumping into a forest hole - I wanted to know where that is filmed.


screen-bbc-planet-earth-sky-diver


Answer


"Cave of Swallows" - This can be seen here: at about 1:05


From the youtube description:
This 400 meters deep cave is located in a rainforest in San Luis Potosí.
This Video is a beginning of BBC´s 2006 "Planet Earth".


Monday 27 June 2016

Second form submit button seems to be skipped(?) PHP / HTML



I need help about this, I have a PHP page, which searches for records, based on their first and last names, if sql finds the data then the second form comes out, which has lots of textboxes, to update the 'searched'information. And when I click the submit button of the second form , it does nothing, and even if I have syntax or whatever errors I have put on condition if(isset($_POST['submit'])), they end up being disregarded (no error messages will come up), after clicking the submit button, it just goes back to the page's original state, when it has to update the record I have searched for that was just edited. What exactly is the mistake on this part?



class.php - .php file that contains the operations for sql





$months = array('January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',

'September',
'October',
'November',
'December');

class EmployeeProfile {


public
function openConnection() {

$conn = mysqli_connect("localhost", "root", "", "db_employee");

if (mysqli_connect_errno()) {
echo "Failed to connect to database server";
}


return $conn;

}


public
function insert($query) {

if (mysqli_query($this - > openConnection(), $query) == 1) {
echo "Profile successfully registered!";
} else {
echo "Register failed";
}


}

public
function display($query) {

$result = mysqli_query($this - > openConnection(), $query);
echo "

";
if ($result - > num_rows == 1) {
while ($row = $result - > fetch_assoc()) {
echo "";

echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";

echo "";
echo "";
echo "
First Name: ".$row["firstname"]."
Middle Name: ".$row["middlename"]."
Last Name: ".$row["lastname"]."
Date of Birth: ".$row["dateofbirth"]."
Age: ".$row["age"]."
School: ".$row["school"]."
Highest Educational Attainment: ".$row["educ"]."
Year Last Attended: ".$row["yearattended"]."
Skills: ".$row["skills"]."
Previous Company: ".$row["prevcompany"]."
Position: ".$row["position"]."
Date of Employment: ".$row["dateofemployment"]."
";
}
} else

{

echo "Profile not found";
}


}

public
function edit($query) {

$result = mysqli_query($this - > openConnection(), $query);

}


}

?>


edit.php - the page itself.




Edit Profile








Enter first or last name


include("class.php");

if(isset($_POST['search2'])):

$status = "hidden";
$query = "select * from employee WHERE firstname='".$_POST['search']."' OR lastname='".$_POST['search']."' ";
$emp = new EmployeeProfile();
$emp->openConnection();

$result = mysqli_query($emp->openConnection(), $query);



if($result->num_rows == 1):




?>

































if(isset($_POST['submit'])):
$firstname = $_POST['firstname'];
$middlename = $_POST['middlename'];

$lastname = $_POST['lastname'];
$dateofbirth = $_POST['month']. " ".$_POST['days']. ", ".$_POST['year'];
$age = $_POST['age'];
$school = $_POST['school'];
$educ = $_POST['educ'];
$yearattended = $_POST['yearattended'];
$skills = $_POST['skills'];
$prevcompany = $_POST['prevcompany'];
$position = $_POST['position'];
$dateofemployment = $_POST['empmonth']. " ".$_POST['empyear'];


$row = $result->fetch_assoc();
$usr = $row["firstname"];


$query2 = "UPDATE employee SET firstname='$firstname', middlename='$middlename', lastname='$lastname', dateofbirth='$dateofbirth', age='$age', school='$school',
educ='$educ', yearattended='$yearattended', skills='$skills', prevcompany='$prevcompany', position='$position', dateofemployment='$dateofemployment',
WHERE firstname='$usr'";

mysqli_query($emp->openConnection(), $query2);


endif;





else:
echo "Profile not found";
endif;

endif;


?>

Edit your profile:
*Enter first name:
Enter middle name:
*Enter last name:
*Date of Birth:
*Age:
*School:
*Highest Educational Attainment:
*Year Last Attended:
*Skill(s):
Previous Company:
Position:
*Date of Employment:
* - Required







and I do really think that this line and beyond gets ignored.



This is part of the edit.php file that is shown above.




if(isset($_POST['submit'])):
$firstname = $_POST['firstname'];
$middlename = $_POST['middlename'];

$lastname = $_POST['lastname'];
$dateofbirth = $_POST['month']. " ".$_POST['days']. ", ".$_POST['year'];
$age = $_POST['age'];
$school = $_POST['school'];
$educ = $_POST['educ'];
$yearattended = $_POST['yearattended'];
$skills = $_POST['skills'];
$prevcompany = $_POST['prevcompany'];
$position = $_POST['position'];
$dateofemployment = $_POST['empmonth']. " ".$_POST['empyear'];


$row = $result->fetch_assoc();
$usr = $row["firstname"];


$query2 = "UPDATE employee SET firstname='$firstname', middlename='$middlename', lastname='$lastname', dateofbirth='$dateofbirth', age='$age', school='$school',
educ='$educ', yearattended='$yearattended', skills='$skills', prevcompany='$prevcompany', position='$position', dateofemployment='$dateofemployment',
WHERE firstname='$usr'";

mysqli_query($emp->openConnection(), $query2);



endif;

Answer



In general, there are two kinds of errors present.




  1. HTML tag order errors, which are extensive

  2. Syntax errors.
    - > must be -> to be properly parsed
    must be to be properly parsed




The syntax errors are present in both files.



Note: the following code contains some debug statements.





echo "

In myquery.php header

";

error_reporting(E_ALL);
//echo "

" . var_dump($_POST); . "

";
//echo "

" . var_dump($_GET); . "

";
?>

include("class.php");
?>

Edit Profile




echo "

In myquery.php body

";
?>








Enter first or last name






echo "

about to check _post for search2

";

if(isset($_POST['search2'])):
echo "

found _post for search2

";

$status = "hidden";
$query = "select * from employee WHERE firstname='".$_POST['search']."' OR lastname='".$_POST['search']."' ";
echo "

about to open DB

";
$emp = new EmployeeProfile();
$emp->openConnection();

echo "

about to place find query

";
$result = mysqli_query($emp->openConnection(), $query);

echo "

about to check for successful query

";
if($result->num_rows == 1):

echo "

successful search query

";
?>





























Edit your profile:
*Enter first name:
Enter middle name:
*Enter last name:
*Date of Birth:
*Age:
*School:
*Highest Educational Attainment:
*Year Last Attended:
*Skill(s):
Previous Company:
Position:
*Date of Employment:
* - Required



echo "

about to check for submit second form

";


if(isset($_POST['submit'])):

echo "

found submit for second form

";

$firstname = $_POST['firstname'];
$middlename = $_POST['middlename'];
$lastname = $_POST['lastname'];
$dateofbirth = $_POST['month']. " ".$_POST['days']. ", ".$_POST['year'];
$age = $_POST['age'];
$school = $_POST['school'];

$educ = $_POST['educ'];
$yearattended = $_POST['yearattended'];
$skills = $_POST['skills'];
$prevcompany = $_POST['prevcompany'];
$position = $_POST['position'];
$dateofemployment = $_POST['empmonth']. " ".$_POST['empyear'];

$row = $result->fetch_assoc();
$usr = $row["firstname"];



$query2 =
"UPDATE employee
SET firstname='$firstname',
middlename='$middlename',
lastname='$lastname',
dateofbirth='$dateofbirth',
age='$age',
school='$school',
educ='$educ',

yearattended='$yearattended',
skills='$skills',
prevcompany='$prevcompany',
position='$position',
dateofemployment='$dateofemployment',
WHERE firstname='$usr'";

echo "

about to update DB

";

mysqli_query($emp->openConnection(), $query2);

endif;
else:
echo "

search query failed

";

echo "Profile not found";
endif;
endif;
?>





Typecasting malloc C++





I have some C code with malloc statements in it that I want to merge with some C++ code.



I was wondering when and why is typecasting a call to malloc neccessary in C++?



For example:




char *str = (char*)malloc(strlen(argv[1]) * sizeof(char));

Answer




when and why is typecasting a call to malloc neccessary in C++?




Always when not assigning to a void *, since void * doesn't convert implicitly to other pointer types, the way it does in C. But the true answer is you shouldn't ever use malloc in C++ in the first place.







I am not suggesting you should use new instead of malloc. Modern C++ code should use new sparingly, or avoid it altogether if possible. You should hide all use of new or use non-primitive types (like std::vector mentioned by Xeo). I'm not really qualified to give advice in this direction due to my limited experience but this article along with searching for "C++ avoid new" should help. Then you'll want to look into:




php - rethinkdb changes() with yield doesn't return value

function fetchProduct()

{
$cursor = r\table("tableOne")->changes()->run($conn);

foreach ($cursor as $product) {
yield $product;
}
}


$product = fetchProduct();

var_dump($product);
echo "i"; //when the function use yield, this line executed. But when return used, it doesn't come to this line.


I understand rethinkdb's changes() will keep listening to the changes so i found that its better to use yield over the $cursor. But the yield doesn't return value to the calling party. But when return is used value returned.



How to make the yield to return any value when changes occur?



References:
https://rethinkdb.com/docs/async-connections/
What does yield mean in PHP?

assignment operator - Are `=` and `












Is it just a style preference?



As far as I can tell, they are the same.



I see many people prefer the "longer" <- version and I can't tell why (perhaps keeping away from = and == confusions?)


Answer



No, they are not exactly the same: the = operator cannot be used everywhere that <- can.




The operators <- and = assign into the environment in which they are evaluated. The operator <- can be used anywhere, whereas the operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions.





There are also differences in scope. See this answer for more details.



Which is better depends on who you ask.






Reading from "Introducing Monte Carlo Methods with R", by Robert and Casella:





"The assignment operator is =, not to be confused with ==, which is the Boolean operator for equality. An older assignment operator is <- and, for compatibility reasons, it still remains functional, but it should be ignored to ensure cleaner programming. (As pointed out by Spector, P. (2009). 'Data Manipulation with R' - Section 8.7., an exception is when using system.time, since = is then used to identify keywords)




Source






On the other hand, Google's R style guide recommends using <-:





Assignment



Use <-, not =, for assignment.



GOOD:
x <- 5



BAD:
x = 5



php - Laravel Syntax error, unexpected 'variable' (T_STRING)





I am trying to access a Shopping Cart view of a user, but when i click to get the Cart View it throws the below error.




Error : syntax error, unexpected 'item' (T_STRING)





Button:



 Shopping Cart
{{ Session::has('cart') ? Session::get('cart')->totalQty : '' }}



Route:




Route::get('/shopping-cart','ProductController@getCart');


View:



@if(Session::has('cart))



    @foreach($products as $product)


  • {{ $product['qty'] }}
    {{ $product['item']['title'] }}
    {{ $product['price'] }}


  • @endforeach




@endif



Cart Controller:



public function getCart(){
if(!Session::has('cart')){
return view('shop.shopping-cart');
}
$oldCart = Session::get('cart');
$cart = new Cart($oldCart);

return view('shop.shopping-cart', ['products' => $cart->items, 'totalPrice' => $cart->totalPrice]);
}

Answer



@if(Session::has('cart))



There is a typo here.


fetch_assoc error with sql query in php





I get this error :




Call to a member function fetch_assoc() on a non-object




when I use this code :



$sql = ('select '.$metric1.' as t1metric from '.$table1.' t1 WHERE '.$date1.' between ('.$start_date.' AND '.$end_date.')');



but it works when I use this :



$sql = ("select t1.clicks as t1clicks from aaa t1 WHERE t1.date between ('2015-11-11 and '2015-11-10')");


I first thought it was an issue with the different quotation marks " and ' but I was proven wrong.



This is my full code :




$servername = 'XXXXX';
$username = 'XXXXX';
$password = 'XXXXX';
$dbname = 'XXXXX';
$table1 = 'aaa';
$table2 = 'bbb';
$metric1 = 'clicks';
$metric2 = 'clicks';
$date1 = 'date';
$date2 = 'date';

$start_date = '2015-11-10';
$end_date = '2015-11-11';

$Db = mysqli_init();
$Db->options(MYSQLI_OPT_LOCAL_INFILE, true);
$Db->real_connect($servername, $username, $password, $dbname, 3306);

// Creation of SQL query
$sql = ("select t1.date, t1.clicks as t1clicks , t2.clicks as t2clicks from aaa t1, bbb t2 WHERE t1.date = t2.date AND t1.clicks != t2.clicks group by date");


// Run the query
$query = $Db->query($sql);

//
while ($row = $query->fetch_assoc())
{
echo sprintf("date: %s, aaa: %s, bbb: %s \n", $row['date'], $row['t1clicks'], $row['t2clicks']);
}

Answer




The reason you are getting the error is because you have not wrapped the dates with quotes.



WHERE '.$date1.' between ("'.$start_date.'" AND "'.$end_date.'")');
will work.



Hope this helps!



Cheers!


K-PAX ending explanation

In K-PAX, there are two possible explanations:



  1. Prot is crazy.

  2. He is truly an alien.


There are facts that indicate 1, but also 2.
Examples:



He seems to respond to hypnosis, has a sort of phobia of water, looks just like his friend and doesn't physically leave. But he sees UV rays, finds his planet and in the end makes the other patient (Bess) vanish.



How should the whole movie be interpreted, especially the ending?


Answer


Prot is human



  • Prot has a human subconscious

  • Prot has a human history (e.g. the school book, and the probable trauma)

  • Prot remains on earth after July 27th


Prot is an alien inhabiting a disturbed human's body



  • He can see ultraviolet rays (perhaps through the glasses)

  • He has an astounding knowledge of astronomy, physics, and advanced psychology (cures patients of serious mental illnesses that are equal to his own if he were human)

  • The electrical disturbance on the surveillance when he 'left'

  • He managed to disappear and survive unnoticed for almost 5 years since the incident.

  • He evaded security and left for 3 days completely unnoticed.

  • He left Bess's letter on her bed before she disappeared, confirming some sort of interaction that allowed her to disappear unnoticed on July 27th. (Perhaps he told her of a way to breach security)


Prot was an ET and could travel through a light beam in human body physical form but only one at a time. Hence, "I can only take one of you" ultimately choosing Bess.
Robert Porter was Prot's human friend before suffering mental trauma and becoming catatonic so Prot occupied his body to protect him and travel through until he could deliver him from peril after finding the right caretaker (Dr. Powell), then catching his prearranged travel timed Lightbeam Home using Bess as his human form (Vehicle), leaving Robert in safe haven with Dr. Powell. That's my synopsis.


Regardless, Prot acknowledges his return to consciousness with Jeff Bridges, asking that he take care of him. To me this says that although Prot may be an alien in Robert's body, he may still maintain some of the human subconsciousness.
For these reasons I find the clues are more consistent with the possibility that he is an Alien, than he is not. Funny enough to say, it would be almost more convoluted to argue that he was human.


string - When to use double or single quotes in JavaScript?




console.log("double"); vs console.log('single');



I see more and more JavaScript libraries out there using single quotes when handling strings. What are the reasons to use one over the other? I thought they're pretty much interchangeable.


Answer



The most likely reason for use of single vs double in different libraries is programmer preference and/or API consistency. Other than being consistent, use whichever best suits the string.



Using the other type of quote as a literal:



alert('Say "Hello"');
alert("Say 'Hello'");



This can get complicated:



alert("It's \"game\" time.");
alert('It\'s "game" time.');


Another option, new in ES6, are Template literals which use the back-tick character:




alert(`Use "double" and 'single' quotes in the same string`);
alert(`Escape the \` back-tick character and the \${ dollar-brace sequence in a string`);


Template literals offer a clean syntax for: variable interpolation, multi-line strings, and more.



Note that JSON is formally specified to use double quotes, which may be worth considering depending on system requirements.


c# - why IntPtr.size is 4 on Windows x64?



I think I should get 8 when I use IntPtr.Size. However I still get 4 on x64 machine with Widnows 7 x64, why?


Answer



check your file CPU architecture, is it x86? It should be CPU any / 64bit



Excel spreadsheet password cracking using VBA



I tried writing a password cracker code similar to the code I used to crack Excel sheet's password But I am not sure if I am doing correctly or not - when i tried this code it prompted me for password but no password was entered to the text input box.



Please suggest what I am doing wrong.



Thanks




Sub testmacro()
Dim password
Dim a, b, c, d, e, f, g, h, i, j, k, l
SendKeys "^r"
SendKeys "{PGUP}"

For a = 65 To 66
For b = 65 To 66
For c = 65 To 66
For d = 65 To 66

For e = 65 To 66
For f = 65 To 66
For g = 65 To 66
For h = 65 To 66
For i = 65 To 66
For j = 0 To 255
password = Chr(a) & Chr(b) & Chr(c) & Chr(d) & Chr(e) & Chr(f) & Chr(g) & Chr(h) & Chr(i) & Chr(j)
SendKeys "{Enter}", True
MsgBox password
SendKeys password, True

SendKeys "{Enter}", True

On Error GoTo 200
MsgBox password
GoTo 300
200 password = ""

Next
Next
Next

Next
Next
Next
Next
Next
Next
Next
300 MsgBox "exited"
End Sub


Answer



The reason your code is not executing properly is because you are attempting to execute a macro on a password protected execel file, which is not permitted. This is due to the fact that macros will not execute on an excel workbook until the password is entered - thus the prompt for a password before you can execute your macro code.



This SO article explains this as well, with greater detail: Excel VBA - Automatically Input Password



EDIT



For 2003







If you are trying to access the workbook, not the worksheet, there are a variety of ways in versions 2003 and earlier. After a quick perusual, this blogspot Code Samples entry appears to have a working version for unprotecting a 2003 workbook.



Also, on a related note, if you are stepping back even further and trying to unlock a VBA project, this SO article appears to adequately address the issue.



For 2007






If you are simply trying to "brute force" unprotect a client's workbook, a gentleman named Jason has outlined such a process in his blog.






SQL injection for the following regular expression



I am looking for backdoors in various softwares and wondering if the following code is vulnerable to a sql injection.



There's an email field with the following validation expression. (ASPX/CS)



ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">



Is it possible to exploit the above to drop a table for example or do anything malicious using a SQL injection?



Thanks
Regards



EDIT 1: People have asked me how this was implemented —



SqlConnection conn = new SqlConnection(snpConnectionString);

SqlCommand command = conn.CreateCommand();
conn.Open();
command.CommandText = "INSERT INTO TABLE_ VALUES ('" + TextBoxFN.Text + "','" + TextBoxLN.Text + "','" + sb1.ToString() + "','" + TextBoxEA.Text + "','" + sb.ToString() + "',0,'" + DateTime.Now + "')";
try{
SqlDataReader reader = command.ExecuteReader();
}
catch
{
Response.Redirect("Error.aspx", true);
}



TextBoxEA.text corresponds to the email address.


Answer



Regular expression validation is great for the UI or business layer to check user input to prevent errors.



It is less great for preventing SQL injection.



If the code does not use parameterized queries, it is vulnerable either now, or later after someone makes a minor error updating the regular expression to conform to a new business requirement.


Sunday 26 June 2016

javascript - How can I access and process nested objects, arrays or JSON?



I have a nested data structure containing objects and arrays. How can I extract the information, i.e. access a specific or multiple values (or keys)?



For example:




var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]

};


How could I access the name of the second item in items?


Answer



Preliminaries



JavaScript has only one data type which can contain multiple values: Object. An Array is a special form of object.



(Plain) Objects have the form




{key: value, key: value, ...}


Arrays have the form



[value, value, ...]


Both arrays and objects expose a key -> value structure. Keys in an array must be numeric, whereas any string can be used as key in objects. The key-value pairs are also called the "properties".




Properties can be accessed either using dot notation



const value = obj.someProperty;


or bracket notation, if the property name would not be a valid JavaScript identifier name [spec], or the name is the value of a variable:



// the space is not a valid character in identifier names
const value = obj["some Property"];


// property name as variable
const name = "some Property";
const value = obj[name];


For that reason, array elements can only be accessed using bracket notation:



const value = arr[5]; // arr.5 would be a syntax error


// property name / index as variable
const x = 5;
const value = arr[x];


Wait... what about JSON?



JSON is a textual representation of data, just like XML, YAML, CSV, and others. To work with such data, it first has to be converted to JavaScript data types, i.e. arrays and objects (and how to work with those was just explained). How to parse JSON is explained in the question Parse JSON in JavaScript? .



Further reading material




How to access arrays and objects is fundamental JavaScript knowledge and therefore it is advisable to read the MDN JavaScript Guide, especially the sections











Accessing nested data structures




A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation.



Here is an example:



const data = {
code: 42,
items: [{
id: 1,
name: 'foo'

}, {
id: 2,
name: 'bar'
}]
};


Let's assume we want to access the name of the second item.



Here is how we can do it step-by-step:




As we can see data is an object, hence we can access its properties using dot notation. The items property is accessed as follows:



data.items


The value is an array, to access its second element, we have to use bracket notation:



data.items[1]



This value is an object and we use dot notation again to access the name property. So we eventually get:



const item_name = data.items[1].name;


Alternatively, we could have used bracket notation for any of the properties, especially if the name contained characters that would have made it invalid for dot notation usage:



const item_name = data['items'][1]['name'];






I'm trying to access a property but I get only undefined back?



Most of the time when you are getting undefined, the object/array simply doesn't have a property with that name.



const foo = {bar: {baz: 42}};
console.log(foo.baz); // undefined



Use console.log or console.dir and inspect the structure of object / array. The property you are trying to access might be actually defined on a nested object / array.



console.log(foo.bar.baz); // 42





What if the property names are dynamic and I don't know them beforehand?




If the property names are unknown or we want to access all properties of an object / elements of an array, we can use the for...in [MDN] loop for objects and the for [MDN] loop for arrays to iterate over all properties / elements.



Objects



To iterate over all properties of data, we can iterate over the object like so:



for (const prop in data) {
// `prop` contains the name of each property, i.e. `'code'` or `'items'`
// consequently, `data[prop]` refers to the value of each property, i.e.
// either `42` or the array

}


Depending on where the object comes from (and what you want to do), you might have to test in each iteration whether the property is really a property of the object, or it is an inherited property. You can do this with Object#hasOwnProperty [MDN].



As alternative to for...in with hasOwnProperty, you can use Object.keys [MDN] to get an array of property names:



Object.keys(data).forEach(function(prop) {
// `prop` is the property name
// `data[prop]` is the property value

});


Arrays



To iterate over all elements of the data.items array, we use a for loop:



for(let i = 0, l = data.items.length; i < l; i++) {
// `i` will take on the values `0`, `1`, `2`,..., i.e. in each iteration
// we can access the next element in the array with `data.items[i]`, example:

//
// var obj = data.items[i];
//
// Since each element is an object (in our example),
// we can now access the objects properties with `obj.id` and `obj.name`.
// We could also use `data.items[i].id`.
}


One could also use for...in to iterate over arrays, but there are reasons why this should be avoided: Why is 'for(var item in list)' with arrays considered bad practice in JavaScript?.




With the increasing browser support of ECMAScript 5, the array method forEach [MDN] becomes an interesting alternative as well:



data.items.forEach(function(value, index, array) {
// The callback is executed for each element in the array.
// `value` is the element itself (equivalent to `array[index]`)
// `index` will be the index of the element in the array
// `array` is a reference to the array itself (i.e. `data.items` in this case)
});



In environments supporting ES2015 (ES6), you can also use the for...of [MDN] loop, which not only works for arrays, but for any iterable:



for (const item of data.items) {
// `item` is the array element, **not** the index
}


In each iteration, for...of directly gives us the next element of the iterable, there is no "index" to access or use.







What if the "depth" of the data structure is unknown to me?



In addition to unknown keys, the "depth" of the data structure (i.e. how many nested objects) it has, might be unknown as well. How to access deeply nested properties usually depends on the exact data structure.



But if the data structure contains repeating patterns, e.g. the representation of a binary tree, the solution typically includes to recursively [Wikipedia] access each level of the data structure.



Here is an example to get the first leaf node of a binary tree:




function getLeaf(node) {
if (node.leftChild) {
return getLeaf(node.leftChild); // <- recursive call
}
else if (node.rightChild) {
return getLeaf(node.rightChild); // <- recursive call
}
else { // node must be a leaf node
return node;
}

}

const first_leaf = getLeaf(root);




const root = {
leftChild: {
leftChild: {

leftChild: null,
rightChild: null,
data: 42
},
rightChild: {
leftChild: null,
rightChild: null,
data: 5
}
},

rightChild: {
leftChild: {
leftChild: null,
rightChild: null,
data: 6
},
rightChild: {
leftChild: null,
rightChild: null,
data: 7

}
}
};
function getLeaf(node) {
if (node.leftChild) {
return getLeaf(node.leftChild);
} else if (node.rightChild) {
return getLeaf(node.rightChild);
} else { // node must be a leaf node
return node;

}
}

console.log(getLeaf(root).data);





A more generic way to access a nested data structure with unknown keys and depth is to test the type of the value and act accordingly.




Here is an example which adds all primitive values inside a nested data structure into an array (assuming it does not contain any functions). If we encounter an object (or array) we simply call toArray again on that value (recursive call).



function toArray(obj) {
const result = [];
for (const prop in obj) {
const value = obj[prop];
if (typeof value === 'object') {
result.push(toArray(value)); // <- recursive call
}
else {

result.push(value);
}
}
return result;
}




const data = {

code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};



function toArray(obj) {
const result = [];
for (const prop in obj) {
const value = obj[prop];
if (typeof value === 'object') {
result.push(toArray(value));
} else {
result.push(value);
}

}
return result;
}

console.log(toArray(data));












Helpers



Since the structure of a complex object or array is not necessarily obvious, we can inspect the value at each step to decide how to move further. console.log [MDN] and console.dir [MDN] help us doing this. For example (output of the Chrome console):



> console.log(data.items)
[ Object, Object ]



Here we see that that data.items is an array with two elements which are both objects. In Chrome console the objects can even be expanded and inspected immediately.



> console.log(data.items[1])
Object
id: 2
name: "bar"
__proto__: Object



This tells us that data.items[1] is an object, and after expanding it we see that it has three properties, id, name and __proto__. The latter is an internal property used for the prototype chain of the object. The prototype chain and inheritance is out of scope for this answer, though.


c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...