Wednesday, 30 November 2016

python - Removing duplicates in lists



Pretty much I need to write a program to check if a list has any duplicates and if it does it removes them and returns a new list with the items that weren't duplicated/removed. This is what I have but to be honest I do not know what to do.




def remove_duplicates():
t = ['a', 'b', 'c', 'd']
t2 = ['a', 'c', 'd']
for t in t2:
t.append(t.remove())
return t

Answer



The common approach to get a unique collection of items is to use a set. Sets are unordered collections of distinct objects. To create a set from any iterable, you can simply pass it to the built-in set() function. If you later need a real list again, you can similarly pass the set to the list() function.




The following example should cover whatever you are trying to do:



>>> t = [1, 2, 3, 1, 2, 5, 6, 7, 8]
>>> t
[1, 2, 3, 1, 2, 5, 6, 7, 8]
>>> list(set(t))
[1, 2, 3, 5, 6, 7, 8]
>>> s = [1, 2, 3]
>>> list(set(t) - set(s))
[8, 5, 6, 7]



As you can see from the example result, the original order is not maintained. As mentioned above, sets themselves are unordered collections, so the order is lost. When converting a set back to a list, an arbitrary order is created.



Maintaining order



If order is important to you, then you will have to use a different mechanism. A very common solution for this is to rely on OrderedDict to keep the order of keys during insertion:



>>> from collections import OrderedDict
>>> list(OrderedDict.fromkeys(t))

[1, 2, 3, 5, 6, 7, 8]


Starting with Python 3.7, the built-in dictionary is guaranteed to maintain the insertion order as well, so you can also use that directly if you are on Python 3.7 or later (or CPython 3.6):



>>> list(dict.fromkeys(t))
[1, 2, 3, 5, 6, 7, 8]


Note that this may have some overhead of creating a dictionary first, and then creating a list from it. If you don’t actually need to preserve the order, you’re often better off using a set, especially because it gives you a lot more operations to work with. Check out this question for more details and alternative ways to preserve the order when removing duplicates.







Finally note that both the set as well as the OrderedDict/dict solutions require your items to be hashable. This usually means that they have to be immutable. If you have to deal with items that are not hashable (e.g. list objects), then you will have to use a slow approach in which you will basically have to compare every item with every other item in a nested loop.


reactjs - Unable to run a function inside another function: Cannot read property 'test' of undefined / Cannot read property 'setState' of undefined



I want to run a callback test() from the onClose() function. I tried to find the solution across StackOverflow but I was unable to solve the problem. Running this code gives me undefined errors mentioned in the comments with codeblocks



constructor(props){

super(props)
this.state = {
isPaid: false
}
this.test = this.test.bind(this)
}
test = () =>{
const { isPaid } = this.state
console.log(isPaid)
this.setState({isPaid: true})

}

render() {
const isPaid = this.state
const {test} = this.props
let config = {
"publicKey": "*****",
"productIdentity": "1234567890",
"eventHandler": {
onSuccess (payload) {

console.log(payload);
},
onError (error) {
// handle errors
console.log(error);
},
onClose (){
console.log('widget is closing');
//Want to add some callback here to test()


const {test} = this.props //The issue is here
console.log(test) //getting Undefined
test(); //TypeError: Cannot read property 'test' of undefined


//OR

console.log(isPaid) //I get state as log
this.setState({isPaid: !isPaid}) //TypeError: Cannot read property 'setState' of undefined


}
}
};
let checkout = new paygateway(config);
return (




)


Answer



You're deconstructing test from this.props and the function doesn't exist in props. It's simply a function you've declared within the component. So, you should just assign test variable to the test function like so:



const test = this.test

Installing Wordpress on Windows 8 using XAMPP but PHP not running



I'm Windows 8 user who wants to install Wordpress.




I'm using XAMPP and have checked that my XAMPP is working. I also have created a database on MySql and set up the wp-config.php with the database details I have created before.
But every time I click the wp-admin/install.php, I get this error :




Error: PHP is not running
WordPress requires that your web server is running PHP. Your server does not have PHP installed, or PHP is turned off.




I'm using mySQL database, and database name is wordpress.
This is my config :





// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */ define('DB_NAME',
'wordpress');



/** MySQL database username */ define('DB_USER', 'root');



/** MySQL database password */ define('DB_PASSWORD', '');




/** MySQL hostname */ define('DB_HOST', 'localhost');



/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');



/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');




I still get the error, need some help.



Answer



Use XAMPP controle panel to start Apache (PHP) and MySQL. Every time when you shutdown windows Apache and MySQL will be shutdown as well. If you haven't setup Apache (PHP) and MySQL as a service you need to manually start apache(PHP) and MySQL via the controle panel. C:\xampp\xampp-control.exe if you use the default directory. Make sure to run the programm as admin.


python - How to run code when a class is subclassed?




Is there a way to trigger code when my class is subclassed?




class SuperClass:
def triggered_routine(subclass):
print("was subclassed by " + subclass.__name__)

magically_register_triggered_routine()

print("foo")

class SubClass0(SuperClass):
pass


print("bar")

class SubClass1(SuperClass):
print("test")


Should output



foo

was subclassed by SubClass0
bar
test
was subclassed by SubClass1

Answer



Classes (by default) are instances of type.
Just as an instance of a class Foo is created by foo = Foo(...),
an instance of type (i.e. a class) is created by myclass = type(name, bases, clsdict).




If you want something special to happen at the moment of class-creation, then you have to modify the thing creating the class -- i.e. type. The way to do that is to define a subclass of type -- i.e. a metaclass.



A metaclass is to its class as a class is to its instance.



In Python2 you would define the metaclass of a class with



class SuperClass:
__metaclass__ = Watcher



where Watcher is a subclass of type.



In Python3 the syntax has been changed to



class SuperClass(metaclass=Watcher)


Both are equivalent to



Superclass = Watcher(name, bases, clsdict)



where in this case, name equals the string 'Superclass', and bases is the tuple (object, ). The clsdict is a dictionary of the class attributes defined in the body of the class definition.



Note the similarity to myclass = type(name, bases, clsdict).



So, just as you would use a class's __init__ to control events at the moment of a instance's creation, you can control events at the moment of a class's creation with a metaclass's __init__:







class Watcher(type):
def __init__(cls, name, bases, clsdict):
if len(cls.mro()) > 2:
print("was subclassed by " + name)
super(Watcher, cls).__init__(name, bases, clsdict)

class SuperClass:
__metaclass__ = Watcher



print("foo")

class SubClass0(SuperClass):
pass

print("bar")

class SubClass1(SuperClass):
print("test")



prints



foo
was subclassed by SubClass0
bar
test
was subclassed by SubClass1

pointers - C: free memory allocated in c

suppose i have a struct:




typedef struct{
char *ID;
char *name;
float price;
int quantity;
} Generic_Properties;


now if i have used malloc to allocate space in the heap for it and saved the address in a pointer, lets call him p1. now i want to free that specific memory block, is it enough to just declare free(p1):




free(p1);


or do i need to separately free ID and name pointers, because I used malloc to allocated space for the string they're pointing to?

php - PDO Statements And XSS Attack

I've one POST parameter in one of the page hosted at localhost server.



$name = addslashes(trim($_POST['name']));


and using PDO prepared statements in one of the Update.php page and,




When i try to submit the field with the following data, it shows a ALERT Popup which leads to XSS attack, so how can i prevent this attack so that SQL Injection and XSS won't works.



abc">


Here's the SQL Query which i'm using -



$query = "UPDATE table set name =? where id=?";
$stmt = $conn->prepare($query);
$stmt->execute(array($name,$id));



