Saturday 30 November 2019

parsing - PHP Version 5.2.14 / Parse error: syntax error, unexpected T_FUNCTION, expecting ')'

I have a certain piece of code that I'm trying to use with PHP Version 5.2.14 . Is it incompatible?? I run the following,


jailshell-3.2$ php -l /XYZ/functions.php

And it gives:



Parse error: syntax error, unexpected T_FUNCTION, expecting ')' in /XYZ/functions.php on line 2115
Errors parsing /XYZ/functions.php



The code is:


2114    $range = array_map(
2115 function (DatePeriod $p) use ($vt2) {
2116 $res = array();

echo - Strange print behaviour in PHP?




Why does the following code output 128?




print 4 << 5;
?>

Answer



Because it's a bitwise operator. I think it means 4 multiplied to 2^5 because that operator means




Shift the bits of $a $b steps to the left (each step means "multiply
by two")





so it's five steps. It's 4 * 2 * 2 * 2 * 2 * 2 (But I'm guessing here; everything happens at bit level).


ruby - Generate pseudo random string A-Z, 0-9



How can I generate an n-character pseudo random string containing only A-Z, 0-9 like SecureRandom.base64 without "+", "/", and "="? For example:



(0..n).map {(('1'..'9').to_a + ('A'..'Z').to_a)[rand(36)]}.join

Answer



Array.new(n){[*"A".."Z", *"0".."9"].sample}.join

Create a 100 number vector with random values in R rounded to 2 decimals

I need to do a pretty simple task,but since im not versed in R I don't know exactly how to. I have to create a vector of 100 numbers with random values from 0 to 1 with 2 DECIMAL numbers. I've tried this:




 x2 <- runif(100, 0.0, 1.0)


and it works great, but the numbers have 8 decimal numbers and I need them with only 2.

How to format a JavaScript date




How can I format a JavaScript date object to print as 10-Aug-2010?


Answer




Attention: There are better answers below. This answer was written in 2010 and newer and better solutions have arrived since. The OP should accept another answer.






function formatDate(date) {
var monthNames = [

"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
];

var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();


return day + ' ' + monthNames[monthIndex] + ' ' + year;
}

console.log(formatDate(new Date())); // show current date-time in console





You can edit the array monthNames to use Jan, Feb, Mar, etc..


insertafter - jQuery dynamically added elements cannot be removed





I have been trying to work out a solution to this issue, and have come across many similar posts online,.. but none with solutions that worked for my particular instance.



I'm using jQuery it 'inserAfter' within a group of elements. I can add the groups easily,.. but, I also have a remove() function called when a delete link is clicked,.. but nothing happens to the newly added elements, even though I can delete the other groups without problems.



I'm using jQuery's on() for the click function.. but, that still doesn't work on the dynamically added elements.




To reproduce the issue, go to the jsfiddle link below,
Click the ADD GROUP button and see a yellow group added to the DOM.
Now, hover over the yellow group to show the delete button.
Click the delete button and, tada... nothin'



Here is an example:



http://jsfiddle.net/revive/5MFRm/




jQuery(function($) { 

$( "#tabs" ).tabs();
$("#group0").hide();
$('.group-content').hide(); // Hide all group-content elements

function clonePanel() {
var panel=$("#tabs #group0").clone(false),
lastpanel = $("#tabs .group").last().index(),
newid = 'group'+(lastpanel+1);


panel.attr('id',newid).addClass('newpanel');
panel.insertAfter($("#tabs .group").last()).show();
}

$(".add-group").on('click',function(){
clonePanel();
});

$(".delete-group").on('click',function(){

$(this).closest('.group').fadeOut('slow', function(){$(this).closest('.group').remove(); });
// alert('done');
});

$('#tabs').on('click', '.group-title-toggle',function(){ // Add class "hover" on dt when hover
$(this).closest('.group-title').toggleClass('active').next().slideToggle(); // Toggle dd when the respective dt is clicked
});

});


Answer



That is what you are looking for: In jQuery, how to attach events to dynamic html elements?.



And here is your code working properly.
http://jsfiddle.net/5MFRm/2/



Instead of $('.add-group').on('click', function() {})



use this notation




$('body').on('click', '.add-group', function() {})


'twin-peaks' tag wiki - Movies & TV



Television show of the 90s involving solving the mystery of the death of a high school girl of the Pacific Northwest, Laura Palmer, and the supernatural events surrounding the principal suspects, their friends, and enemies.






There is no tag wiki for this tag … yet!



Tag wikis help introduce newcomers to the tag. They contain an overview of the topic defined by the tag, along with guidelines on its usage.



All registered users may propose new tag wikis.



(Note that if you have less than 20000 reputation, your tag wiki will be peer reviewed before it is published.)



scope - JavaScript closures vs. anonymous functions



A friend of mine and I are currently discussing what is a closure in JS and what isn't. We just want to make sure we really understand it correctly.



Let's take this example. We have a counting loop and want to print the counter variable on the console delayed. Therefore we use setTimeout and closures to capture the value of the counter variable to make sure that it will not print N times the value N.



The wrong solution without closures or anything near to closures would be:



for(var i = 0; i < 10; i++) {

setTimeout(function() {
console.log(i);
}, 1000);
}


which will of course print 10 times the value of i after the loop, namely 10.



So his attempt was:




for(var i = 0; i < 10; i++) {
(function(){
var i2 = i;
setTimeout(function(){
console.log(i2);
}, 1000)
})();
}



printing 0 to 9 as expected.



I told him that he isn't using a closure to capture i, but he insists that he is. I proved that he doesn't use closures by putting the for loop body within another setTimeout (passing his anonymous function to setTimeout), printing 10 times 10 again. The same applies if I store his function in a var and execute it after the loop, also printing 10 times 10. So my argument is that he doesn't really capture the value of i, making his version not a closure.



My attempt was:



for(var i = 0; i < 10; i++) {
setTimeout((function(i2){
return function() {
console.log(i2);

}
})(i), 1000);
}


So I capture i (named i2 within the closure), but now I return another function and pass this around. In my case, the function passed to setTimeout really captures i.



Now who is using closures and who isn't?



Note that both solutions print 0 to 9 on the console delayed, so they solve the original problem, but we want to understand which of those two solutions uses closures to accomplish this.



Answer



Editor's Note: All functions in JavaScript are closures as explained in this post. However we are only interested in identifying a subset of these functions which are interesting from a theoretical point of view. Henceforth any reference to the word closure will refer to this subset of functions unless otherwise stated.



A simple explanation for closures:




  1. Take a function. Let's call it F.

  2. List all the variables of F.

  3. The variables may be of two types:



    1. Local variables (bound variables)

    2. Non-local variables (free variables)


  4. If F has no free variables then it cannot be a closure.

  5. If F has any free variables (which are defined in a parent scope of F) then:


    1. There must be only one parent scope of F to which a free variable is bound.

    2. If F is referenced from outside that parent scope, then it becomes a closure for that free variable.


    3. That free variable is called an upvalue of the closure F.




Now let's use this to figure out who uses closures and who doesn't (for the sake of explanation I have named the functions):



Case 1: Your Friend's Program



for (var i = 0; i < 10; i++) {
(function f() {

var i2 = i;
setTimeout(function g() {
console.log(i2);
}, 1000);
})();
}


In the above program there are two functions: f and g. Let's see if they are closures:




For f:




  1. List the variables:


    1. i2 is a local variable.

    2. i is a free variable.

    3. setTimeout is a free variable.

    4. g is a local variable.


    5. console is a free variable.


  2. Find the parent scope to which each free variable is bound:


    1. i is bound to the global scope.

    2. setTimeout is bound to the global scope.

    3. console is bound to the global scope.


  3. In which scope is the function referenced? The global scope.



    1. Hence i is not closed over by f.

    2. Hence setTimeout is not closed over by f.

    3. Hence console is not closed over by f.




Thus the function f is not a closure.




For g:




  1. List the variables:


    1. console is a free variable.

    2. i2 is a free variable.


  2. Find the parent scope to which each free variable is bound:



    1. console is bound to the global scope.

    2. i2 is bound to the scope of f.


  3. In which scope is the function referenced? The scope of setTimeout.


    1. Hence console is not closed over by g.

    2. Hence i2 is closed over by g.





Thus the function g is a closure for the free variable i2 (which is an upvalue for g) when it's referenced from within setTimeout.



Bad for you: Your friend is using a closure. The inner function is a closure.



Case 2: Your Program



for (var i = 0; i < 10; i++) {

setTimeout((function f(i2) {
return function g() {
console.log(i2);
};
})(i), 1000);
}


In the above program there are two functions: f and g. Let's see if they are closures:




For f:




  1. List the variables:


    1. i2 is a local variable.

    2. g is a local variable.

    3. console is a free variable.



  2. Find the parent scope to which each free variable is bound:


    1. console is bound to the global scope.


  3. In which scope is the function referenced? The global scope.


    1. Hence console is not closed over by f.





Thus the function f is not a closure.



For g:




  1. List the variables:



    1. console is a free variable.

    2. i2 is a free variable.


  2. Find the parent scope to which each free variable is bound:


    1. console is bound to the global scope.

    2. i2 is bound to the scope of f.


  3. In which scope is the function referenced? The scope of setTimeout.



    1. Hence console is not closed over by g.

    2. Hence i2 is closed over by g.




Thus the function g is a closure for the free variable i2 (which is an upvalue for g) when it's referenced from within setTimeout.



Good for you: You are using a closure. The inner function is a closure.




So both you and your friend are using closures. Stop arguing. I hope I cleared the concept of closures and how to identify them for the both of you.



Edit: A simple explanation as to why are all functions closures (credits @Peter):



First let's consider the following program (it's the control):





lexicalScope();


function lexicalScope() {
var message = "This is the control. You should be able to see this message being alerted.";

regularFunction();

function regularFunction() {
alert(eval("message"));
}
}







  1. We know that both lexicalScope and regularFunction aren't closures from the above definition.

  2. When we execute the program we expect message to be alerted because regularFunction is not a closure (i.e. it has access to all the variables in its parent scope - including message).

  3. When we execute the program we observe that message is indeed alerted.




Next let's consider the following program (it's the alternative):





var closureFunction = lexicalScope();

closureFunction();

function lexicalScope() {
var message = "This is the alternative. If you see this message being alerted then in means that every function in JavaScript is a closure.";


return function closureFunction() {
alert(eval("message"));
};
}







  1. We know that only closureFunction is a closure from the above definition.

  2. When we execute the program we expect message not to be alerted because closureFunction is a closure (i.e. it only has access to all its non-local variables at the time the function is created (see this answer) - this does not include message).

  3. When we execute the program we observe that message is actually being alerted.



What do we infer from this?




  1. JavaScript interpreters do not treat closures differently from the way they treat other functions.

  2. Every function carries its scope chain along with it. Closures don't have a separate referencing environment.


  3. A closure is just like every other function. We just call them closures when they are referenced in a scope outside the scope to which they belong because this is an interesting case.


Combine several images algorithms

I'm looking for algorithms that can combine images based on a quality factor. For example, you have 50-100 photographies of the same scene, but some areas had bad quality in some image because artefacts or whatever.



Now for each pixel I select the best one with a quality factor based in darkness but for sure we have a lot off possible combinations and a lot a quality measures pixel/patch/image-based.



I'm trying to research about this topic but I don't found how to describe it properly, do you know some algorithms or at least which is de name of this "problem"?




Update: Note some desired pixels or pixel areas only appears in a few cases, e.g. in 10 of 100 images. It causes we can't use simple averaging or similar methods.

Javascript - read JSON Array without square brackets

So I got this JSON Object. And I would like to iterate throug all the Objects in nodes but the Objects the nodes Object is not formatet as an Array with []



I can access one after the other, if I know the name for example:



var X = Trend.L13




var node = X.nodes["AGENT.OBJECTS.House.SKL04_SK2.L13.Frost.AL01"]



But how do I iterate them?



var Trend = {


L13: {
dataArchive: "datavalues",
nodes: {

"AGENT.OBJECTS.House.SKL04_SK2.L13.Frost.AL01": {
visible: true,
axis: "left",
style: "Line",
color: "#66AF31",
linewidth: 1,
nonstop: true,
stairs: true,
configname: "L13",
address: "AGENT.OBJECTS.House.SKL04_SK2.L13.Frost.AL01",

text: "Frost"
},
"AGENT.OBJECTS.House.SKL04_SK2.L13.TempZul.MT01": {
visible: true,
axis: "right",
style: "Line",
color: "#8701AF",
linewidth: 1,
nonstop: true,
stairs: false,

configname: "L13",
address: "AGENT.OBJECTS.House.SKL04_SK2.L13.TempZul.MT01",
text: "Temp ZUL"
},
"AGENT.OBJECTS.House.SKL04_SK2.L13.PuWrg.SS01": {
visible: true,
axis: "left",
style: "Line",
color: "#000",
linewidth: 1,

nonstop: true,
stairs: true,
configname: "L13",
address: "AGENT.OBJECTS.House.SKL04_SK2.L13.PuWrg.SS01",
text: "PuWRG"
},
"AGENT.OBJECTS.House.SKL04_SK2.L13.TempWrgVl.MT01": {
visible: true,
axis: "right",
style: "Line",

color: "#FF2511",
linewidth: 1,
nonstop: false,
stairs: false,
configname: "L13",
address: "AGENT.OBJECTS.House.SKL04_SK2.L13.TempWrgVl.MT01",
text: "Temp. WRG Vorlauf"
},
"AGENT.OBJECTS.House.SKL04_SK2.L13.TempZulNachWRG.MT01": {
visible: true,

axis: "right",
style: "Line",
color: "#F99602",
linewidth: 1,
nonstop: false,
stairs: false,
configname: "L13",
address: "AGENT.OBJECTS.House.SKL04_SK2.L13.TempZulNachWRG.MT01",
text: "Temp. ZUL nach WRG"
},

"AGENT.OBJECTS.House.SKL04_SK2.L13.VtWrg.SS01": {
visible: true,
axis: "left",
style: "Line",
color: "#A5184A",
linewidth: 1,
nonstop: false,
stairs: true,
configname: "L13",
address: "AGENT.OBJECTS.House.SKL04_SK2.L13.VtWrg.SS01",

text: "VT WRG"
}
},
leftAxis: {
visible: "1",
autoScale: "1",
min: -3.7,
max: 37,
description: "Linke Achse"
},

rightAxis: {
visible: "1",
autoScale: "0",
min: 0,
max: 40,
description: "Rechte Achse"
},
time: {
startTime: 1453010899798,
endTime: 1453183699799,

lastTime: "1",
lastTimeValue: 2,
lastTimeUnit: "86400"
},
newnodes: {}
}
}

amazon ec2 - E-mail sent through PHP Mail() not received by Microsoft Outlook 365 Only

We have a web application which is using the php mail() function to send emails. Emails are received perfectly by all popular mail clients like gmail, yahoo, etc. but only outlook 365 not receiving any emails not even in Junk folder.




Amazon EC2, Ubuntu 14.04, Plesk 12, LAMP (Apache, MySQL and PHP)



We have checked email logs also but its not showing any errors. It looks like its sending email but its not received by Outlook 365 or they are blocking or something.



We have tried changing "\r\n" to "\n" but its also not working.



We have tried by changing SPF records but its also not working. http://365.webbrewers.com/blog/Lists/Posts/Post.aspx?ID=44



We have been trying to find out a solution everywhere including Microsoft Community, Plesk (Odin) Community, PHP Community, Ubuntu Community, Amazon EC2 Community and didn't find the work around.

Calling remove in foreach loop in Java





In Java, is it legal to call remove on a collection when iterating through the collection using a foreach loop? For instance:



List names = ....
for (String name : names) {
// Do something
names.remove(name).
}


As an addendum, is it legal to remove items that have not been iterated over yet? For instance,




//Assume that the names list as duplicate entries
List names = ....
for (String name : names) {
// Do something
while (names.remove(name));
}

Answer



To safely remove from a collection while iterating over it you should use an Iterator.




For example:



List names = ....
Iterator i = names.iterator();
while (i.hasNext()) {
String s = i.next(); // must be called before you can call i.remove()
// Do something
i.remove();
}



From the Java Documentation :




The iterators returned by this class's iterator and listIterator
methods are fail-fast: if the list is structurally modified at any
time after the iterator is created, in any way except through the
iterator's own remove or add methods, the iterator will throw a
ConcurrentModificationException. Thus, in the face of concurrent

modification, the iterator fails quickly and cleanly, rather than
risking arbitrary, non-deterministic behavior at an undetermined time
in the future.




Perhaps what is unclear to many novices is the fact that iterating over a list using the for/foreach constructs implicitly creates an iterator which is necessarily inaccessible. This info can be found here


Friday 29 November 2019

c++ - Difference between Object object = new Object() and Object object

If I have a class named Object, what's the difference between creating an instance just like that:



#include 

Object var;

main ()
{

var.test();
}


or



#include 

main ()
{

Object* var = new Object();
var->test();
}


Which is the differente between a global object (which you can use wherever you want) and create a dynamic object in the main.cpp? In theory it should be the same, right? The both method can be used in any file.cpp.

Switching the php extention to something else using apache?



I am writing a web application in php using Apache server. What I would like to do is have the index.php (and other files) display as *.aspx files, to confuse potential hackers.




Can this be done by editing the .htaccess file, and if so, what are the relevant lines to edit?


Answer



Serving the wrong file extension is not how you would achieve security, as it would not be enough to fool potential hackers. It might not even be enough to fool the guys at builtwith.com.



Instead of researching how to mislead the hackers with simple tricks, research on ways to secure your application better. You can start that at PHP.net and .



If you insist, you can use Apache mod_rewrite for that.



Something along this line (not tested):




RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.aspx -f
RewriteRule ^(.+).aspx$ /$1.php [L,QSA]


Otherwise, you can also add mime-type in Apache to serve *aspx files as PHP.




AddType application/x-httpd-php .aspx

swing - Java JFRAME button then new gui




So, I try to make a Java Program, that when you run it, the first screen will be welcome, under it button "login", under it "register". And now I need to figure how if I press one of these buttons, how can I call new GUI, which I will define somewhere. (e.g) i call register button and it calls new gui where is normal things that asks you when you register(login,email,pass,date of birth)



EDIT: problem solved, but there is a one more thing. How can I close the first window?



This is my code so far:



import javax.swing.*;
import java.awt.*;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.util.*;
import javax.swing.JFrame;
import java.awt.Dimension;
public class Gui extends JFrame
{
private JLabel lab1,lab2;
private JButton butt1,butt2;
private JPanel p1,p2;
public static void main(String[] args)
{
Gui okno = new Gui();
//vytáhne z defaultního monitoru width a height
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int width = (int) screenSize.getWidth();
int height = (int) screenSize.getHeight();
//velikost okna
Dimension appSize = new Dimension(210,250);
okno.setPreferredSize(appSize);
//nastavení na stred
okno.setLocation((width/2)-105,(height/2)-125);
okno.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
okno.setVisible(true);
//okno.setLocationRelativeTo(null); todle dá do středu obrazovky jen první body x a y od kterejch se to odvíjí
okno.setResizable(false);
okno.pack();

}

public Gui(){
super("Jméno hry vole");
setLayout(new BorderLayout(20,20));
/////////////////////////////////////////////////////////////////
// p1
p1 = new JPanel();
add(p1,BorderLayout.NORTH);
lab1 = new JLabel("Welcome",SwingConstants.CENTER); //centr labelu
lab2 = new JLabel("Created by DECHKR",SwingConstants.CENTER); //centr labelu
lab1.setFont(new Font("Serif", Font.PLAIN, 36)); //velikost fontu
p1.add(lab1);
//p2
p2 = new JPanel(new GridLayout(2,1,0,5));
add(p2,BorderLayout.SOUTH);

Dimension d = new Dimension(210,75);
butt1 = new JButton("Login");
butt1.setPreferredSize(d);
butt2 = new JButton("Register");
butt2.setPreferredSize(d);
p2.add(butt1);
p2.add(butt2);


butt1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
//Gui okno = new Gui();
//System.exit(0); endne celej jvm proces



}

});

butt2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){


}

});
}