Thank you

oop - Preserving a reference to "this" in JavaScript prototype functions




I'm just getting into using prototypal JavaScript and I'm having trouble figuring out how to preserve a this reference to the main object from inside a prototype function when the scope changes. Let me illustrate what I mean (I'm using jQuery here):




MyClass = function() {
this.element = $('#element');
this.myValue = 'something';

// some more code
}

MyClass.prototype.myfunc = function() {
// at this point, "this" refers to the instance of MyClass


this.element.click(function() {
// at this point, "this" refers to the DOM element
// but what if I want to access the original "this.myValue"?
});
}

new MyClass();



I know that I can preserve a reference to the main object by doing this at the beginning of myfunc:



var myThis = this;


and then using myThis.myValue to access the main object's property. But what happens when I have a whole bunch of prototype functions on MyClass? Do I have to save the reference to this at the beginning of each one? Seems like there should be a cleaner way. And what about a situation like this:



MyClass = function() {
this.elements $('.elements');
this.myValue = 'something';


this.elements.each(this.doSomething);
}

MyClass.prototype.doSomething = function() {
// operate on the element
}

new MyClass();



In that case, I can't create a reference to the main object with var myThis = this; because even the original value of this within the context of doSomething is a jQuery object and not a MyClass object.



It's been suggested to me to use a global variable to hold the reference to the original this, but that seems like a really bad idea to me. I don't want to pollute the global namespace and that seems like it would prevent me from instantiating two different MyClass objects without them interfering with each other.



Any suggestions? Is there a clean way to do what I'm after? Or is my entire design pattern flawed?


Answer



For preserving the context, the bind method is really useful, it's now part of the recently released ECMAScript 5th Edition Specification, the implementation of this function is simple (only 8 lines long):



// The .bind method from Prototype.js 

if (!Function.prototype.bind) { // check if native implementation available
Function.prototype.bind = function(){
var fn = this, args = Array.prototype.slice.call(arguments),
object = args.shift();
return function(){
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
};
};
}



And you could use it, in your example like this:



MyClass.prototype.myfunc = function() {

this.element.click((function() {
// ...
}).bind(this));
};



Another example:



var obj = {
test: 'obj test',
fx: function() {
alert(this.test + '\n' + Array.prototype.slice.call(arguments).join());
}
};


var test = "Global test";
var fx1 = obj.fx;
var fx2 = obj.fx.bind(obj, 1, 2, 3);

fx1(1,2);
fx2(4, 5);


In this second example we can observe more about the behavior of bind.




It basically generates a new function, that will be the responsible of calling our function, preserving the function context (this value), that is defined as the first argument of bind.



The rest of the arguments are simply passed to our function.



Note in this example that the function fx1, is invoked without any object context (obj.method() ), just as a simple function call, in this type of invokation, the this keyword inside will refer to the Global object, it will alert "global test".



Now, the fx2 is the new function that the bind method generated, it will call our function preserving the context and correctly passing the arguments, it will alert "obj test 1, 2, 3, 4, 5" because we invoked it adding the two additionally arguments, it already had binded the first three.


python - Using global variables in a function




How can I create or use a global variable in a function?



If I create a global variable in one function, how can I use that global variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?


Answer



You can use a global variable in other functions by declaring it as global in each function that assigns to it:



globvar = 0

def set_globvar_to_one():

global globvar # Needed to modify global copy of globvar
globvar = 1

def print_globvar():
print(globvar) # No need for global declaration to read value of globvar

set_globvar_to_one()
print_globvar() # Prints 1



I imagine the reason for it is that, since global variables are so dangerous, Python wants to make sure that you really know that's what you're playing with by explicitly requiring the global keyword.



See other answers if you want to share a global variable across modules.


What is the Python 3 equivalent of "python -m SimpleHTTPServer"



What is the Python 3 equivalent of python -m SimpleHTTPServer?


Answer



From the docs:




The SimpleHTTPServer module has been merged into http.server in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0.





So, your command is python -m http.server, or depending on your installation, it can be:



python3 -m http.server

c++ - Error using std::set to implement a sparse 3D grid



I'm trying to implement a sparse 3D grid with std::set container, but I can't understand the error returned from the compiler, this is the minimal example I'm trying to run:



#include 

#include
#include
#include

#include

using namespace std;

class Cell {
public:

EIGEN_MAKE_ALIGNED_OPERATOR_NEW
Cell(const Eigen::Vector3i idx=Eigen::Vector3i::Zero()):_idx(idx) {
_center = Eigen::Vector3f::Zero();
_parent = 0;
_distance = std::numeric_limits::max();
}

inline bool operator < (const Cell& c){
for (int i=0; i<3; i++){
if (_idx[i]
return true;
if (_idx[i]>c._idx[i])
return false;
}
return false;
}

inline bool operator == (const Cell& c) { return c._idx == _idx;}

private:

Eigen::Vector3i _idx;
Eigen::Vector3f _center;
vector _points;
Cell* _parent;
size_t _closest_point;
float _distance;
int _tag;
};



int main(int argc, char* argv[]) {

set grid;

float max = 1, min = -1;
int dim = 5;
float delta = (max-min)/(dim-1);

for(int k = 0; k < dim; k++)
for(int j = 0; j < dim; j++)

for(int i = 0; i < dim; i++)
grid.insert(Cell(Eigen::Vector3i(i,j,k)));

return 0;
}


and this is the compiler error:





In file included from /usr/include/c++/4.8/string:48:0,
from /usr/include/c++/4.8/bits/locale_classes.h:40,
from /usr/include/c++/4.8/bits/ios_base.h:41,
from /usr/include/c++/4.8/ios:42,
from /usr/include/c++/4.8/ostream:38,
from /usr/include/c++/4.8/iostream:39,
from /home/dede/build/sparse_grid/main.cpp:1: /usr/include/c++/4.8/bits/stl_function.h: In instantiation of 'bool
std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp =
Cell]': /usr/include/c++/4.8/bits/stl_tree.h:1324:11: required from
'std::pair

std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare,
_Alloc>::_M_get_insert_unique_pos(const key_type&) [with _Key = Cell; _Val = Cell; _KeyOfValue = std::_Identity; _Compare = std::less; _Alloc = std::allocator; std::_Rb_tree<_Key,
_Val, _KeyOfValue, _Compare, _Alloc>::key_type = Cell]' /usr/include/c++/4.8/bits/stl_tree.h:1377:47: required from
'std::pair, bool> std::_Rb_tree<_Key,
_Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_unique(_Arg&&) [with _Arg = Cell; _Key = Cell; _Val = Cell; _KeyOfValue = std::_Identity; _Compare = std::less; _Alloc =
std::allocator]' /usr/include/c++/4.8/bits/stl_set.h:472:40:
required from 'std::pair, _Compare, typename
_Alloc::rebind<_Key>::other>::const_iterator, bool> std::set<_Key, _Compare, _Alloc>::insert(std::set<_Key, _Compare, _Alloc>::value_type&&) [with _Key = Cell; _Compare = std::less; _Alloc = std::allocator; typename std::_Rb_tree<_Key, _Key, std::_Identity<_Key>, _Compare, typename
_Alloc::rebind<_Key>::other>::const_iterator = std::_Rb_tree_const_iterator; std::set<_Key, _Compare,
_Alloc>::value_type = Cell]' /home/dede/build/sparse_grid/main.cpp:53:57: required from here
/usr/include/c++/4.8/bits/stl_function.h:235:20: error: passing 'const

Cell' as 'this' argument of 'bool Cell::operator<(const Cell&)'
discards qualifiers [-fpermissive]
{ return __x < __y; }
^ make[2]: * [CMakeFiles/sparse_grid.dir/main.cpp.o] Error 1 make[1]: *
[CMakeFiles/sparse_grid.dir/all] Error 2 make: *** [all] Error 2




I would really appreciate if someone could tell me what I'm doing wrong.



Thanks,

Federico


Answer



You should declare your boolean operator functions as const members:



inline bool operator < (const Cell& c) const {
// ^^^^^
for (int i=0; i<3; i++){
if (_idx[i] return true;
if (_idx[i]>c._idx[i])

return false;
}
return false;
}

inline bool operator == (const Cell& c) const { return c._idx == _idx;}
// ^^^^^


Otherwise these cannot be used with rvalue objects of Cell.



php - How can I show only tags in The Loop?



Is there a way to force The Loop to show only

tags from the content of a post, while ignoring all other tags (h2, p, hr... )?



  

$hm_intro = new WP_query(array(
'p' => 375,
'post_type' => 'any',
'posts_per_page' => 1
));
if($hm_intro->have_posts()) : while($hm_intro->have_posts()) : $hm_intro->the_post();

//Here I want display only the

from the_content().

endwhile;
wp_reset_postdata();
endif;
?>


Answer



You can parse all the H1s out of the post content with domDocument:



if($hm_intro->have_posts()) : while($hm_intro->have_posts()) : $hm_intro->the_post();

$dom = new domDocument;
$dom->loadHTML(get_the_content());

$headings = $dom->getElementsByTagName('h1');

foreach ($heading as $h){
echo '

' . $h->textContent . '

';
}

endwhile;

analysis - Were parts of The Dark Knight Rises a commentary on the Occupy movement? - Movies & TV



A fair amount of the second act of The Dark Knight Rises has a class warfare plotline. This is foreshadowed in the trailers with Selina Kyle's "there's a storm coming" monologue. Some of the verbiage and themes of this portion of the film seem to mirror the Occupy Movement, and I wanted to know if this was on purpose.




Did the writers of The Dark Knight Rises purposefully model this plotline on the Occupy Movement, or were they pulling from some other source?


Answer



In an interview with Rolling Stone, director Christopher Nolan insists his film is apolitical:




In the new movie, you have Bane more or less trick Gotham's 99 percent
into rising up against the rich – is that intended as an anti-Occupy
Wall Street statement?




I've had as many conversations with people who
have seen the film the other way round. We throw a lot of things
against the wall to see if it sticks. We put a lot of interesting
questions in the air, but that's simply a backdrop for the story. What
we're really trying to do is show the cracks of society, show the
conflicts that somebody would try to wedge open. We're going to get
wildly different interpretations of what the film is supporting and
not supporting, but it's not doing any of those things. It's just
telling a story. If you're saying, “Have you made a film that's
supposed to be criticizing the Occupy Wall Street movement?” – well,

obviously, that's not true.



But the movie certainly suggests that there's a great danger of
populist movements being pushed too far.



If the populist movement is
manipulated by somebody who is evil, that surely is a criticism of the
evil person. You could also say the conditions the evil person is
exploiting are problematic and should be addressed.




Node.js vs .Net performance

I've read a lot about Node.js being fast and able to accommodate large amounts of load. Does anyone have any real world evidence of this vs other frameworks, particularly .Net? Most of the articles i've read are anecdotal or don't have comparisons to .Net.




Thanks

php - Option Value when selected

I'm trying to get my dropdown box to set the selected option as the option value.




$category = $pdo->query('SELECT jobCategory FROM Category');

foreach ($category as $row) {
echo "";
}


Currently, it sets the jobCate to "owner1".

unsupported class version - java.lang.UnsupportedClassVersionError

When I ran a java program I received this error.. Could you please suggest why do we get this error:



Exception in thread "main" java.lang.UnsupportedClassVersionError: 
GenerateInvoice (Unsupported major.minor version 49.0)
at java.lang.ClassLoader.defineClass0(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:539)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:251)
at java.net.URLClassLoader.access$100(URLClassLoader.java:55)
at java.net.URLClassLoader$1.run(URLClassLoader.java:194)

at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:187)
at java.lang.ClassLoader.loadClass(ClassLoader.java:289)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:274)
at java.lang.ClassLoader.loadClass(ClassLoader.java:235)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:302)

object - Build a Basic Python Iterator

There are four ways to build an iterative function:


Examples:


# generator
def uc_gen(text):
for char in text:
yield char.upper()
# generator expression
def uc_genexp(text):
return (char.upper() for char in text)
# iterator protocol
class uc_iter():
def __init__(self, text):
self.text = text
self.index = 0
def __iter__(self):
return self
def __next__(self):
try:
result = self.text[self.index].upper()
except IndexError:
raise StopIteration
self.index += 1
return result
# getitem method
class uc_getitem():
def __init__(self, text):
self.text = text
def __getitem__(self, index):
result = self.text[index].upper()
return result

To see all four methods in action:


for iterator in uc_gen, uc_genexp, uc_iter, uc_getitem:
for ch in iterator('abcde'):
print ch,
print

Which results in:


A B C D E
A B C D E
A B C D E
A B C D E

Note:


The two generator types (uc_gen and uc_genexp) cannot be reversed(); the plain iterator (uc_iter) would need the __reversed__ magic method (which must return a new iterator that goes backwards); and the getitem iteratable (uc_getitem) must have the __len__ magic method:


    # for uc_iter
def __reversed__(self):
return reversed(self.text)
# for uc_getitem
def __len__(self)
return len(self.text)



To answer Colonel Panic's secondary question about an infinite lazily evaluated iterator, here are those examples, using each of the four methods above:


# generator
def even_gen():
result = 0
while True:
yield result
result += 2
# generator expression
def even_genexp():
return (num for num in even_gen()) # or even_iter or even_getitem
# not much value under these circumstances
# iterator protocol
class even_iter():
def __init__(self):
self.value = 0
def __iter__(self):
return self
def __next__(self):
next_value = self.value
self.value += 2
return next_value
# getitem method
class even_getitem():
def __getitem__(self, index):
return index * 2
import random
for iterator in even_gen, even_genexp, even_iter, even_getitem:
limit = random.randint(15, 30)
count = 0
for even in iterator():
print even,
count += 1
if count >= limit:
break
print

Which results in (at least for my sample run):


0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32



How to choose which one to use? This is mostly a matter of taste. The two methods I see most often are generators and the iterator protocol, as well as a hybrid (__iter__ returning a generator).


Generator expressions are useful for replacing list comprehensions (they are lazy and so can save on resources).


If one needs compatibility with earlier Python 2.x versions use __getitem__.

Tuesday, 29 November 2016

parsing - PHP parse/syntax errors; and how to solve them



Everyone runs into syntax errors. Even experienced programmers make typos. For newcomers, it's just part of the learning process. However, it's often easy to interpret error messages such as:





PHP Parse error: syntax error, unexpected '{' in index.php on line 20




The unexpected symbol isn't always the real culprit. But the line number gives a rough idea of where to start looking.




Always look at the code context. The syntax mistake often hides in the mentioned or in previous code lines. Compare your code against syntax examples from the manual.





While not every case matches the other. Yet there are some general steps to solve syntax mistakes.
This references summarized the common pitfalls:





Closely related references:





And:






While is also welcoming rookie coders, it's mostly targetted at professional programming questions.




  • Answering everyone's coding mistakes and narrow typos is considered mostly off-topic.

  • So please take the time to follow the basic steps, before posting syntax fixing requests.

  • If you still have to, please show your own solving initiative, attempted fixes, and your thought process on what looks or might be wrong.