Answer



I am still learning, but want to try and help.I would try making a new JFrame in the actionPerformed method of the listener. I also would probably make separate classes for your button action listeners otherwise you won't be able to perform separate task. I.E.



 class button1Listener implements ActionListener {
public void actionPerformed(ActionEvent ev){
JFrame frame = new JFrame();
(ETC CODE...)
}
}

Stop Font Color From Changing When Adding Conditional Formatting With VBA in Excel 2007

So I am adding conditional formatting to a column of cells that is dynamically created by the user with VBA. The problem I am having is that after the first format is added, any subsequent formatting will change the font color of the already formatted cells. There is some conditional formatting in the cells already that is copied from a master source that formats when cells = 0 or "Select One:" to be blue text in a yellow cell Below is the code I have so far:



With Range(Ltrs & 36, Ltrs & 41)

.FormatConditions.Add xlExpression, Formula1:="= $" & Ltrs & "$33 <> ""Custom" & OCV + 1 & """"
.FormatConditions(.FormatConditions.Count).SetFirstPriority
With .FormatConditions(1)
.Interior.Color = vbBlack
.Font.Color = vbBlack
.StopIfTrue = False
End With
End With

With Range(Ltrs & 42, Ltrs & 44)

.FormatConditions.Add xlExpression, Formula1:="=AND($" & Ltrs & "$29<>Repack1, $" & Ltrs & "$29<>Repack2)"
.FormatConditions(.FormatConditions.Count).SetFirstPriority
With .FormatConditions(1)
.Interior.Color = vbBlack
.Font.Color = vbBlack
.StopIfTrue = False
End With
End With

With Range(Ltrs & 45)

.FormatConditions.Add xlExpression, Formula1:="=AND($" & Ltrs & "$29<>Repack1, $" & Ltrs & "$29<>Repack2)"
.FormatConditions(.FormatConditions.Count).SetFirstPriority
With .FormatConditions(1)
.Interior.Color = vbBlack
.Font.Color = vbBlack
.StopIfTrue = False
End With
End With

With Range(Ltrs & 47)

.FormatConditions.Add Type:=xlTextString, String:="Enter", TextOperator:=xlContains
.FormatConditions(.FormatConditions.Count).SetFirstPriority
With .FormatConditions(1)
.Interior.Color = 13421823 'Light Red
.Font.Color = -14614363 'Dark Red/Brown
.StopIfTrue = False
End With
End With



This results in all cells with a 0 to be formatted with red text and all cells with "Select One:" to have black text while cells containing the value "Enter" have blue text. The strange thing is (at least to me) is that the interior cell colors are all still correct, it's just the font color that is wrong.

plot explanation - Why was Curt Connors in the sewer? - Movies & TV




After first injecting himself at Oscorp, Curt created his own lab in the sewer system later in the movie. If he was the head of the lab at Oscorp, couldn't he have just kept everyone out of the lab (he had already done this previously) and done all of his testing there, instead of doing it in the sewer?


Answer



The Lizard often retreats to the sewers, lives in the sewers in his appearances in the comic "The Amazing Spider-Man".



One of the more famous Lizard storyline The Gauntlet has him trying to get humans to act like Lizards, turn them into lizards. He does this whilst hiding in the sewer.



Practically this is useful for a reptile who likes wet/humid conditions whilst also eliminating to some degree Spider-Man's main asset which is his agility given the cramped confines. It also allows him to navigate the city quickly without drawing attention to his form.



The current story arc in the Amazing Spider-Man, which start in issue 688 (I think) features the Lizard who is found living in the sewer.




So I think the film was trying to replicate the character from the comic for those comic fans out there, like myself.


php new hosting with double quote error

I have just change my hosting, before all my PHP scripts worked fine



but now i get many mysql error like this:



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 column = \'value\' 


it seems that there is a double quote in some script




there is a way to resolve without update all my PHP scripts?



EDIT: example of PHP code



function test( $table,$column, $where ){

if( get_magic_quotes_gpc() ) { $where = strip_tags( trim( $where ) ); }
else{ $where = strip_tags( mysql_real_escape_string( trim( $where ) ) ); }


$where = "AND id = '" . $where . "' ";

$query = "SELECT " . $column . " FROM " . $table . " WHERE 1 " . $where . " LIMIT 1";
//...

asp.net - jquery how to deserialize json object




How can you deserialize this json object below?



[{"id":"67","name":"TestString"}]


I tried to do this below but couldnt succeed...



success: function (data, status) {
$.each(data, function (dt) {


var mydata = data.d;

alert(mydata); // returns [{"id":"67","name":"TestString"}]

$("#txt_speciality").tokenInput("add", mydata.id);
});
}



here is the way I am creating the json object



[WebMethod]
public static string get_specialities(string ProfessionalID)
{
Database db = DatabaseFactory.CreateDatabase("Connection String2");
DbCommand dbCommand;
dbCommand = db.GetStoredProcCommand("Select_Professionals_Speciality");
db.AddInParameter(dbCommand, "prof_id", DbType.Int16, Convert.ToInt16(ProfessionalID));
IDataReader dr = db.ExecuteReader(dbCommand);

//[{ id: 3, name: "test3" }]
string return_str="[";
int i = 0;
while (dr.Read()) {
if (i > 0)
return_str += ",";
return_str += "{\"id\":\"" + dr["SpecialtyID"].ToString().Trim() + "\",\"name\":\"" + dr["SpecialtyName"].ToString().Trim() + "\"}";
i++;
}
return_str += "]";

return return_str;
}

Answer



You can do this with:



var mydata; // [{"id":"67","name":"TestString"}]

var json = $.parseJSON(mydata);



the json variable will contain the de-serialized json object


Is there a Java library for calculating elapsed time?



I am wondering if there is a library one can use that calculates elapsed time? Something like... if you pass it a long of milliseconds, you get a result like "2d 5h 12m 55s" (possibly even more formats similarly to SimpleDateFormatter).




I've heard of jodatime, but I've never used it. Can it be used for such calculations, or are there other more appropriate libraries?



It's not like I can't knock up a few methods myself, but I find myself doing this every now and then and that's why I'm wondering if something like this already exists.


Answer



Use Joda time's Period & PeriodFormatter. Example.


What does [:-1] mean/do in python?




Working on a python assignment and was curious as to what [:-1] means in the context of the following code: instructions = f.readline()[:-1]



Have searched on here on S.O. and on Google but to no avail. Would love an explanation!



Answer



It slices the string to omit the last character, in this case a newline character:



>>> 'test\n'[:-1]
'test'


Since this works even on empty strings, it's a pretty safe way of removing that last character, if present:



>>> ''[:-1]

''


This works on any sequence, not just strings.



For lines in a text file, I’d actually use line.rstrip('\n') to only remove a newline; sometimes the last line in the file doesn’t end in a newline character and using slicing then removes whatever other character is last on that line.


java - What is the {L} Unicode category?




I came across some regular expressions that contain [^\\p{L}]. I understand that this is using some form of a Unicode category, but when I checked the documentation, I found only the following "L" categories:



Lu  Uppercase letter    UPPERCASE_LETTER
Ll Lowercase letter LOWERCASE_LETTER
Lt Titlecase letter TITLECASE_LETTER
Lm Modifier letter MODIFIER_LETTER
Lo Other letter OTHER_LETTER


What is L in this context?



Answer



Taken from this link: http://www.regular-expressions.info/unicode.html



Check the Unicode Character Properties section.




\p{L} matches a single code point in
the category "letter". If your input
string is à encoded as U+0061 U+0300,
it matches a without the accent. If

the input is à encoded as U+00E0, it
matches à with the accent. The reason
is that both the code points U+0061
(a) and U+00E0 (à) are in the category
"letter", while U+0300 is in the
category "mark".



javascript - jQuery blatantly ignoring the path I give to .getScript()



I have a script, TemplateLoader.js which loads 2 Mustache templates, and renders them on the page (or at least that's the goal).



My directory structure:



COMP266
Unit 4
scripts
mustache.min.js

TemplateLoader.js
PageUsingTemplateLoader.html


Inside of TemplateLoader (the object), I have the following chunk to load Mustache, and render the templates:



$.getScript("./scripts/mustache.min.js", function() {
$('head').html( Mustache.render(headTemplate, data) );
$('body').html( Mustache.render(bodyTemplate, data, uniqueBodyTemplate) );
});



This however, yields the following error in the developer console:




HTTP404: NOT FOUND - The server has not found anything matching the requested URI (Uniform Resource Identifier).
(XHR): GET - http://localhost:63342/COMP266/Unit%204/mustache.min.js?_=1450903391318




Oddly, it seems to have dropped the script folder completely from the path.




I decided to play around, so I changed the fetch path to (duplicating the script folder):



./scripts/scripts/mustache.min.js


But this yields:




HTTP404: NOT FOUND - The server has not found anything matching the requested URI (Uniform Resource Identifier).

(XHR): GET - http://localhost:63342/COMP266/Unit%204/scripts/scripts/mustache.min.js?_=1450903743022




Now it's listening! Unfortunately, this is obviously the wrong path.



I have no idea how to go about debugging this. It seems like jQuery is selectively dropping the scripts folder. That seems ridiculous, but just to make sure, I searched through the jQuery source, and couldn't find anything that would be doing the observed filtering of the path.



It's currently local, not hosted.



Can anyone give me a hint about what's going on here?



Answer



It turns out the issue was caused by me forgetting that my template added the mustache script (from a previous test), resulting in it being added twice.



I don't understand how this affected it though. It's not like the jQuery addition was succeeding while the template addition was causing the error, since changing the jQuery fetch path caused a direct change in the error message.



Sure enough though, when I removed the script import from the template, it worked.



I really don't understand how this caused a specific folder to be dropped from the path though.


How can I create a two dimensional array in JavaScript?



I have been reading online and some places say it isn't possible, some say it is and then give an example and others refute the example, etc.




  1. How do I declare a 2 dimensional array in JavaScript? (assuming it's possible)


  2. How would I access its members? (myArray[0][1] or myArray[0,1]?)



Answer






var items = [
[1, 2],
[3, 4],
[5, 6]
];
console.log(items[0][0]); // 1
console.log(items[0][1]); // 2
console.log(items[1][0]); // 3
console.log(items[1][1]); // 4

console.log(items);




Passing a 2D array to a C++ function




I have a function which I want to take, as a parameter, a 2D array of variable size.



So far I have this:



void myFunction(double** myArray){
myArray[x][y] = 5;
etc...
}



And I have declared an array elsewhere in my code:



double anArray[10][10];


However, calling myFunction(anArray) gives me an error.



I do not want to copy the array when I pass it in. Any changes made in myFunction should alter the state of anArray. If I understand correctly, I only want to pass in as an argument a pointer to a 2D array. The function needs to accept arrays of different sizes also. So for example, [10][10] and [5][5]. How can I do this?


Answer



There are three ways to pass a 2D array to a function:





  1. The parameter is a 2D array



    int array[10][10];
    void passFunc(int a[][10])
    {
    // ...
    }
    passFunc(array);


  2. The parameter is an array containing pointers



    int *array[10];
    for(int i = 0; i < 10; i++)
    array[i] = new int[10];
    void passFunc(int *a[10]) //Array containing pointers
    {
    // ...
    }

    passFunc(array);

  3. The parameter is a pointer to a pointer



    int **array;
    array = new int *[10];
    for(int i = 0; i <10; i++)
    array[i] = new int[10];
    void passFunc(int **a)
    {

    // ...
    }
    passFunc(array);


oop - Clone Object without reference javascript

I have a big object with much data. And i want to clone this in other variable. When i set some param of the instance B has the same result in the original object:



var obj = {a: 25, b: 50, c: 75};
var A = obj;
var B = obj;

A.a = 30;
B.a = 40;

alert(obj.a + " " + A.a + " " + B.a); // 40 40 40


My output should be 25 30 40.
Any ideas?



EDIT



Thanks Everyone. I change the code of dystroy and this is my result:



Object.prototype.clone = Array.prototype.clone = function()
{
if (Object.prototype.toString.call(this) === '[object Array]')
{
var clone = [];
for (var i=0; i clone[i] = this[i].clone();

return clone;
}
else if (typeof(this)=="object")
{
var clone = {};
for (var prop in this)
if (this.hasOwnProperty(prop))
clone[prop] = this[prop].clone();

return clone;
}
else
return this;
}

var obj = {a: 25, b: 50, c: 75};
var A = obj.clone();
var B = obj.clone();
A.a = 30;
B.a = 40;
alert(obj.a + " " + A.a + " " + B.a);

var arr = [25, 50, 75];
var C = arr.clone();
var D = arr.clone();
C[0] = 30;
D[0] = 40;
alert(arr[0] + " " + C[0] + " " + D[0]);

javascript - Error: The quota has been exceeded. on Safari IOS 10

I'm getting this error on my iPhone's safari, when doing localStorage.setItem('user',some string here):





Error: The quota has been exceeded.
setItem@[native code]




It is not private mode! What other circumstances can make localStorage not work?

java - NullPointerException on getActivity().runOnUiThread(new Runnable(){





I know there are many different causes for NPE but mine is slightly weird (At least to me).



So I have converted my Activities to Fragments successfully, but my problem appears to be coming from the function that displays the date. When the application is running, everything works just fine. But as soon as you press the back button. The app force closes, then in the log it says I'm getting NullPointerException at line 102. So looking at the code, I did research on this but unfortunately got nothing.



This is the line where the error is coming from when you press the back button.




getActivity().runOnUiThread(new Runnable(){


Also I have tried disabling the back button (As I'm building a launcher and it's not needed). But it doesn't seem to be working.



Here is the code for the whole date displaying method/function.



// (Calendar) Date function - Displays dateview on Card
final boolean keepRunning1 = true;
Thread thread_two = new Thread(){

@Override
public void run(){

while(keepRunning1){

// Make the thread wait half a second. If you want...
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Toast.makeText(getActivity().getApplicationContext(), "Default Signature Fail", Toast.LENGTH_LONG).show();

e.printStackTrace();
}

getActivity().runOnUiThread(new Runnable(){
@Override
public void run(){
TextView date = (TextView) getView().findViewById(R.id.date);
date.setText(DateUtils.formatDateTime(getActivity().getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR));
}
});

}
}
};

thread_two.start();


Thanks for your time, hopefully you can shed some light on what I'm doing wrong.



Logcat -




05-23 21:17:33.216: E/AndroidRuntime(6906): java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.FragmentActivity.runOnUiThread(java.lang.Runnable)' on a null object reference
05-23 21:17:33.216: E/AndroidRuntime(6906): at com.activelauncher.fragments.UtilsFragment$2.run(UtilsFragment.java:102)

Answer



I'm almost sure that this is caused when the thread finish its work but the activity is no longer visible.



You should check if the getActivity() call return null, and ...



To apply corrections on your code, look at this:




// (Calendar) Date function - Displays dateview on Card
final boolean keepRunning1 = true;
Thread thread_two = new Thread(){

@Override
public void run(){

while(keepRunning1){


// Make the thread wait half a second. If you want...
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Toast.makeText(getActivity().getApplicationContext(), "Default Signature Fail", Toast.LENGTH_LONG).show();
e.printStackTrace();
}

// here you check the value of getActivity() and break up if needed
if(getActivity() == null)

return;

getActivity().runOnUiThread(new Runnable(){
@Override
public void run(){
TextView date = (TextView) getView().findViewById(R.id.date);
date.setText(DateUtils.formatDateTime(getActivity().getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR));
}
});
}

}
};thread_two.start();

Thursday 28 November 2019

Android Studio 0.8.2 - Gradle project sync failed



In hindsight I should not have enabled L build stuff.




I am new to programming and I created a new Android Studio project which is throwing the Gradle errror right away.



Errors are:



yellow bar at the top - Gradle project sync failed. Basic functionality (e.g. editing, debugging) will not work properly. Try again Open Event Log Show Log in Finder



messages gradle sync - compileSdkVersion android-L requires compiling with JDK-7. open sdk settings, open file.



tried looking through google and other comments but did not find much I could make sense of except for Android Studio - Gradle sync project failed




tried converting URL to 1.10 instead of 1.12 and syncing but that failed after syncing



I need help either getting L working or removing it so that a new studio project can compile to device without errors.


Answer



I too faced the same issue and after days of trouble I figured it out. Just check if Java is installed




  • Open a Terminal window and type:




java -version



Any version above JDK 6 is OK




  • In terminal type



open -a TextEdit ~/.bash_profile





  • Copy and paste the following lines of into textedit



export JAVA_HOME=$(/usr/libexec/java_home)



export JDK_HOME=$(/usr/libexec/java_home)




  • Save it, close editor and type the following to apply changes




source ~/.bash_profile



Now try gradle sync now, you must be able to complete sync


php - Can't use method return value in write context




I would think the following piece of code should work, but it doesn't (Edited: Now works in PHP 5.5+):



if (!empty($r->getError()))


Where getError() is simply:



public function getError()
{
return $this->error;

}


Yet I end up with this error:




can't use method return value in write context




What does this mean? Isn't this just a read?



Answer



empty() needs to access the value by reference (in order to check whether that reference points to something that exists), and PHP before 5.5 didn't support references to temporary values returned from functions.



However, the real problem you have is that you use empty() at all, mistakenly believing that "empty" value is any different from "false".



Empty is just an alias for !isset($thing) || !$thing. When the thing you're checking always exists (in PHP results of function calls always exist), the empty() function is nothing but a negation operator.



PHP doesn't have concept of emptyness. Values that evaluate to false are empty, values that evaluate to true are non-empty. It's the same thing. This code:



$x = something();

if (empty($x)) …


and this:



$x = something();
if (!$x) …


has always the same result, in all cases, for all datatypes (because $x is defined empty() is redundant).




Return value from the method always exists (even if you don't have return statement, return value exists and contains null). Therefore:



if (!empty($r->getError()))


is logically equivalent to:



if ($r->getError())


css - css3 transition from width auto to "n" px

how do I apply css transition to a div which has initial width set as auto



However if I set the initial width to some number say 50px, the transition kicks in.




Here is the - DEMO



.container {
width: 200px;
background: red;
height: 50px;
}



.child1 {
background: black;
display: inline-block;

}

.child2 {
background: blue;
display: inline-block;
width: auto; /* this does not work */


/* width: 50px; */ /* this works */
float: right;
-webkit-transition: width 2s;
transition: width 2s;
}

.child2:hover {
width: 100px;
}

Python time vs datetime vs mxDateTime

WHy would I choose to use Python's time vs datetime (and also mxDateTime) when either way you can get the same result? For example,




time.localtime()[7]
datetime.date.today().timetuple()[7]


yields the same, mxDateTime can also produce same result.

python - Correct way to write line to file?



I'm used to doing print >>f, "hi there"




However, it seems that print >> is getting deprecated. What is the recommended way to do the line above?



Update:
Regarding all those answers with "\n"...is this universal or Unix-specific? IE, should I be doing "\r\n" on Windows?


Answer



This should be as simple as:



with open('somefile.txt', 'a') as the_file:
the_file.write('Hello\n')



From The Documentation:




Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single '\n' instead, on all platforms.




Some useful reading:





Python Counting Vowels

I have started on a program to count vowels and have seemed to be getting nowhere. I need to count vowels from a string and then display the vowels. I need to do this by storing the number of occurrences in variables. Like this :



    a = 0

b = 0
....

then print the lowest.


Current code (its not that much ):



string = str(input("please input a string:  "))
edit= ''.join(string)



print(edit)


I have tried a number of methods just by my self and don't seem to get anywhere.

c++ - Is it safe to store a pointer to an item in an std::set?





Is it possible to store a pointer to an element inside of an std::set?



For instance take the following unsafe example...



std::vector vec;
//add a bunch of items
int* ptr = &vec[10];
//add more items
std::cout << *ptr << std::endl;



In this case the memory which ptr points to could have been invalidated by adding extra elements to the vector causing it to reallocate. However if I had used a linked list instead of a vector I believe this would have been safe since it does not need to reallocate the nodes.



I want to use an std::set to save memory when dealing with redundant strings. Would the following example be safe? I think it would be for std::set but not for std::unordered_set.



const char* makeString(const char* s)
{
static std::set strings_pool;
return strings_pool.insert(s).first->c_str();
}



If the string c is not already in the strings_pool it is inserted otherwise it returns an iterator to the string already in the pool. In either case I get the value of the iterator and return the pointer to underlying cstring. I think that this is a safe operation but can someone confirm it.



At this link http://en.cppreference.com/w/cpp/container/set/insert it says "No iterators or references are invalidated." I think this means I can do it.



Also under the documentation for std::unordered_set it says "References are not invalidated." Does this means it is safe to use std::unordered_set as well?


Answer



Yes, both set and unordered_set are safe in this regard. If references are not invalidated, your pointers also remain valid.




It's an easy property for the node-based collections to maintain; unlike vector there's no need for them to move values around in memory.


x86 - To learn assembly - should I start with 32 bit or 64 bit?



I'm really wanting to learn assembly. I'm pretty good at c/c++, but want a better understanding of what's going on at a lower level.



I realize that assembly related questions have been asked before, but I'm just looking for some direction that's particular to my situation:



I'm running windows 7, and am confused about how I should start working with assembly. Do I have to start with x64 because I'm running windows 7? Some people have said 'start with 32 bit first' - how do I go about doing this? What does my operating system have to do with my ability to write assembly for '32' or '64' bit. In fact, what does 'n bit' assembly mean, where n is a number??







Edit:



Here are some links that have helped me get started with assembly; others who are just getting started may find them helpful. I'll keep updating this list as I continue on my assembly journey :)



Note: As I've been learning, I've decided to focus on programming with masm32. Therefore most of the below resources focus on that.




  • tag wiki (beginner guides, reference manuals, ABI documentation, and more.)

  • www.masm32.com

  • X86 Assembly WikiBook


  • X86 Dissassembly WikiBook (great for understanding some conventions, and the basics of how higher level code translates into assembly)

  • WinAsm IDE (plays nicely with masm32)

  • Intro: Assembly for Windows (all code examples are for masm32)

  • List of Interrupts

  • Assembly Tutorial (great for helping to understand core concepts)

  • x86 Assembly Guide

  • Agner Fog's Software optimization resources, including some good stuff about calling conventions on different platforms (Windows vs. Linux/OS X), as well as a lot of examples of how to do specific things efficiently. Not great for total beginners, but great for intermediate to advanced readers.



    (He also has detailed performance info for each instruction for Intel and AMD CPUs, excellent for serious performance micro-optimization. Some beginners might want to look at some of that to get started thinking about how CPUs work, and why you might do something one way instead of another.)




Answer



When people refer to 32-bit and 64-bit assembly, they're talking about which instruction set you'll use - they're also sometimes called Ia32 and x64 in the Intel case, which I presume you're asking about. There is a lot more going on in the 64-bit case, so starting with 32-bit is probably good; you just need to make sure you're assembling your program with a 32-bit assembler into a 32-bit binary. Windows will still know how to run it.



What I really recommend for getting started with assembly would be something with a simpler instruction set to get a handle on. Go learn MIPS assembly - the spim simulator is great and easy to use. If you really want to dive straight into the Intel assembly world, write yourself a little C program that calls your assembly routines for you; doing all the setup and teardown for a 'real program' is a big mess, and you won't even be able to get started there. So just write a C wrapper with main() in it, and compile and link that with the object files you get from writing your assembly code.



Please don't get in the habit of writing inline assembly in your C code - it's a code portability nightmare, and there's no reason for it.



You can download all of the Intel 64 and IA-32 Architectures Software Developer's Manuals to get started.


forms - What does "for" attribute do in HTML tag?




I wonder what is the difference between the following two code snippets:







and








I'm sure it does something when you use a special JavaScript library, but apart from that, does it validate the HTML or required for some other reason?


Answer



The tag allows you to click on the label, and it will be treated like clicking on the associated input element. There are two ways to create this association:



One way is to wrap the label element around the input element:






The other way is to use the for attribute, giving it the ID of the associated input:








This is especially useful for use with checkboxes and buttons, since it means you can check the box by clicking on the associated text instead of having to hit the box itself.



Read more about this element in MDN.


c++ - Uninitialized Error

c has an indeterminate value in your for loop here:



for(int c; x < c; c++)
^


you need to initialize it to a value for example:




for(int c=2; x < c; c++)


it will need to be greater than 0(perhaps 2 since you probably don't want 1 as a divisor) since you are using it in the modulus operation here:



if (x%c==0)


and modulus by 0 is undefined behavior as per the draft C++ standard section 5.6 Multiplicative operators paragraph 4 says:





[...]If the second operand of / or % is zero the behavior is undefined.[...]




It looks like you may have flipped your ending condition and it should go from c < x instead of x < c.

python - How to load large data into pandas efficiently?




I am working with a very wide dataset (1005 rows * 590,718 columns, 1.2G). Loading such a large dataset into a pandas dataframe result in code failure entirely due to insufficient memory.




I am aware that Spark is probably a good alternative to Pandas for dealing with large datasets, but is there any amenable solution in Pandas to reduce memory usage while loading large data?


Answer



You could use



pandas.read_csv(filename, chunksize = chunksize)

Java array is lost when exiting method



I'm relatively new to java, and the passing by reference without pointers confuses me a little. I wrote a function for homework that requires me to return the length of user input, and assign use input to an array that is passed in, when the method exits the user input array is lost, what is wrong.



public static int readArray(char[] intoArray)

{
char[] capture = captureInputAsCharArray(); //User input comes back as char[]
System.arraycopy(intoArray,0, capture, 0, capture.length);

return capture.length;
}

public static main(String[] args)
{
size = readArray(arrItem7); // item 7

System.out.println(size);
printOneInLine(arrItem7); // prints individual elements of array
}

Answer



Because you have the arguments to System.arraycopy() backwards.



http://download.oracle.com/javase/6/docs/api/java/lang/System.html



public static void arraycopy(Object src,

int srcPos,
Object dest,
int destPos,
int length)


Swap intoArray and capture:



System.arraycopy(capture,0, intoArray, 0, capture.length);


php - using prepared mysqli statements to bind parameters into the SELECT section of a query



I am building a web app that imports data from data feeds in php/mysql. I import the data into a buffer/temp holding table. As each data format is different I choose the column to select based on the particular source.



I am having trouble getting this query to work in this context :



$stmt = $this->dbObj->prepare("SELECT mk.PK_phone_maker, b.?, b.phoneDescription
b.thumbPic,

FROM buffer_table b left join mobile_phone pm on b.? = pm.phoneModel
LEFT JOIN phone_maker mk on mk.CompanyName = b.?
WHERE pm.phoneModel is null
group by b.?");
$stmt->bind_param('ssss',$phoneModelField, $phoneModelField, $phnMakerField,$phoneModelField);
$stmt->execute();


I recieve the error msg:




Fatal error: Call to a member function bind_param() on a non-object


This refers to the line:



 $stmt->bind_param('ssss',$phoneModelField, $phoneModelField, 


And I assume this is because the "prepare" on my sql hasnt worked as $stmt is not an object




As such it appears to me that you can not bind parameters to select columns and join fields, you can only bind to the where clause. Am I right in this assertion or am I missing something?


Answer



Prepared statements only allow you to bind values, other constructs (such as fields, tables or functions, let alone whole bits of SQL) are not allowed.


php - How to turn off magic quotes on shared hosting?



I want to turn off PHP's magic quotes. I don't have access to php.ini.




When I tried to add php_flag magic_quotes_gpc off to my .htaccess file, I get a 500 internal server error. This is what my .htaccess file looks like:



AddType x-mapp-php5 .php
php_flag magic_quotes_gpc off


Then I tried to use ini_set('magic_quotes_gpc', 'O'), but that had no effect.



How do I turn magic quotes off?


Answer




As per the manual you can often install a custom php.ini on shared hosting, where mod_php isn't used and the php_value directive thus leads to an error. For suexec/FastCGI setups it is quite common to have a per-webspace php.ini in any case.



--



I don't think O (uppercase letter o) is a valid value to set an ini flag. You need to use a true/false, 1/0, or "on"/"off" value.



ini_set( 'magic_quotes_gpc', 0 );   // doesn't work


EDIT




After checking the list of ini settings, I see that magic_quotes_gpc is a PHP_INI_PERDIR setting (after 4.2.3), which means you can't change it with ini_set() (only PHP_INI_ALL settings can be changed with ini_set())



What this means is you have to use an .htaccess file to do this - OR - implement a script to reverse the effects of magic quotes. Something like this



if ( in_array( strtolower( ini_get( 'magic_quotes_gpc' ) ), array( '1', 'on' ) ) )
{
$_POST = array_map( 'stripslashes', $_POST );
$_GET = array_map( 'stripslashes', $_GET );
$_COOKIE = array_map( 'stripslashes', $_COOKIE );

}

php - Get all value of h1 tag

I want to get all value of h1 tag and I found this article: getting all values from h1 tags using php



Then I tried to using:



include "functions/simple_html_dom.php";

function getTextBetweenTags($string, $tagname) {
// Create DOM from string
$html = str_get_html($string);

$titles = array();
// Find all tags
foreach($html->find($tagname) as $element) {
$titles[] = $element->plaintext;
}
return $titles;

}
echo getTextBetweenTags("http://mydomain.com/","h1");
?>


But it's not running and I get:




Notice: Array to string conversion in C:\xampp\htdocs\checker\abc.php
on line 14 Array





Plz help me fix it. I want to get all h1 tag of a website with input data is URL of that website. Thanks so much!

javascript - iOS6 - Is there a way to clear cached ajax POST requests for webapp added to home screen?

iOS6 ajax POST request caching is becoming a huge problem for our webApp. Most of our users have added the app to the home screen. Ever since the upgrade, most of the POST requests to the backend are not working and data is stale from over 6 days ago and counting. We are aware of two workarounds to resolve this, one is to change every POST request so that it's different by adding a timestamp or some random input to it, and the second is to disable caching on the webserver.




Both workarounds are detailed in the following post:
Is Safari on iOS 6 caching $.ajax results?



Turning off caching on the webserver would have solved the issue if it was set before the iOS6 upgrade (or right after). However, it seems any POST requests that were made since the upgrade and until the time we turned caching off from apps added to the home screen, are still cached! and we can't find a way to clear them. removing the home screen app and restarting the device doesn't do the trick! The only option we have is to change our URL or to add a timestamp to every request in addition to turning off caching on the webserver.



Does anyone know of a way to clear a home screen app cache, aside from restoring to factory? please provide details.



Warning to anyone who implemented a workaround by adding a timestamp to their requests without turning off caching on the server. If your app is added to the home screen, EVERY post response will now be cached and it doesn't seem to expire. Unless someone has a way to clear it, this looks like a potential memory leak!

Wednesday 27 November 2019

templates - Pretty-print C++ STL containers



Please take note of the updates at the end of this post.



Update: I have created a public project on GitHub for this library!






I would like to have a single template that once and for all takes care of pretty-printing all STL containers via operator<<. In pseudo code, I'm looking for something like this:



template
std::ostream & operator<<(std::ostream & o, const C & x)
{
o << open;
// for (typename C::const_iterator i = x.begin(); i != x.end(); i++) /* Old-school */
for (auto i = x.begin(); i != x.end(); i++)
{
if (i != x.begin()) o << delim;
o << *i;
}
o << close;
return o;
}


Now I've seen plenty of template magic here on SO that I never thought possible, so I'm wondering if anyone can suggest something that would match all containers C. Maybe something trait-ish that can figure out if something has the necessary iterator?



Many thanks!






Update (and solution)



After raising this problem again on Channel 9, I got a fantastic answer from Sven Groot, which, combined with a bit of SFINAE type traiting, appears to solve the problem in a completely general and nestable fashion. The delimiters may be individually specialised, an example specialization for std::set is included, as well as an example of using custom delimiters.



The helper "wrap_array()" can be used to print raw C arrays. Update: Pairs and tuples are available for printing; default delimiters are round brackets.



The enable-if type trait requires C++0x, but with some modifications it should be possible to make a C++98 version of this. Tuples require variadic templates, hence C++0x.



I have asked Sven to post the solution here so that I can accept it, but in the meantime I'd like to post the code myself for reference. (Update: Sven has now posted his code below, which I made the accepted answer. My own code uses container type traits, which work for me but may cause unexpected behaviour with non-container classes that provide iterators.)



Header (prettyprint.h):



#ifndef H_PRETTY_PRINT
#define H_PRETTY_PRINT


#include
#include
#include
#include


namespace std
{
// Pre-declarations of container types so we don't actually have to include the relevant headers if not needed, speeding up compilation time.
template class set;
}

namespace pretty_print
{

// SFINAE type trait to detect a container based on whether T::const_iterator exists.
// (Improvement idea: check also if begin()/end() exist.)

template
struct is_container_helper
{
private:
template static char test(typename C::const_iterator*);
template static int test(...);
public:
static const bool value = sizeof(test(0)) == sizeof(char);
};


// Basic is_container template; specialize to derive from std::true_type for all desired container types

template struct is_container : public ::std::integral_constant::value> { };


// Holds the delimiter values for a specific character type

template
struct delimiters_values
{
typedef TChar char_type;
const TChar * prefix;
const TChar * delimiter;
const TChar * postfix;
};


// Defines the delimiter values for a specific container and character type

template
struct delimiters
{
typedef delimiters_values type;
static const type values;
};


// Default delimiters

template struct delimiters { static const delimiters_values values; };
template const delimiters_values delimiters::values = { "[", ", ", "]" };
template struct delimiters { static const delimiters_values values; };
template const delimiters_values delimiters::values = { L"[", L", ", L"]" };


// Delimiters for set

template struct delimiters< ::std::set, char> { static const delimiters_values values; };
template const delimiters_values delimiters< ::std::set, char>::values = { "{", ", ", "}" };
template struct delimiters< ::std::set, wchar_t> { static const delimiters_values values; };
template const delimiters_values delimiters< ::std::set, wchar_t>::values = { L"{", L", ", L"}" };


// Delimiters for pair (reused for tuple, see below)

template struct delimiters< ::std::pair, char> { static const delimiters_values values; };
template const delimiters_values delimiters< ::std::pair, char>::values = { "(", ", ", ")" };
template struct delimiters< ::std::pair, wchar_t> { static const delimiters_values values; };
template const delimiters_values delimiters< ::std::pair, wchar_t>::values = { L"(", L", ", L")" };


// Functor to print containers. You can use this directly if you want to specificy a non-default delimiters type.

template, typename TDelimiters = delimiters>
struct print_container_helper
{
typedef TChar char_type;
typedef TDelimiters delimiters_type;
typedef std::basic_ostream & ostream_type;

print_container_helper(const T & container)
: _container(container)
{
}

inline void operator()(ostream_type & stream) const
{
if (delimiters_type::values.prefix != NULL)
stream << delimiters_type::values.prefix;

for (typename T::const_iterator beg = _container.begin(), end = _container.end(), it = beg; it != end; ++it)
{
if (it != beg && delimiters_type::values.delimiter != NULL)
stream << delimiters_type::values.delimiter;

stream << *it;
}

if (delimiters_type::values.postfix != NULL)
stream << delimiters_type::values.postfix;
}

private:
const T & _container;
};


// Type-erasing helper class for easy use of custom delimiters.
// Requires TCharTraits = std::char_traits and TChar = char or wchar_t, and MyDelims needs to be defined for TChar.
// Usage: "cout << pretty_print::custom_delims(x)".

struct custom_delims_base
{
virtual ~custom_delims_base() { }
virtual ::std::ostream & stream(::std::ostream &) = 0;
virtual ::std::wostream & stream(::std::wostream &) = 0;
};

template
struct custom_delims_wrapper : public custom_delims_base
{
custom_delims_wrapper(const T & t) : t(t) { }

::std::ostream & stream(::std::ostream & stream)
{
return stream << ::pretty_print::print_container_helper, Delims>(t);
}
::std::wostream & stream(::std::wostream & stream)
{
return stream << ::pretty_print::print_container_helper, Delims>(t);
}

private:
const T & t;
};

template
struct custom_delims
{
template custom_delims(const Container & c) : base(new custom_delims_wrapper(c)) { }
~custom_delims() { delete base; }
custom_delims_base * base;
};

} // namespace pretty_print


template
inline std::basic_ostream & operator<<(std::basic_ostream & stream, const pretty_print::custom_delims & p)
{
return p.base->stream(stream);
}


// Template aliases for char and wchar_t delimiters
// Enable these if you have compiler support
//
// Implement as "template const sdelims::type sdelims>::values = { ... }."

//template using pp_sdelims = pretty_print::delimiters;
//template using pp_wsdelims = pretty_print::delimiters;


namespace std
{
// Prints a print_container_helper to the specified stream.

template
inline basic_ostream & operator<<(basic_ostream & stream,
const ::pretty_print::print_container_helper & helper)
{
helper(stream);
return stream;
}

// Prints a container to the stream using default delimiters

template
inline typename enable_if< ::pretty_print::is_container::value, basic_ostream&>::type
operator<<(basic_ostream & stream, const T & container)
{
return stream << ::pretty_print::print_container_helper(container);
}

// Prints a pair to the stream using delimiters from delimiters>.
template
inline basic_ostream & operator<<(basic_ostream & stream, const pair & value)
{
if (::pretty_print::delimiters, TChar>::values.prefix != NULL)
stream << ::pretty_print::delimiters, TChar>::values.prefix;

stream << value.first;

if (::pretty_print::delimiters, TChar>::values.delimiter != NULL)
stream << ::pretty_print::delimiters, TChar>::values.delimiter;

stream << value.second;

if (::pretty_print::delimiters, TChar>::values.postfix != NULL)
stream << ::pretty_print::delimiters, TChar>::values.postfix;

return stream;
}
} // namespace std

// Prints a tuple to the stream using delimiters from delimiters>.

namespace pretty_print
{
struct tuple_dummy_t { }; // Just if you want special delimiters for tuples.

typedef std::pair tuple_dummy_pair;

template
struct pretty_tuple_helper
{
static inline void print(::std::basic_ostream & stream, const Tuple & value)
{
pretty_tuple_helper::print(stream, value);

if (delimiters::values.delimiter != NULL)
stream << delimiters::values.delimiter;

stream << std::get(value);
}
};

template
struct pretty_tuple_helper
{
static inline void print(::std::basic_ostream & stream, const Tuple & value) { stream << ::std::get<0>(value); }
};
} // namespace pretty_print


namespace std
{
template
inline basic_ostream & operator<<(basic_ostream & stream, const tuple & value)
{
if (::pretty_print::delimiters< ::pretty_print::tuple_dummy_pair, TChar>::values.prefix != NULL)
stream << ::pretty_print::delimiters< ::pretty_print::tuple_dummy_pair, TChar>::values.prefix;

::pretty_print::pretty_tuple_helper &, sizeof...(Args), TChar, TCharTraits>::print(stream, value);

if (::pretty_print::delimiters< ::pretty_print::tuple_dummy_pair, TChar>::values.postfix != NULL)
stream << ::pretty_print::delimiters< ::pretty_print::tuple_dummy_pair, TChar>::values.postfix;

return stream;
}
} // namespace std


// A wrapper for raw C-style arrays. Usage: int arr[] = { 1, 2, 4, 8, 16 }; std::cout << wrap_array(arr) << ...

namespace pretty_print
{
template
struct array_wrapper
{
typedef const T * const_iterator;
typedef T value_type;

array_wrapper(const T (& a)[N]) : _array(a) { }
inline const_iterator begin() const { return _array; }
inline const_iterator end() const { return _array + N; }

private:
const T * const _array;
};
} // namespace pretty_print

template
inline pretty_print::array_wrapper pretty_print_array(const T (& a)[N])
{
return pretty_print::array_wrapper(a);
}


#endif


Usage example:



#include 
#include
#include
#include
#include
#include
#include
#include
#include

#include "prettyprint.h"

// Specialization for a particular container
template<> const pretty_print::delimiters_values pretty_print::delimiters, char>::values = { "|| ", " : ", " ||" };

// Custom delimiters for one-off use
struct MyDel { static const delimiters_values values; };
const delimiters_values MyDel::values = { "<", "; ", ">" };

int main(int argc, char * argv[])
{
std::string cs;
std::unordered_map um;
std::map om;
std::set ss;
std::vector v;
std::vector> vv;
std::vector> vp;
std::vector vd;
v.reserve(argc - 1);
vv.reserve(argc - 1);
vp.reserve(argc - 1);
vd.reserve(argc - 1);

std::cout << "Printing pairs." << std::endl;

while (--argc)
{
std::string s(argv[argc]);
std::pair p(argc, s);

um[argc] = s;
om[argc] = s;
v.push_back(s);
vv.push_back(v);
vp.push_back(p);
vd.push_back(1./double(i));
ss.insert(s);
cs += s;

std::cout << " " << p << std::endl;
}

std::array a{{ 'h', 'e', 'l', 'l', 'o' }};

std::cout << "Vector: " << v << std::endl
<< "Incremental vector: " << vv << std::endl
<< "Another vector: " << vd << std::endl
<< "Pairs: " << vp << std::endl
<< "Set: " << ss << std::endl
<< "OMap: " << om << std::endl
<< "UMap: " << um << std::endl
<< "String: " << cs << std::endl
<< "Array: " << a << std::endl
;

// Using custom delimiters manually:
std::cout << pretty_print::print_container_helper, char, std::char_traits, MyDel>(v) << std::endl;

// Using custom delimiters with the type-erasing helper class
std::cout << pretty_print::custom_delims(v) << std::endl;

// Pairs and tuples and arrays:
auto a1 = std::make_pair(std::string("Jello"), 9);
auto a2 = std::make_tuple(1729);
auto a3 = std::make_tuple("Qrgh", a1, 11);
auto a4 = std::make_tuple(1729, 2875, std::pair(1.5, "meow"));
int arr[] = { 1, 4, 9, 16 };

std::cout << "C array: " << wrap_array(arr) << std::endl
<< "Pair: " << a1 << std::endl
<< "1-tuple: " << a2 << std::endl
<< "n-tuple: " << a3 << std::endl
<< "n-tuple: " << a4 << std::endl
;
}


Further ideas for improvements:




  • Implement output for std::tuple<...> in the same way is we have it for std::pair. Update: This is now a separate question on SO! Upupdate: This has now been implemented, thanks to Xeo!

  • Add namespaces so that the helper classes don't bleed into the global namespace. Done

  • Add template aliases (or something similar) to facilitate making custom delimiter classes, or maybe preprocessor macros?



Recent updates:




  • I removed the custom output iterator in favour of a simple for loop in the print function.

  • All implementation details are now in the pretty_print namespace. Only the global stream operators and the pretty_print_array wrapper are in the global namespace.

  • Fixed the namespacing so that operator<< is now correctly in std.



Notes:




  • Removing the output iterator means that there is no way to use std::copy() to get pretty-printing. I might reinstate the pretty iterator if this is a desired feature, but Sven's code below has the implementation.

  • It was a conscious design decision to make the delimiters compile-time constants rather than object constants. That means that you cannot supply delimiters dynamically at runtime, but it also means that there's no unneeded overhead. An object-based delimiter configuration has been proposed by Dennis Zickefoose in a comment to Sven's code below. If desired, this could be implemented as an alternative feature.

  • It is currently not obvious how to customize nested container delimiters.

  • Bear in mind that the purpose of this library is to allow quick container printing facilities that require zero coding on your part. It is not an all-purpose formatting library, but rather a developing tool to alleviate the need to write boiler-plate code for container inspection.



Thank you to everyone who contributed!






Note: If you are looking for a quick way to deploy custom delimiters, here is one way using type erasure. We assume that you have already constructed a delimiter class, say MyDel, like so:



struct MyDel { static const pretty_print::delimiters_values values; };
const pretty_print::delimiters_values MyDel::values = { "<", "; ", ">" };


Now we want to be able to write std::cout << MyPrinter(v) << std::endl; for some container v using those delimiters. MyPrinter will be a type-erasing class, like so:



struct wrapper_base
{
virtual ~wrapper_base() { }
virtual std::ostream & stream(std::ostream & o) = 0;
};

template
struct wrapper : public wrapper_base
{
wrapper(const T & t) : t(t) { }
std::ostream & stream(std::ostream & o)
{
return o << pretty_print::print_container_helper, Delims>(t);
}
private:
const T & t;
};

template
struct MyPrinter
{
template MyPrinter(const Container & c) : base(new wrapper(c)) { }
~MyPrinter() { delete base; }
wrapper_base * base;
};

template
std::ostream & operator<<(std::ostream & o, const MyPrinter & p) { return p.base->stream(o); }

Answer



This solution was inspired by Marcelo's solution, with a few changes:



#include 
#include
#include
#include
#include

// This works similar to ostream_iterator, but doesn't print a delimiter after the final item
template >
class pretty_ostream_iterator : public std::iterator
{
public:
typedef TChar char_type;
typedef TCharTraits traits_type;
typedef std::basic_ostream ostream_type;

pretty_ostream_iterator(ostream_type &stream, const char_type *delim = NULL)
: _stream(&stream), _delim(delim), _insertDelim(false)
{
}

pretty_ostream_iterator& operator=(const T &value)
{
if( _delim != NULL )
{
// Don't insert a delimiter if this is the first time the function is called
if( _insertDelim )
(*_stream) << _delim;
else
_insertDelim = true;
}
(*_stream) << value;
return *this;
}

pretty_ostream_iterator& operator*()
{
return *this;
}

pretty_ostream_iterator& operator++()
{
return *this;
}

pretty_ostream_iterator& operator++(int)
{
return *this;
}
private:
ostream_type *_stream;
const char_type *_delim;
bool _insertDelim;
};

#if _MSC_VER >= 1400

// Declare pretty_ostream_iterator as checked
template
struct std::_Is_checked_helper > : public std::tr1::true_type
{
};

#endif // _MSC_VER >= 1400

namespace std
{
// Pre-declarations of container types so we don't actually have to include the relevant headers if not needed, speeding up compilation time.
// These aren't necessary if you do actually include the headers.
template class vector;
template class list;
template class set;
template class map;
}

// Basic is_container template; specialize to derive from std::true_type for all desired container types
template struct is_container : public std::false_type { };

// Mark vector as a container
template struct is_container > : public std::true_type { };

// Mark list as a container
template struct is_container > : public std::true_type { };

// Mark set as a container
template struct is_container > : public std::true_type { };

// Mark map as a container
template struct is_container > : public std::true_type { };

// Holds the delimiter values for a specific character type
template
struct delimiters_values
{
typedef TChar char_type;
const TChar *prefix;
const TChar *delimiter;
const TChar *postfix;
};

// Defines the delimiter values for a specific container and character type
template
struct delimiters
{
static const delimiters_values values;
};

// Default delimiters
template struct delimiters { static const delimiters_values values; };
template const delimiters_values delimiters::values = { "{ ", ", ", " }" };
template struct delimiters { static const delimiters_values values; };
template const delimiters_values delimiters::values = { L"{ ", L", ", L" }" };

// Delimiters for set
template struct delimiters, char> { static const delimiters_values values; };
template const delimiters_values delimiters, char>::values = { "[ ", ", ", " ]" };
template struct delimiters, wchar_t> { static const delimiters_values values; };
template const delimiters_values delimiters, wchar_t>::values = { L"[ ", L", ", L" ]" };

// Delimiters for pair
template struct delimiters, char> { static const delimiters_values values; };
template const delimiters_values delimiters, char>::values = { "(", ", ", ")" };
template struct delimiters, wchar_t> { static const delimiters_values values; };
template const delimiters_values delimiters, wchar_t>::values = { L"(", L", ", L")" };

// Functor to print containers. You can use this directly if you want to specificy a non-default delimiters type.
template, typename TDelimiters = delimiters >
struct print_container_helper
{
typedef TChar char_type;
typedef TDelimiters delimiters_type;
typedef std::basic_ostream& ostream_type;

print_container_helper(const T &container)
: _container(&container)
{
}

void operator()(ostream_type &stream) const
{
if( delimiters_type::values.prefix != NULL )
stream << delimiters_type::values.prefix;
std::copy(_container->begin(), _container->end(), pretty_ostream_iterator(stream, delimiters_type::values.delimiter));
if( delimiters_type::values.postfix != NULL )
stream << delimiters_type::values.postfix;
}
private:
const T *_container;
};

// Prints a print_container_helper to the specified stream.
template
std::basic_ostream& operator<<(std::basic_ostream &stream, const print_container_helper &helper)
{
helper(stream);
return stream;
}

// Prints a container to the stream using default delimiters
template
typename std::enable_if::value, std::basic_ostream&>::type
operator<<(std::basic_ostream &stream, const T &container)
{
stream << print_container_helper(container);
return stream;
}

// Prints a pair to the stream using delimiters from delimiters>.
template
std::basic_ostream& operator<<(std::basic_ostream &stream, const std::pair &value)
{
if( delimiters, TChar>::values.prefix != NULL )
stream << delimiters, TChar>::values.prefix;

stream << value.first;

if( delimiters, TChar>::values.delimiter != NULL )
stream << delimiters, TChar>::values.delimiter;

stream << value.second;

if( delimiters, TChar>::values.postfix != NULL )
stream << delimiters, TChar>::values.postfix;
return stream;
}

// Used by the sample below to generate some values
struct fibonacci
{
fibonacci() : f1(0), f2(1) { }
int operator()()
{
int r = f1 + f2;
f1 = f2;
f2 = r;
return f1;
}
private:
int f1;
int f2;
};

int main()
{
std::vector v;
std::generate_n(std::back_inserter(v), 10, fibonacci());

std::cout << v << std::endl;

// Example of using pretty_ostream_iterator directly
std::generate_n(pretty_ostream_iterator(std::cout, ";"), 20, fibonacci());
std::cout << std::endl;
}


Like Marcelo's version, it uses an is_container type trait that must be specialized for all containers that are to be supported. It may be possible to use a trait to check for value_type, const_iterator, begin()/end(), but I'm not sure I'd recommend that since it might match things that match those criteria but aren't actually containers, like std::basic_string. Also like Marcelo's version, it uses templates that can be specialized to specify the delimiters to use.



The major difference is that I've built my version around a pretty_ostream_iterator, which works similar to the std::ostream_iterator but doesn't print a delimiter after the last item. Formatting the containers is done by the print_container_helper, which can be used directly to print containers without an is_container trait, or to specify a different delimiters type.



I've also defined is_container and delimiters so it will work for containers with non-standard predicates or allocators, and for both char and wchar_t. The operator<< function itself is also defined to work with both char and wchar_t streams.



Finally, I've used std::enable_if, which is available as part of C++0x, and works in Visual C++ 2010 and g++ 4.3 (needs the -std=c++0x flag) and later. This way there is no dependency on Boost.


php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...