If your browser displays error messages such as "SyntaxError: illegal character", then it's not actually -related, but a -syntax error.






Syntax errors raised on vendor code: Finally, consider that if the syntax error was not raised by editing your codebase, but after an external vendor package install or upgrade, it could be due to PHP version incompatibility, so check the vendor's requirements against your platform setup.


Answer



What are the syntax errors?



PHP belongs to the C-style and imperative programming languages. It has rigid grammar rules, which it cannot recover from when encountering misplaced symbols or identifiers. It can't guess your coding intentions.




Function definition syntax abstract



Most important tips



There are a few basic precautions you can always take:




  • Use proper code indentation, or adopt any lofty coding style.
    Readability prevents irregularities.



  • Use an IDE or editor for PHP with syntax highlighting.
    Which also help with parentheses/bracket balancing.



    Expected: semicolon


  • Read the language reference and examples in the manual.
    Twice, to become somewhat proficient.




How to interpret parser errors




A typical syntax error message reads:




Parse error: syntax error, unexpected T_STRING, expecting ';' in file.php on line 217




Which lists the possible location of a syntax mistake. See the mentioned file name and line number.



A moniker such as T_STRING explains which symbol the parser/tokenizer couldn't process finally. This isn't necessarily the cause of the syntax mistake, however.




It's important to look into previous code lines as well. Often syntax errors are just mishaps that happened earlier. The error line number is just where the parser conclusively gave up to process it all.



Solving syntax errors



There are many approaches to narrow down and fix syntax hiccups.




  • Open the mentioned source file. Look at the mentioned code line.





    • For runaway strings and misplaced operators, this is usually where you find the culprit.


    • Read the line left to right and imagine what each symbol does.



  • More regularly you need to look at preceding lines as well.




    • In particular, missing ; semicolons are missing at the previous line ends/statement. (At least from the stylistic viewpoint. )


    • If { code blocks } are incorrectly closed or nested, you may need to investigate even further up the source code. Use proper code indentation to simplify that.



  • Look at the syntax colorization!





    • Strings and variables and constants should all have different colors.


    • Operators +-*/. should be tinted distinct as well. Else they might be in the wrong context.


    • If you see string colorization extend too far or too short, then you have found an unescaped or missing closing " or ' string marker.


    • Having two same-colored punctuation characters next to each other can also mean trouble. Usually, operators are lone if it's not ++, --, or parentheses following an operator. Two strings/identifiers directly following each other are incorrect in most contexts.



  • Whitespace is your friend.
    Follow any coding style.



  • Break up long lines temporarily.




    • You can freely add newlines between operators or constants and strings. The parser will then concretize the line number for parsing errors. Instead of looking at the very lengthy code, you can isolate the missing or misplaced syntax symbol.


    • Split up complex if statements into distinct or nested if conditions.


    • Instead of lengthy math formulas or logic chains, use temporary variables to simplify the code. (More readable = fewer errors.)


    • Add newlines between:




      1. The code you can easily identify as correct,


      2. The parts you're unsure about,

      3. And the lines which the parser complains about.



      Partitioning up long code blocks really helps to locate the origin of syntax errors.



  • Comment out offending code.




    • If you can't isolate the problem source, start to comment out (and thus temporarily remove) blocks of code.



    • As soon as you got rid of the parsing error, you have found the problem source. Look more closely there.


    • Sometimes you want to temporarily remove complete function/method blocks. (In case of unmatched curly braces and wrongly indented code.)


    • When you can't resolve the syntax issue, try to rewrite the commented out sections from scratch.



  • As a newcomer, avoid some of the confusing syntax constructs.




    • The ternary ? : condition operator can compact code and is useful indeed. But it doesn't aid readability in all cases. Prefer plain if statements while unversed.


    • PHP's alternative syntax (if:/elseif:/endif;) is common for templates, but arguably less easy to follow than normal { code } blocks.




  • The most prevalent newcomer mistakes are:




    • Missing semicolons ; for terminating statements/lines.


    • Mismatched string quotes for " or ' and unescaped quotes within.


    • Forgotten operators, in particular for the string . concatenation.


    • Unbalanced ( parentheses ). Count them in the reported line. Are there an equal number of them?



  • Don't forget that solving one syntax problem can uncover the next.





    • If you make one issue go away, but other crops up in some code below, you're mostly on the right path.


    • If after editing a new syntax error crops up in the same line, then your attempted change was possibly a failure. (Not always though.)



  • Restore a backup of previously working code, if you can't fix it.




    • Adopt a source code versioning system. You can always view a diff of the broken and last working version. Which might be enlightening as to what the syntax problem is.




  • Invisible stray Unicode characters: In some cases, you need to use a hexeditor or different editor/viewer on your source. Some problems cannot be found just from looking at your code.




    • Try grep --color -P -n "\[\x80-\xFF\]" file.php as the first measure to find non-ASCII symbols.


    • In particular BOMs, zero-width spaces, or non-breaking spaces, and smart quotes regularly can find their way into the source code.



  • Take care of which type of linebreaks are saved in files.




    • PHP just honors \n newlines, not \r carriage returns.



    • Which is occasionally an issue for MacOS users (even on OS  X for misconfigured editors).


    • It often only surfaces as an issue when single-line // or # comments are used. Multiline /*...*/ comments do seldom disturb the parser when linebreaks get ignored.



  • If your syntax error does not transmit over the web:
    It happens that you have a syntax error on your machine. But posting the very same file online does not exhibit it anymore. Which can only mean one of two things:




    • You are looking at the wrong file!


    • Or your code contained invisible stray Unicode (see above).
      You can easily find out: Just copy your code back from the web form into your text editor.




  • Check your PHP version. Not all syntax constructs are available on every server.




    • php -v for the command line interpreter


    • for the one invoked through the webserver.





    Those aren't necessarily the same. In particular when working with frameworks, you will them to match up.


  • Don't use PHP's reserved keywords as identifiers for functions/methods, classes or constants.



  • Trial-and-error is your last resort.




If all else fails, you can always google your error message. Syntax symbols aren't as easy to search for ( itself is indexed by SymbolHound though). Therefore it may take looking through a few more pages before you find something relevant.



Further guides:





White screen of death




If your website is just blank, then typically a syntax error is the cause.
Enable their display with:




  • error_reporting = E_ALL

  • display_errors = 1



In your php.ini generally, or via .htaccess for mod_php,

or even .user.ini with FastCGI setups.



Enabling it within the broken script is too late because PHP can't even interpret/run the first line. A quick workaround is crafting a wrapper script, say test.php:



   error_reporting(E_ALL);
ini_set("display_errors", 1);
include("./broken-script.php");



Then invoke the failing code by accessing this wrapper script.



It also helps to enable PHP's error_log and look into your webserver's error.log when a script crashes with HTTP 500 responses.


What does the asterisk in C do?




What does the * mean in C? I see it used when declaring a char or FILE variable (char = *test) How does that change how a variable behaves?


Answer



This type of * is called "indirection operator", and *test means "get the data from where the pointer test points".




char is reserved for use as a keyword, so char = *test won't compile unless char is defined as a macro.


php - Why does empty() not accept function return value when it accepts getter output?




I'm having a class that implements the ArrayAccess interface. I noticed that I can use empty function on the offset values with no errors:



$class = new MyArrayClass();
if(!empty($class["offset"]))
...
else
die("Empty!!!");



However calling even the offsetGet interface method will not work:



if(!empty($class->offsetGet("offset"))) 


It throws standard error:




Can't use function return value in write context.





My question is: Why does empty work on getters and virtual array offsets? As far as I know, they are actually function return values, not variables...



This question is rather educational then practical. I'm just curious. Please try to explain as much as possible.


Answer



empty in php version less than 5.5 accepts only variables.



from changelog:





5.5.0 empty() now supports expressions, rather than only variables.



Retrieving Value from Config file in C# Application Doesn't Work




I'm having an issue trying to work with a config file,
I've read a few posts here and elsewhere
but I can't solve problem in work,



In my question here, I have added the Configuration.



























Declared in the document




string ab123 = ConfigurationManager.AppSettings["ab123"];


But in the side , I show error is
" win32 Exception was unhandled - System can not find the file specified"



System.Diagnostics.Process.Start(ConfigurationManager.AppSettings["ab123"]);



When I run this code, ab123 value always null !!!!!
I sure path is normal



How can I fix it?


Answer



It appears from your xml config files that you are really trying to use User Settings rather than Application setting and that you have mixed some of the ideas up. I think a more correct version of a config might be:


















D:\ab123\Source\ab123.c






The only significant difference is the way you define settings. For example I changed it to:





D:\ab123\Source\ab123.c



You can create more settings just like this using a different name



The client code is a bit different as it has to find the userSettings, find the program property settings and then query for the key (like ab123). I have added some trivial error handling but you need to deal with the errors yourself. I simply return on error for code simplification. The code has inline comments to help figure out what is going on.



using System;
using System.Collections.Generic;

using System.Text;
using System.Configuration;
using System.Diagnostics;
using System.IO;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)

{
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Retrieve the userSettings gorup
ConfigurationSectionGroup group = config.SectionGroups[@"userSettings"];
if (group == null) return;

// Get the program settings
ClientSettingsSection clientSection = group.Sections["CA.Properties.Settings"] as ClientSettingsSection;
if (clientSection == null) return;


// This retrieves the value associated with the key
string sFileName = clientSection.Settings.Get("ab123").Value.ValueXml.InnerText;

// Check if ab123 has a value and the file exists
if (!string.IsNullOrEmpty(sFileName) && System.IO.File.Exists(sFileName))
{
using (StreamReader sr = new StreamReader(sFileName))
{
string line;
// Read and display lines from the file until the end of

// the file is reached.
while ((line = sr.ReadLine()) != null)
{
System.Diagnostics.Debug.WriteLine(line);
}
}
}
}
}
}



If you are using Settings.settings to create and delete settings then the code can be simplified to this since Visual Studio will create bindings for your settings object that be accessed at design time and runtime. For information on using Settings.settings through the Visual Studio IDE please see this article. If for some reason the code below doesn't work you can use the code above:



using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Diagnostics;
using System.IO;


namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string sFileName = Properties.Settings.Default.ab123;

// Check if ab123 has a value and the file exists

if (!string.IsNullOrEmpty(sFileName) && System.IO.File.Exists(sFileName))
{
using (StreamReader sr = new StreamReader(sFileName))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
System.Diagnostics.Debug.WriteLine(line);

}
}
}
}
}
}

r - Adding hover tooltips to shinyapps.io



I would like to add hover tooltips to my input and output boxes on a shiny app that is deployed in shinyapps.io.



I found the RLumShiny package which can add tooltips and I have modified my app to accommodate this. The app works locally but when I try to deploy it to shinyapps.io I end up with the error seen below. There are no companion files to the app - just the ui.R and server.R files.



To deploy I run




library(rsconnect)
deployApp('~/sandbox/overdiag/', logLevel="verbose")


I get an error message




----- Deployment error -----




Error: C stack usage 7969336 is too close to the limit




(and a bunch of other information from the track). I've made a minimal example that produces the same error where the ui.R is



## ui.R ##                                                                                                                                                
library("shiny")
library("RLumShiny") ## This package is problematic
library("shinydashboard")
library("shinyWidgets")


dashboardPage(
dashboardHeader(),
dashboardSidebar(),
dashboardBody()
)


and server.R




library("shiny")
library("RLumShiny") ## Again this package
library("shinydashboard")

function(input, output, session) {

}


Now if I remove the library("RLumShiny") line then everything works fine and I can deploy it right away. I don't get information that the package is not available but maybe there is something else wrong (I have a nagging feeling that the javascript in the package might do some things that the shinyapps.io service does not like).




Now: is there an alternative approach (ie., some other package) to get hover tooltips on the shinyapps.io or can I do something else to get RLumShiny to work?


Answer



In general in shiny you can get tooltips by using tags$div in your ui.r to wrap your controls / outputs and giving it a title. So for example you could do:



tags$div(title="My tooltip", plotOutput(outputId="MyPlot"))


and you will get a tool tip. The same pattern works for controls.


go - Is there a way to do repetitive tasks at intervals?



Is there a way to do repetitive background tasks in Go? I'm thinking of something like Timer.schedule(task, delay, period) in Java. I know I can do this with a goroutine and Time.sleep(), but I'd like something that easily stopped.



Here's what I got, but looks ugly to me. Is there a cleaner/better way?




func oneWay() {
var f func()
var t *time.Timer

f = func () {
fmt.Println("doing stuff")
t = time.AfterFunc(time.Duration(5) * time.Second, f)
}


t = time.AfterFunc(time.Duration(5) * time.Second, f)

defer t.Stop()

//simulate doing stuff
time.Sleep(time.Minute)
}

Answer



The function time.NewTicker makes a channel that sends a periodic message, and provides a way to stop it. Use it something like this (untested):




ticker := time.NewTicker(5 * time.Second)
quit := make(chan struct{})
go func() {
for {
select {
case <- ticker.C:
// do stuff
case <- quit:
ticker.Stop()

return
}
}
}()


You can stop the worker by closing the quit channel: close(quit).


c++ - What does "dereferencing" a pointer mean?



Please include an example with the explanation.


Answer



Reviewing the basic terminology



It's usually good enough - unless you're programming assembly - to envisage a pointer containing a numeric memory address, with 1 referring to the second byte in the process's memory, 2 the third, 3 the fourth and so on....





  • What happened to 0 and the first byte? Well, we'll get to that later - see null pointers below.

  • For a more accurate definition of what pointers store, and how memory and addresses relate, see "More about memory addresses, and why you probably don't need to know".



When you want to access the data/value in the memory that the pointer points to - the contents of the address with that numerical index - then you dereference the pointer.



Different computer languages have different notations to tell the compiler or interpreter that you're now interested in the pointed-to value - I focus below on C and C++.




A pointer scenario



Consider in C, given a pointer such as p below...



const char* p = "abc";


...four bytes with the numerical values used to encode the letters 'a', 'b', 'c', and a 0 byte to denote the end of the textual data, are stored somewhere in memory and the numerical address of that data is stored in p.



For example, if the string literal happened to be at address 0x1000 and p a 32-bit pointer at 0x2000, the memory content would be:




Memory Address (hex)    Variable name    Contents
1000 'a' == 97 (ASCII)
1001 'b' == 98
1002 'c' == 99
1003 0
...
2000-2003 p 1000 hex



Note that there is no variable name/identifier for address 0x1000, but we can indirectly refer to the string literal using a pointer storing its address: p.



Dereferencing the pointer



To refer to the characters p points to, we dereference p using one of these notations (again, for C):



assert(*p == 'a');  // The first character at address p will be 'a'
assert(p[1] == 'b'); // p[1] actually dereferences a pointer created by adding
// p and 1 times the size of the things to which p points:
// In this case they're char which are 1 byte in C...

assert(*(p + 1) == 'b'); // Another notation for p[1]


You can also move pointers through the pointed-to data, dereferencing them as you go:



++p;  // Increment p so it's now 0x1001
assert(*p == 'b'); // p == 0x1001 which is where the 'b' is...


If you have some data that can be written to, then you can do things like this:




int x = 2;
int* p_x = &x; // Put the address of the x variable into the pointer p_x
*p_x = 4; // Change the memory at the address in p_x to be 4
assert(x == 4); // Check x is now 4


Above, you must have known at compile time that you would need a variable called x, and the code asks the compiler to arrange where it should be stored, ensuring the address will be available via &x.



Dereferencing and accessing a structure data member




In C, if you have a variable that is a pointer to a structure with data members, you can access those members using the -> dereferencing operator:



typedef struct X { int i_; double d_; } X;
X x;
X* p = &x;
p->d_ = 3.14159; // Dereference and access data member x.d_
(*p).d_ *= -1; // Another equivalent notation for accessing x.d_



Multi-byte data types



To use a pointer, a computer program also needs some insight into the type of data that is being pointed at - if that data type needs more than one byte to represent, then the pointer normally points to the lowest-numbered byte in the data.



So, looking at a slightly more complex example:



double sizes[] = { 10.3, 13.4, 11.2, 19.4 };
double* p = sizes;
assert(p[0] == 10.3); // Knows to look at all the bytes in the first double value
assert(p[1] == 13.4); // Actually looks at bytes from address p + 1 * sizeof(double)

// (sizeof(double) is almost always eight bytes)
assert(++p); // Advance p by sizeof(double)
assert(*p == 13.4); // The double at memory beginning at address p has value 13.4
*(p + 2) = 29.8; // Change sizes[3] from 19.4 to 29.8
// Note: earlier ++p and + 2 here => sizes[3]


Pointers to dynamically allocated memory



Sometimes you don't know how much memory you'll need until your program is running and sees what data is thrown at it... then you can dynamically allocate memory using malloc. It is common practice to store the address in a pointer...




int* p = malloc(sizeof(int)); // Get some memory somewhere...
*p = 10; // Dereference the pointer to the memory, then write a value in
fn(*p); // Call a function, passing it the value at address p
(*p) += 3; // Change the value, adding 3 to it
free(p); // Release the memory back to the heap allocation library


In C++, memory allocation is normally done with the new operator, and deallocation with delete:




int* p = new int(10); // Memory for one int with initial value 10
delete p;

p = new int[10]; // Memory for ten ints with unspecified initial value
delete[] p;

p = new int[10](); // Memory for ten ints that are value initialised (to 0)
delete[] p;



See also C++ smart pointers below.



Losing and leaking addresses



Often a pointer may be the only indication of where some data or buffer exists in memory. If ongoing use of that data/buffer is needed, or the ability to call free() or delete to avoid leaking the memory, then the programmer must operate on a copy of the pointer...



const char* p = asprintf("name: %s", name);  // Common but non-Standard printf-on-heap

// Replace non-printable characters with underscores....
for (const char* q = p; *q; ++q)

if (!isprint(*q))
*q = '_';

printf("%s\n", p); // Only q was modified
free(p);


...or carefully orchestrate reversal of any changes...



const size_t n = ...;

p += n;
...
p -= n; // Restore earlier value...


C++ smart pointers



In C++, it's best practice to use smart pointer objects to store and manage the pointers, automatically deallocating them when the smart pointers' destructors run. Since C++11 the Standard Library provides two, unique_ptr for when there's a single owner for an allocated object...



{

std::unique_ptr p{new T(42, "meaning")};
call_a_function(p);
// The function above might throw, so delete here is unreliable, but...
} // p's destructor's guaranteed to run "here", calling delete


...and shared_ptr for share ownership (using reference counting)...



{
std::shared_ptr p(new T(3.14, "pi"));

number_storage.may_add(p); // Might copy p into its container
} // p's destructor will only delete the T if number_storage didn't copy


Null pointers



In C, NULL and 0 - and additionally in C++ nullptr - can be used to indicate that a pointer doesn't currently hold the memory address of a variable, and shouldn't be dereferenced or used in pointer arithmetic. For example:



const char* p_filename = NULL; // Or "= 0", or "= nullptr" in C++
char c;

while ((c = getopt(argc, argv, "f:")) != EOF)
switch (c) {
case f: p_filename = optarg; break;
}
if (p_filename) // Only NULL converts to false
... // Only get here if -f flag specified


In C and C++, just as inbuilt numeric types don't necessarily default to 0, nor bools to false, pointers are not always set to NULL. All these are set to 0/false/NULL when they're static variables or (C++ only) direct or indirect member variables of static objects or their bases, or undergo zero initialisation (e.g. new T(); and new T(x, y, z); perform zero-initialisation on T's members including pointers, whereas new T; does not).




Further, when you assign 0, NULL and nullptr to a pointer the bits in the pointer are not necessarily all reset: the pointer may not contain "0" at the hardware level, or refer to address 0 in your virtual address space. The compiler is allowed to store something else there if it has reason to, but whatever it does - if you come along and compare the pointer to 0, NULL, nullptr or another pointer that was assigned any of those, the comparison must work as expected. So, below the source code at the compiler level, "NULL" is potentially a bit "magical" in the C and C++ languages...



More about memory addresses, and why you probably don't need to know



More strictly, initialised pointers store a bit-pattern identifying either NULL or a (often virtual) memory address.



The simple case is where this is a numeric offset into the process's entire virtual address space; in more complex cases the pointer may be relative to some specific memory area, which the CPU may select based on CPU "segment" registers or some manner of segment id encoded in the bit-pattern, and/or looking in different places depending on the machine code instructions using the address.



For example, an int* properly initialised to point to an int variable might - after casting to a float* - access a value in "GPU" memory quite distinct from the int variable, then once cast to a function pointer might refer to distinct memory holding the machine opcodes for the function.




3GL programming languages like C and C++ tend to hide this complexity, such that:




  • If the compiler gives you a pointer to a variable or function, you can dereference it freely (as long as the variable's not destructed/deallocated meanwhile) and it's the compiler's problem whether e.g. a particular CPU register needs to be restored beforehand, or a distinct machine code instruction used


  • If you get a pointer to an element in an array, you can use pointer arithmetic to move anywhere else in the array, or even to form an address one-past-the-end of the array that's legal to compare with other pointers to elements in the array (or that have similarly been moved by pointer arithmetic to the same one-past-the-end value); again in C and C++, it's up to the compiler to ensure this "just works"


  • Specific OS functions, e.g. shared memory mapping, may give you pointers, and they'll "just work" within the range of addresses that makes sense for them


  • Attempts to move legal pointers beyond these boundaries, or to cast arbitrary numbers to pointers, or use pointers cast to unrelated types, typically have undefined behaviour, so should be avoided in higher level libraries and applications, but code for OSes, device drivers, etc. may need to rely on behaviour left undefined by C or C++, that is nevertheless well defined by their specific hardware.



c - Conditional jump or move depends on uninitialised value(s)



I've been struggling with this problem for a while now, searching every possible solution. I'm new to C so I'ts hard. I know I have some variable uninitialized, but I can't find them. I am trying to print a matrix. Here's the constructor:



BoardP createNewBoard(int width, int high)

{

BoardP board = (BoardP) malloc(sizeof(Board));

if (board == NULL)
{
reportError(MEM_OUT);
return NULL;
}
board->height = high;

board->width = width;
board->board = (char**) malloc(high * sizeof(char*));
int i;
for (i=0; i {
board->board[i] = (char*) malloc(width * sizeof(char));
if (board->board[i] == NULL)
{
freeTempBoard(board,i);
return NULL;

}
}

return board;
}


The constructor returns BoardP, a pinter to Board, which is:



typedef struct Board

{
int width;
int height;
char **board;
} Board;


Now I fail trying to print the board->board. I loop over the matrix and for each cell I call this function:



static void printChar(ConstBoardP board, int X, int Y)

{
if (X>=board->height || Y>=board->width)
{
printf(" ");
}
else
{
printf("%c ",board->board[X][Y]); //!!THIS IS LINE 299 IN Board.c!!
}
}



And fianlly here's the error I get:



==4931== Conditional jump or move depends on uninitialised value(s)
==4931== at 0x4E973D9: _IO_file_overflow@@GLIBC_2.2.5 (fileops.c:880)
==4931== by 0x4E6F01B: vfprintf (vfprintf.c:1614)
==4931== by 0x4E75879: printf (printf.c:35)
==4931== by 0x400D91: printChar (Board.c:299)
==4931== by 0x400CED: printBoard (Board.c:284)

==4931== by 0x400F1A: main (PlayBoard.c:19)
==4931==
==4931== Conditional jump or move depends on uninitialised value(s)
==4931== at 0x4E97401: _IO_file_overflow@@GLIBC_2.2.5 (fileops.c:887)
==4931== by 0x4E6F01B: vfprintf (vfprintf.c:1614)
==4931== by 0x4E75879: printf (printf.c:35)
==4931== by 0x400D91: printChar (Board.c:299)
==4931== by 0x400CED: printBoard (Board.c:284)
==4931== by 0x400F1A: main (PlayBoard.c:19)
==4931==

==4931== Conditional jump or move depends on uninitialised value(s)
==4931== at 0x4E6F025: vfprintf (vfprintf.c:1614)
==4931== by 0x4E75879: printf (printf.c:35)
==4931== by 0x400D91: printChar (Board.c:299)
==4931== by 0x400CED: printBoard (Board.c:284)
==4931== by 0x400F1A: main (PlayBoard.c:19)


Now there's another file that calls createNewBoard, and then create printBoard(newBoard,0,0). The only thing that could possibly be uninitialized is board->board, other then that I have no ideas. I don't know how to debug it.
I know its a lot of text, but I can't find the problem. Any idea would be much appreciated



Answer



Try:



for (i=0; i{
board->board[i] = (char*) malloc(width * sizeof(char));
/* ... */
memset(board[i], 0, width);
}


java - NullPointerException when Creating an Array of objects





I have been trying to create an array of a class containing two values, but when I try to apply a value to the array I get a NullPointerException.



public class ResultList {
public String name;
public Object value;
}





public class Test {
public static void main(String[] args){
ResultList[] boll = new ResultList[5];
boll[0].name = "iiii";
}
}



Why am I getting this exception and how can I fix it?


Answer



You created the array but didn't put anything in it, so you have an array that contains 5 elements, all of which are null. You could add



boll[0] = new ResultList();


before the line where you set boll[0].name.



SQL Server: assigning string literals to a parameter



I need to do something like:



EXEC sp_ExecuteSQL N'select * from Members where Name like @pat',
N'@pat nvarchar(max)', @pat=Tom


My question is about the last parameter.




When the value to assign is a "simple" string, i.e. no spaces etc, I could use something like @pat=Tom, no quotes needed.



However, when the value to assign ends with the % character for example, it won't work, and I have to do something like @pat=N'Tom%'.



Is this how the syntax of assigning a string literal is defined?



Does it also mean that if my value contains the single quotation mark, I would have to escape it manually?


Answer



I am surprised that it works with no quotes. This must be a peculiarity of exec.




Always include the single quotes:



EXEC sp_ExecuteSQL N'select * from Members where Name like @pat',
N'@pat nvarchar(max)', @pat='Tom';


According to the documentation:





If the value of a parameter is an object name, character string, or
qualified by a database name or schema name, the whole name must be
enclosed in single quotation marks
. If the value of a parameter is a
keyword, the keyword must be enclosed in double quotation marks.




I don't know why it would work without the single quotes.


realism - Could a fire hose really support the weight of a falling man? - Movies & TV



In the movie Die Hard, near the end, John McClane ties a fire hose around his waist and jumps off the roof of the Nakotomi plaza building.



Would a fire hose really be able to support the weight of a man of that build at falling speeds?


Answer




I suspect the fire hose would survive, but our poor action hero would not.



From this article:




So in the Die Hard fall its unlikely to stretch very much. Lets say in
Bruce's jump a 10m fire hose stretches 1% i.e. 0.1m. Our force formula
now becomes F = 7900 / 0.1 = 79000 N ... equivalent to the weight of
about 100 Bruce Willis!




So what would happen to our action hero? Talking through all this one
day with the actor and presenter Robert Llewellyn he quite rightly
reflected "I think there would be a Bruce and somewhere else a
Willis!"



Calculating the difference between two Java date instances



I'm using Java's java.util.Date class in Scala and want to compare a Date object and the current time. I know I can calculate the delta by using getTime():



(new java.util.Date()).getTime() - oldDate.getTime()


However, this just leaves me with a long representing milliseconds. Is there any simpler, nicer way to get a time delta?


Answer




The JDK Date API is horribly broken unfortunately. I recommend using Joda Time library.



Joda Time has a concept of time Interval:



Interval interval = new Interval(oldTime, new Instant());


EDIT: By the way, Joda has two concepts: Interval for representing an interval of time between two time instants (represent time between 8am and 10am), and a Duration that represents a length of time without the actual time boundaries (e.g. represent two hours!)



If you only care about time comparisions, most Date implementations (including the JDK one) implements Comparable interface which allows you to use the Comparable.compareTo()



c++ - What is wrong with my binary search tree insertion logic?



binarysearch.h :






#ifndef BST_BINARYSEARCH_H
#define BST_BINARYSEARCH_H

struct Node{
int value;
Node* left;
Node* right;
};


class BST{
public:
Node* root;
BST(){
root = nullptr;
}
Node* insertNode(Node* root, Node toInsert);
void inOrder(Node* root);
};


#endif //BST_BINARYSEARCH_H



binarysearch.cpp :





#include
#include

#include "binarysearch.h"

Node* BST::insertNode(Node* root, Node toInsert) {
if(root == nullptr){
root = &toInsert;
}
else {
if (toInsert.value value)
root->left = insertNode(root->left, toInsert);
else

root->right = insertNode(root->right, toInsert);
}
return root;
}

void BST::inOrder(Node *root) {
if(root!= NULL){
inOrder(root->left);
std::coutvalue;
inOrder(root->right);

}
}



main.cpp:





#include

#include "binarysearch.h"

int main() {

BST bst;
Node* root = nullptr;

Node a;
a.value = 4;
a.left = NULL;

a.right = NULL;

root = bst.insertNode(root, a);
bst.insertNode(root, a);
a.value = 5;
bst.insertNode(root, a);
a.value = 6;
bst.insertNode(root, a);
a.value = 7;
bst.insertNode(root, a);

a.value = 8;
bst.insertNode(root, a);

bst.inOrder(root);
return 0;
}



Apparently my root keeps moving from the original position as I insert more items.




I am getting Process finished with exit code 139 (interrupted by signal 11: SIGSEGV) on bst.inOrder(root).



What is the issue here?


Answer



The issue is with the insert node function, here you say if the tree is empty, we set the root to be the address of "toInsert". The problem here is toInsert isn't a reference, it's passed by copy. Which means toInsert is a temporary local copy variable, which expires as soon as the function ends. Meaning your root pointer now doesn't point to anything.



   //NOTE: Passing toInsert, copy is made
Node* BST::insertNode(Node* root, Node toInsert) {
//NOTE: root is null, so we set it to point to the node's copy

if(root == nullptr){
root = &toInsert;
}
//NOTE: The copy is destroyed because we ran out of scope
}


Solution would be to make "toInsert" a pointer, or a reference


PHP Output Buffering



What are the methods to turn on output buffering either within a PHP script or using and htaccess file?



I use the following method in an htaccess file in the root of my application:




php_value output_buffering On
php_value output_handler mb_output_handler


On one of my shared hosting accounts (linux hosting with PHP 5.2.x), the above yields a blank page. Tech support says they can't turn it on in the php.ini file but I can turn it on in my script...



ob_start() and ob_end_flush() also yields the same result. What can I do?


Answer



Use ob_start() and ob_end_flush().




ob_start() at the start of the script before any output (not even an empty space).



When u want to output use ob_end_flush().


What PHP Functions Create Output?

Has anyone ever compiled a list of all the PHP functions/methods that send output to the browser (or STDOUT when running in CLI mode)? A quick search didn't show any manual pages with this information (but I could be wrong there)



I'm interested in functions that are designed to do this, not functions that may raise warnings that would be sent directly to the browser.



The print and echo functions are the obvious ones, I'm looking for a list of lesser known output functions, like readfile.



The main reason I'm asking the question is I'd like a list of functions to check for when tracking down "early output" style errors. (headers can't be set, etc.)

film techniques - Is Hulk a pure CGI being?

In The Incredible Hulk and The Avengers, the Hulk is an obvious CGI character.


However, I am unclear as to how much of him is actual CGI vs motion capture or if his face is a real person's face or another part of the wonders of CGI, etc?


How much of the Hulk can be attributed to a real entity and how much is pure CGI?


Answer


Computer artists start by developing a hand drawing of a character, and places like ILM will sometimes create small clay figures as references.


These are then passed to the modeling artists who convert the concept into a digital character with high level of detail. This is often done with special digital clay sculpting software.


Here are some examples I found;


enter image description here


The face can be done digitally as well, and made to be very realistic.


enter image description here


Those images were taken from artists on the Pixologic community forum at http://www.zbrushcentral.com/forum.php


After digital sculpting is complete, the model is passed to Technical Directors who apply bones/muscles and controls. Also layers of visual effects can be added (smoke, fire, sparks, glowing things). This process is actually very complex and time consuming.


At this point the character has become what is called a "digital asset". It can move through the production pipeline to different departments. It might go back for more sculpting, go to the rendering departing for lighting, go to texture artists for painting, etc.. etc..


The animators will bring the character to life by key framing the motion. They work on shots and sequences assigned to them by a producer. They can acquire data from another department in the form of data files captured during motion capture sessions with an actor. While an actor might have performed motion capture sessions, an animator is still required to clean and apply the sequence to the character. A lot of people think motion capture makes things easier, but it doesn't. It's a challenge to work with.


You can read more about VFX processes at CGSociety. The Wrath of The Titans is a recent example.


jquery - How to get member variable in event handler called from a prototype function in a JavaScript class?

My problem is simplified to something like this:




function ClassA(){
this.x = 2;
}

ClassA.prototype = {
init: function(){
$(window).scroll(this.handleScroll);
},
handleScroll: function(){

... // how to get this.x, this is now referring to window and I cannot pass parameter from window.scroll
}
}

Monday, 28 November 2016

Building Regular Expression (RegEx) to extract text of HTML tag




I am trying to build a regular expression to extract the text inside the HTML tag as shown below. However I have limited skills in regular expressions, and I'm having trouble building the string.



How can I extract the text from this tag:




text



That is just a sample of the HTML source of the page. Basically, I need a regex string to match the "text" inside of the tag. Can anyone assist me with this? Thank you. I hope my question wasn't phrased too horribly.



UPDATE: Just for clarification, report_drilldown is absolute, but I don't really care if it's present in the regex as absolute or not.



145817 is a random 6 digit number that is actually a database id. "text" is just simple plain text, so it shouldn't be invalid HTML. Also, most people are saying that it's best to not use regex in this situation, so what would be best to use? Thanks so much!


Answer



([^<]*)



This won't really solve the problem, but it may just barely scrape by. In particular, it's very brittle, the slightest change to the markup and it won't match. If report_drilldown isn't meant to be absolute, replace it with [^']*, and/or capture both it and the number if you need.



If you need something that parses HTML, then it's a bit of a nightmare if you have to deal with tag soup. If you were using Python, I'd suggest BeautifulSoup, but I don't know something similar for C#. (Anyone know of a similar tag soup parsing library for C#?)


python - Get statistics for each group (such as count, mean, etc) using pandas GroupBy?



I have a data frame df and I use several columns from it to groupby:



df['col1','col2','col3','col4'].groupby(['col1','col2']).mean()



In the above way I almost get the table (data frame) that I need. What is missing is an additional column that contains number of rows in each group. In other words, I have mean but I also would like to know how many number were used to get these means. For example in the first group there are 8 values and in the second one 10 and so on.



In short: How do I get group-wise statistics for a dataframe?


Answer



On groupby object, the agg function can take a list to apply several aggregation methods at once. This should give you the result you need:



df[['col1', 'col2', 'col3', 'col4']].groupby(['col1', 'col2']).agg(['mean', 'count'])

Coraline - Relevance of Buttons (Button-Eyes)? - Movies & TV




What relevance do the buttons (button-eyes) play in Coraline as it never appears to be defined. For those of you who have not yet seen the film, then please do not read any further as the plot will be revealed. For those of you who have seen it, then please continue to read.



My thought was that it was because the Other Mother made the other world and thus used buttons as her 'signature', if you like?



Can anyone clear this up?


Answer



Watched this movie a 1,000 times. My daughter loves it and watched it over and over again.



The eyes are the window to the soul, and once she has your eyes she has your soul.




The other three children let the mother sew buttons into their eyes, and she was able to keep them in the other world. In the original book the mother eats the three children, and their spirits are trapped. The children warn Coraline not to let her sew buttons in her eyes, and Coraline helps free their souls at the end.



I don't think there is really anything deeper in the meaning then that. If Coraline lets the mother sew the buttons into her eyes, then she is becoming compliant and accepting of the new world she's in.


jQuery plugin: Define defaults for NESTED options




I would like to define defaults for nested options like this:



$("div").filters({
url : 'url.example.com'
filters : {
'projects' : {
'type' : 'dropdown',
'min' : 1,
'max' : 10,

'htmlOptions': {
'name' : 'projects',
'class': 'filters',
'id' : 'project-filter',
}
},
'another' : {
'type' : 'dropdown'
}
...

}
});


I use jQuery $.extend() to merge these with the defaults in my plugin code like this:



settings = $.extend(defaults,options);


My code is too big, so I can put all of it here.




The problem I am having is that settings.url works, but I don't know how to do the same with settings.filters because I don't know how many filters the developer is going to want to put here.



Can anyone suggest a better method of dealing with this maybe?



I'm stuck. Thank you


Answer



Because you want to allow the developer to name the filters whatever they want, I assume you don't want to set any defaults for each specific filter (you don't know their names!).



However, you need to set a default empty object for filters.

So your defaults could be:



var defaults = {
url : '',
filters: {}
};


Now, after the merge, you need to iterate over the filters object to see if there are any filters passed in.




See this SO question:
iterating-a-javascript-objects-properties-using-jquery



So you need something like this:



$.each(settings.filters, function(filterName, value) {
alert(filterName + ": " + value);
});



where value will be your filter object {}



You can use this each loop to access all properties inside a filter object.



However, if you want the developer to be able to initialise only some properties of a filter - like in your example, where filter another has only type specified - you need to extend each filter with a set of default filter properties.


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...