Saturday, 31 December 2016

javascript - How do I prevent a parent's onclick event from firing when a child anchor is clicked?




I'm currently using jQuery to make a div clickable and in this div I also have anchors. The problem I'm running into is that when I click on an anchor both click events are firing (for the div and the anchor). How do I prevent the div's onclick event from firing when an anchor is clicked?



Here's the broken code:



JavaScript



var url = $("#clickable a").attr("href");

$("#clickable").click(function() {
window.location = url;

return true;
})


HTML






Answer



Events bubble to the highest point in the DOM at which a click event has been attached. So in your example, even if you didn't have any other explicitly clickable elements in the div, every child element of the div would bubble their click event up the DOM to until the DIV's click event handler catches it.



There are two solutions to this is to check to see who actually originated the event. jQuery passes an eventargs object along with the event:



$("#clickable").click(function(e) {
var senderElement = e.target;
// Check if sender is the
element e.g.
// if($(e.target).is("div")) {

window.location = url;
return true;
});


You can also attach a click event handler to your links which tell them to stop event bubbling after their own handler executes:



$("#clickable a").click(function(e) {
// Do something
e.stopPropagation();

});

html - Stop PHP from making repeat querys on refresh

I'm making a web application, and I'm having trouble figuring out how to stop the PHP from making a query to my database every time the page is reloaded.


Basically when the form is submitted I want the PHP to make a query to the database adding the variables, however, because it has saved those values in the $_POST, it's making a query every time I refresh with those same values.


I want it to make the query, then perhaps unset the $_POST values or something so that it doesn't satisfy the if condition, and in turn stops it from querying the database with repeat values when the submit button hasn't updated them with new values.


Sorry if that's convoluted I'm trying to explain my problem the best I can.


Here is the PHP


//Require login gile -- Fatal error if not found
require_once('login.php');
require_once('app.html');
//Connect w/ MySQL database [login variables]
$con = new mysqli($hn, $un, $pw, $db);
//If connection error -> kill application and display error
if ($con->connect_error) die('Connect Error (' . $con->connect_errno . ') '. $con->connect_error);
//If both goal and difficulty are set
if (!empty($_POST['goal']) && !empty($_POST['difficulty'])) {
$goal = get_post($con, 'goal');
$difficulty = get_post($con, 'difficulty');
$query = "INSERT INTO items VALUES" . "('$goal', 1, '$difficulty', NULL)";
$result = $con->query($query);
if(!$result) echo "INSERT failed: $query
" . $con->error . "

";
}
unset($_POST['goal']);
unset($_POST['difficulty']);
//close connection
$con->close();
function get_post($conn, $var) {
return $conn->real_escape_string($_POST[$var]);
}
?>

html





Testing






















javascript - How to define optional parameter using UI-Router without trailing slash as well?



I was working on migration of my Angularjs code from ng-router to UI-Router. In my ng-router I have optional parameters however I realized that same easy way to support optional parameter is not supported in ui-router. Following is my routes from my existing ng-router module.




//Define routes for view  using ng-router
$routeProvider.
when('/my-app/home/:userid?', {
templateUrl: '/templates/partials/home/HomeView.html',
controller: 'HomeViewController'
})
.when('/my-app/:productKey/:userid?', {
templateUrl: '/templates/partials/productpage/ProductPageView.html',
controller: 'ProductViewController'
})

.otherwise({redirectTo: '/my-app/home'});


Note: If you see ":userid" parameter is very smoothly implemented here as optional.



I tried following in ui-router however same is not working. I have gone through many post and it was suggested to duplicate the routes. I really don't want to duplicate as it will make code dirty.



//Set the default route

$urlRouterProvider.otherwise('/my-app/home');

//Define routes for view (Please make sure the most matched pattern is define at top)
$stateProvider
.state('viewallcards', {
url: '/my-app/home/:userid',
templateUrl: '/templates/partials/home/HomeView.html',
controller: 'HomeViewController'
})
.state('productpage', {
url: '/my-app/:productKey/:userid',
templateUrl: '/templates/partials/productpage/ProductPageView.html',

controller: 'ProductViewController'
});


Here /my-app/home/ works however /my-app/home doesn't work. How to make it without trailing slash as well?



Also following post on same issue has surprised to me to know that this is not supported in ui-router. Is it still valid?
Please help.


Answer



There is a working example




We can use params : {} object to define the userid exactly as we need (i.e. ready to be omitted).



Check more details about params here:



Angular ui router passing data between states without URL



  $stateProvider
.state('viewallcards', {
url: '/my-app/home/:userid',

params: {
userid: {squash: true, value: null }, // this will make both links below working:
// #/my-app/home
// #/my-app/home/
},
...
})
.state('productpage', {
url: '/my-app/:productKey/:userid',
...

})


Check it in action here


Parse JSON in JavaScript?




I want to parse a JSON string in JavaScript. The response is something like



var response = '{"result":true,"count":1}';


How can I get the values result and count from this?


Answer



The standard way to parse JSON in JavaScript is JSON.parse()



The JSON API was introduced with ES5 (2011) and has since been implemented in >99% of browsers by market share, and Node.js. Its usage is simple:



const json = '{ "fruit": "pineapple", "fingers": 10 }';
const obj = JSON.parse(json);
console.log(obj.fruit, obj.fingers);





The only time you won't be able to use JSON.parse() is if you are programming for an ancient browser, such as IE 7 (2006), IE 6 (2001), Firefox 3 (2008), Safari 3.x (2009), etc. Alternatively, you may be in an esoteric JavaScript environment that doesn't include the standard APIs. In these cases, use json2.js, the reference implementation of JSON written by Douglas Crockford, the inventor of JSON. That library will provide an implementation of JSON.parse().



When processing extremely large JSON files, JSON.parse() may choke because of its synchronous nature and design. To resolve this, the JSON website recommends third-party libraries such as Oboe.js and clarinet, which provide streaming JSON parsing.



jQuery once had a $.parseJSON() function, but it was deprecated with jQuery 3.0. In any case, for a long time it was nothing more than a wrapper around JSON.parse().


c - echo $PATH in system() give me a wrong output




This is a piece of code found on Internet



#include                                                                                                                                      
#include



int main(int argc, char* argv[])
{
putenv("PATH=/nothinghere");
//setenv("PATH","/nothinghere");
system(argv[1]);
return 0;
}



if I do



$./a.out "ls"
sh: 1: ls: not found


Of course
But what if




$./a.out "echo $PATH"
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games


It print the original $PATH !!



If we create a new shell then do the samethings



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

putenv("PATH=/nothinghere");
//setenv("PATH","/nothinghere");
system("/bin/sh");
return 0;
}

$./a.out
$ echo $PATH
/nothinghere
$ ls

/bin/sh: 2: ls: not found


Why?
Is it kind of problem about fork or the implementation of echo?


Answer



This is because you're using double quotes, telling your shell to replace $PATH with the value of the PATH variable before it even starts a.out.



The wrong value is thus being inserted not by the shell invoked by system(), but by the shell you're interactively typing commands at.




To fix it, change:



$ ./a.out "echo $PATH"


to:



$ ./a.out 'echo $PATH'

php - Question mark( �) displaying instead of each Bengali unicode character. How to fix it?



The problem is confusing,such as,




When I am trying to display a Bengali unicode word,'কলম' with this



 $data=$_POST['data'];
echo $data;


Then it displays the word 'কলম' properly as I wanted,



But when I split the word character by character with this




    for($i=0;$i<3;$i++)
{
echo $data[$i];
echo "+";
}


Then it display '�+�+�+' instead of displaying like this 'ক+ল+ম+'.




How to solve this problem .Thank you.



For information , I have declared charset utf-8 in head.




< meta http-equiv= " Content-Type " content= " text/html;
charset=utf-8 " />



Answer



Use mb_substr($data, $i, 1) instead. You are using a multi-byte string.



c++ - May accesses to volatiles be reordered?



Consider the following sequence of writes to volatile memory, which I've taken from David Chisnall's article at InformIT, "Understanding C11 and C++11 Atomics":



volatile int a = 1;
volatile int b = 2;
a = 3;



My understanding from C++98 was that these operations could not be reordered, per C++98 1.9:




conforming
implementations are required to emulate (only) the observable behavior of the abstract machine as
explained below
...
The observable behavior of the abstract machine is its sequence of reads and writes to volatile data and

calls to library I/O functions




Chisnall says that the constraint on order preservation applies only to individual variables, writing that a conforming implementation could generate code that does this:



a = 1;
a = 3;
b = 2;



Or this:



b = 2;
a = 1;
a = 3;


C++11 repeats the C++98 wording that





conforming
implementations are required to emulate (only) the observable behavior of the abstract machine as explained
below.




but says this about volatiles (1.9/8):




Access to volatile objects are evaluated strictly according to the rules of the abstract machine.





1.9/12 says that accessing a volatile glvalue (which includes the variables a, b, and c above) is a side effect, and 1.9/14 says that the side effects in one full expression (e.g., a statement) must precede the side effects of a later full expression in the same thread. This leads me to conclude that the two reorderings Chisnall shows are invalid, because they do not correspond to the ordering dictated by the abstract machine.



Am I overlooking something, or is Chisnall mistaken?



(Note that this is not a threading question. The question is whether a compiler is permitted to reorder accesses to different volatile variables in a single thread.)


Answer



IMO Chisnalls interpretation (as presented by you) is clearly wrong. The simpler case is C++98. The sequence of reads and writes to volatile data needs to be preserved and that applies to the ordered sequence of reads and writes of any volatile data, not to a single variable.



This becomes obvious, if you consider the original motivation for volatile: memory-mapped I/O. In mmio you typically have several related registers at different memory location and the protocol of an I/O device requires a specific sequence of reads and writes to its set of registers - order between registers is important.




The C++11 wording avoids talking about an absolute sequence of reads and writes, because in multi-threaded environments there is not one single well-defined sequence of such events across threads - and that is not a problem, if these accesses go to independent memory locations. But I believe the intent is that for any sequence of volatile data accesses with a well-defined order the rules remain the same as for C++98 - the order must be preserved, no matter how many different locations are accessed in that sequence.



It is an entirely separate issue what that entails for an implementation. How (and even if) a volatile data access is observable from outside the program and how the access order of the program maps to externally observable events is unspecified. An implementation should probably give you a reasonable interpretation and reasonable guarantees, but what is reasonable depends on the context.



The C++11 standard leaves room for data races between unsynchronized volatile accesses, so there is nothing that requires surrounding these by full memory fences or similar constructs. If there are parts of memory that are truly used as external interface - for memory-mapped I/O or DMA - then it may be reasonable for the implementation to give you guarantees for how volatile accesses to these parts are exposed to consuming devices.



One guarantee can probably be inferred from the standard (see [into.execution]): values of type volatile std::sigatomic_t must have values compatible with the order of writes to them even in a signal handler - at least in a single-threaded program.


internet explorer - Passing a Javascript function as an argument in IE




I am using a Javascript function do_when to keep evaluating another function and perform an action once it returns true. I found the function here: javascript, wait for something to be true then run action



Here is the do_when function:



function do_when(predicate, action, timeout_step) {
if (predicate()) {
action();
} else {
setTimeout(do_when, timeout_step, predicate, action, timeout_step);

}
}


I am using it to call a jQuery function:



do_when(function() {return tabledrawn;},
function() {$("#mytable tbody tr td").first().click();},
100);



Everything works fine in Firefox and Chrome, but IE9 (and earlier) fails. Specifically, I get an "Object Expected" error when do_when is called from the setTimeout function.



When I do a debug, the predicate and action arguments correctly show up as function objects when do_when is initially called, but when it is called again from the setTimeout function they both show up as undefined. It appears I am not supplying the arguments to setTimeout the way IE wants to see them. Is there a proper way in IE to pass a function object and its parameters as arguments?



EDIT:
Per SLaks suggestions I changed do_when to the following:



function do_when(predicate, action, timeout_step) {
if (predicate()) {
action();

} else {
setTimeout(function () {
do_when(predicate, action, timeout_step);
},
timeout_step);
}
}


Which fixes my problem.



Answer



You're passing additional arguments to setTimeout, and you're expecting them to be passed to your function.



That's a non-standard Mozilla-only feature.



Instead, you need to pass an anonymous function to setTimeout, and call your function with whatever arguments you want inside of it.


android - "Attempt to invoke virtual method on a null object reference" when trying to getLayoutParams of a CardView in a DialogFragment?

I'm trying to set the size of a CardView inside of a DialogFragment, but I get this error:




java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.ViewGroup$LayoutParams android.support.v7.widget.CardView.getLayoutParams()' on a null object reference




This is my code:



        CardView cardView;
onCreate(...){

cardView = (CardView) findViewById(R.id.cardViewInDialogFragment);
}

private void openDialogFragment() {

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

BlankFragment blankFragment = new BlankFragment();
blankFragment.show(getSupportFragmentManager(),"blankFragment");


CardView.LayoutParams layoutParams = (CardView.LayoutParams) cardView.getLayoutParams();
layoutParams.height = displayMetrics.heightPixels - 20;
layoutParams.width = displayMetrics.widthPixels - 20;
cardView.setLayoutParams(layoutParams);
}


Is it not possible or am I doing something wrong?




UPDATE:
The cardView is inside the fragment.



UPDATE 2:



When changing the code to bellow:



BlankFragment:



public static View view;

pulic void onCreateView(...) {

view = inflater.inflate(R.layout.fragment_blank, container, false);
return view;
}


MainActivity:



CardView cardView;

protected void onCreate(...){
...

cardView = (CardView) BlankFragment.view.findViewById(R.id.cardViewInDialogFragment);
openDialogFragment();
}

private void openDialogFragment() {

DisplayMetrics displayMetrics = new DisplayMetrics();

getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

BlankFragment blankFragment = new BlankFragment();
blankFragment.show(getSupportFragmentManager(),"blankFragment");

CardView.LayoutParams layoutParams = (CardView.LayoutParams) cardView.getLayoutParams();
layoutParams.height = displayMetrics.heightPixels - 20;
layoutParams.width = displayMetrics.widthPixels - 20;
cardView.setLayoutParams(layoutParams);
}



, I get this error:




FATAL EXCEPTION: main
Process: com.sim.buttombarnavigationandfragment, PID: 10685
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.sim.buttombarnavigationandfragment/com.sim.buttombarnavigationandfragment.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method

'android.view.View android.view.View.findViewById(int)' on a null
object reference
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2680)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2741)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488)
at android.os.Handler.dispatchMessage(Handler.java:102)

at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6176)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'android.view.View android.view.View.findViewById(int)' on a
null object reference
at

com.sim.buttombarnavigationandfragment.MainActivity.onCreate(MainActivity.java:56)
at android.app.Activity.performCreate(Activity.java:6679)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2633)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2741) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at

android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6176) 
at java.lang.reflect.Method.invoke(Native Method) 
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)


forms - Linking to a custom .php file in custom Wordpress theme



I'm working on a Wordpress theme that has a Jquery animated contact form in it. I've got the js working (a div that's gets shown/hidden on click, with the form in it). Here's a static HTML/PHP example (click the 'contact' button). What's the problem you say? The problem is that the actual form does not get send. I've got the php file 'contact engine.php' that sends the form inside a folder called 'php' in my template directory. In the HTML i've got:
















After a bit of fiddling I've narrowed the problem down to the actual link to the php file. Wordpress does not send the input to the php-file, and nothing gets done. After some Google sessions I found that most people use a plugin for this, which I'm not a fan of. Also it seems that Wordpress does not let you write your own php snippets to implement in the theme. I've also found something that suggests I should put the php snippet in the functions.php file that comes with every template, but I wouldn't know how to link to a specific php snippet inside functions.php. Anyone knows how to solve this? Thanks in advance!



P.S. The php script looks like this:




$EmailFrom = "contactformulier@stefanhagen.nl";
$EmailTo = "info@stefanhagen.nl";
$Subject = "Contactformulier StefanHagen.nl";
$Name = Trim(stripslashes($_POST['Name']));

$Tel = Trim(stripslashes($_POST['Tel']));
$Email = Trim(stripslashes($_POST['Email']));
$Message = Trim(stripslashes($_POST['Message']));

// validation
$validationOK=true;
if (!$validationOK) {
print "";
exit;
}


// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "\n";
// $Body .= "Tel: ";
// $Body .= $Tel;
// $Body .= "\n";
$Body .= "Email: ";

$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";

// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");

// redirect to success page

if ($success){
print "";
}
else{
print "";
}
?>

Answer



I know when you submit a form within WordPress your code will not work since WordPress filters all the post variables. When you use your own script that shouldn't happen. So how does your contactengine.php script looks like. Do you use an include to WordPress in it? If so you do handle WordPress script.




What I see on your site is that
< ?php bloginfo('template_directory'); ?>
doesn't show up. It is also better to use
< ?php echo get_template_directory_uri(); ?>



In case of the plugins people use, I do that too. Easy to change the form in the backend but that can be a negative point since the customer can change it.


EProgrammerNotFound exception in Delphi?




In Delphi 2009, SysUtils.pas contains this in line 425:



EProgrammerNotFound = class(Exception);



  • Is this simply an easter egg or something serious?

  • When should this exception be raised?

  • Does it also exist in Delphi Prism and/or Free Pascal?







Q: Is this exception class still declared in Delphi (currently XE7)?
A: Yes, and it is even documented!




Nonstandard way to indicate software faults.




You can use EProgrammerNotFound as an alternative to indicate software
faults detected at run time.



Answer



It is just the result of a long day and we had gotten a little giddy. For many, many years (ever since I'd been on the team), we'd always joked about replacing some error message in the compiler for one of the most common errors with a similar message. Internally we've always joked and poked fun at different things and people (mostly on the team itself). If you don't have a sense of humor, you're destined to an early grave.



It was a simple conversation;



"Oh, you should have raised the EProgrammerNotFound exception in that function."
"LOL! We should add that exception and see who notices."
"I wonder how much speculation there will be about why it is there?"




So, I guess all I can say is, "You've all played right into our hands ;-)... Buwahahaha! pwned!"


python - How do I limit an output's maximum number of characters?




I'm trying to limit a number's output to 4 characters (including decimals).



def costEdit(nCost):
nCost = '%.2f'%(nCost*1.25)
nCost = nCost * 1.25
return nCost


I want the nCost to be cut off at 2 decimal places. E.g. if the nCost was 8.364912734, cut it off to 8.36 and edit the nCost variable to be replaced with that. Any Ideas?




Im getting the error:



Traceback (most recent call last):
File "C:\Python33\My Codes\TextTowns\TextTowns.py", line 59, in
costEdit(nCost)
File "C:\Python33\My Codes\TextTowns\TextTowns.py", line 27, in costEdit
nCost = nCost*1.25
TypeError: can't multiply sequence by non-int of type 'float'



Im using it as: costEdit(nCost)


Answer



The problem you're having is confusion between a number, and a string representation of a number. These are different things.



When you do this:



nCost = '%.2f'%(nCost*1.25)



… you're multiplying your number by 1.25, then replacing it with a string that represents the number up to two decimal points. So, when you do this:



    nCost = nCost * 1.25


… you're trying to multiply a string by 1.25, which makes no sense.






I suspect you didn't want a string here at all; you just wanted to round the number as a number. To do that, use the round function:




nCost = round(nCost*1.25, 2)





Of course as soon as you multiply by 1.25 again, you may "unround" it by another decimal place or two:



>>> nCost = 1.33333
>>> nCost = round(nCost*1.25, 2)

>>> nCost
1.33
>>> nCost = nCost * 1.25
>>> nCost
1.6625


And really, it's almost always a bad idea to round values before doing arithmetic on them; that just multiplies rounding errors unnecessarily. It's better to just keep the highest-precision value around as long as possible, and round at the last possible second—ideally by using %.2f/{:.2f} formatting in the printing/writing-to-disk/etc. stage.







Another thing to keep in mind is that not all real numbers can be represented exactly as floats. So, for example, round(13.4999, 2) is actually 13.949999999999999289457264. A simple repr or str or %f will print this out as 13.95, so you may not notice… but it's still not exactly 13.95.



The best way to solve this problem, and your other problems, is to use the Decimal type instead of the float type. Then you can round the value to exactly 2 decimal places, do math in a 2-decimal-places context, etc.


Friday, 30 December 2016

plot explanation - How did Bane get out of the pit/prison in The Dark Knight Rises? - Movies & TV



In The Dark Knight Rises, till the end of the movie the audience would be think like, the kid get out from the pit was Bane. But, in the climatic scene the movie revealed that the kid wasn't Bane, it was Talia.



Furthermore, when Bruce was in the pit, his inmates used to say there was only one person escaped/get out from the pit and that was a small kid. According to the movie it was Talia. Then, how's it possible for Bane to get out from the pit?


Answer



After Talia escapes, she informs Ra's Al Ghul of Bane; so he comes to the prison & rescues Bane (this scene is shown for a short time ~5 seconds), and later trains him.



javascript - Can you pass parameters to an AngularJS controller on creation?



I have a controller responsible for communicating with an API to update properties of a user, name, email, etc. Each user has an 'id' which is passed from the server when the profile page is viewed.



I would like to pass this value to the AngularJS controller so it knows what the API entry point is for the current user. I've tried passing the value in ng-controller. For example:



function UserCtrl(id, $scope, $filter) {


$scope.connection = $resource('api.com/user/' + id)


and in the HTML






where {% id %} print the id sent from the server. but I get errors.




What is the correct way to pass a value into a controller on its creation?


Answer



Notes:



This answer is old. This is just a proof of concept on how the desired outcome can be achieved. However, it may not be the best solution as per some comments below. I don't have any documentation to support or reject the following approach. Please refer to some of the comments below for further discussion on this topic.



Original Answer:



I answered this to
Yes you absolutely can do so using ng-init and a simple init function.




Here is the example of it on plunker



HTML











I am {{name}} {{id}}






JavaScript



var app = angular.module('angularjs-starter', []);


app.controller('MainCtrl', function($scope) {

$scope.init = function(name, id)
{
//This function is sort of private constructor for controller
$scope.id = id;
$scope.name = name;
//Based on passed argument you can make a call to resource
//and initialize more objects

//$resource.getMeBond(007)
};


});

java - hashmap values get changed by doing operations like retainAll()

A Map (or any collection) can only contain references to objects, not the objects themselves. When you put a copy of a reference into a collection or get a reference from a collection, you are copying just the reference, not the underlying object.


When you get a set from a Map, and you modify the set, there is only one copy of that set.


NOTE: The Map is not altered when you alter a Set in it.


If you want a copy of a collection, you have to do this explicitly.

c# remove string with quotes from string




I have a string, containing XML namespace, and I cant seem to remove this part



xmlns="http://www.rar.org/xyz/"



I've tried



return textWriter.ToString().Replace(@"xmlns="http://www.rar.org/xyz/"", "");


but this does not compile.


Answer



You need to escape the string. Since you are providing a verbatim string literal (by using the @), you need to use two quotes to escape it:




return textWriter.ToString().Replace(@"xmlns=""http://www.rar.org/xyz/""", "");

php - CodeIgniter Call to a member function get_where() on a non-object

Im super new to codeigniter and am trying to figure out how to use the Models, ive used a MVP framework before but it was a bit different. I have the users controller, which initializes the model(I think I did it right), then the model has a function, that gets a row by email.



The controller looks like:



class Users extends CI_Controller{
public function login(){

$this->load->model('users_model');

$this->users_model->login('slavigne@uark.edu', 'abcdefg');

$this->load->view('templates/header');
$this->load->view('users/login');
$this->load->view('templates/footer');
}
}



and the model looks like:



class users_model extends CI_Model{
public function users_model(){
parent::__construct();
}

public function login($email, $password){
$query = $this->db->get_where('users', array('email' => $email));

return $query->result();
}
}


The problem im getting is:



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



which I understand means that db isn't an object, but all the code I saw for models, say that this should work. Any help or advice would be great! Also any advice on newbie mistakes to codeigniter would be nice!

javascript - regex to validate emails which allows only these two special symbols .,- before @ symbol




I have used below regex for email validation.




var reg = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;


How can i validate the below two email id like




  1. hello!%#%^world@gmail.com

  2. helloworld@-gmail.com




Vaild Email ids:




  1. hello-world@gmail.com

  2. hello.world@gmail.com



InVaild Email ids:





  1. hello!#%#@gmail.com

  2. helloworld@-gmail.com



Special characters should not be allow before @gmail.com



Below is my JavaScript code



var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;


if (!re.test($(this).val())) {
errmsg.push($(this).attr('placeholder') + ' is invalid');
}

Answer



You could try the below regex to validate emails which allows only these two special symbols .,- before @ symbol.



^[^<>()[\]\\,;:\%#^\s@\"$&!@]+@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z0-9]+\.)+[a-zA-Z]{2,}))$



DEMO


python - Converting list of long ints to ints



[112L, 114L, 115L, 116L, 117L, 118L, 119L, 120L, 121L, 122L, 123L, 124L, 125L, 126L] 


How can I convert this list into a list of integer values of those mentioned values? I tried int() but it returned an error. Any idea guys?


Answer




You generally have many ways to do this. You can either use a list comprehension to apply the built-in int() function to each individual long element in your list:



l = [112L, 114L, 115L, 116L, 117L, 118L, 119L, 120L, 121L, 122L, 123L, 124L, 125L, 126L]

l2 = [int(v) for v in l]


which will return the new list l2 with the corresponding int values:



[112, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126]



Or, you could use map(), which is another built-in function, in conjunction with int() to accomplish the same exact thing:



# gives similar results
l2 = map(int, l)

html - Difference between justify-content vs align-content




I am using both justify-content and align content in the flexbox. what is the difference between them????


Answer



Justify-content: The justify-content property aligns the flexed container’s contents on the main axis, which by default(in case of the web) is the horizontal axis.



align-content: The align-content property aligns a flex container’s lines within the flex container when there is extra space on the cross axis.



For more info on this, visit this link- https://css-tricks.com/snippets/css/a-guide-to-flexbox/


How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?





To illustrate, assume that I have two tables as follows:



VehicleID Name
1 Chuck
2 Larry

LocationID VehicleID City
1 1 New York
2 1 Seattle
3 1 Vancouver

4 2 Los Angeles
5 2 Houston


I want to write a query to return the following results:



VehicleID Name    Locations
1 Chuck New York, Seattle, Vancouver
2 Larry Los Angeles, Houston



I know that this can be done using server side cursors, ie:



DECLARE @VehicleID int
DECLARE @VehicleName varchar(100)
DECLARE @LocationCity varchar(100)
DECLARE @Locations varchar(4000)
DECLARE @Results TABLE
(
VehicleID int

Name varchar(100)
Locations varchar(4000)
)

DECLARE VehiclesCursor CURSOR FOR
SELECT
[VehicleID]
, [Name]
FROM [Vehicles]


OPEN VehiclesCursor

FETCH NEXT FROM VehiclesCursor INTO
@VehicleID
, @VehicleName
WHILE @@FETCH_STATUS = 0
BEGIN

SET @Locations = ''


DECLARE LocationsCursor CURSOR FOR
SELECT
[City]
FROM [Locations]
WHERE [VehicleID] = @VehicleID

OPEN LocationsCursor

FETCH NEXT FROM LocationsCursor INTO
@LocationCity

WHILE @@FETCH_STATUS = 0
BEGIN
SET @Locations = @Locations + @LocationCity

FETCH NEXT FROM LocationsCursor INTO
@LocationCity
END
CLOSE LocationsCursor
DEALLOCATE LocationsCursor


INSERT INTO @Results (VehicleID, Name, Locations) SELECT @VehicleID, @Name, @Locations

END
CLOSE VehiclesCursor
DEALLOCATE VehiclesCursor

SELECT * FROM @Results


However, as you can see, this requires a great deal of code. What I would like is a generic function that would allow me to do something like this:




SELECT VehicleID
, Name
, JOIN(SELECT City FROM Locations WHERE VehicleID = Vehicles.VehicleID, ', ') AS Locations
FROM Vehicles


Is this possible? Or something similar?


Answer



If you're using SQL Server 2005, you could use the FOR XML PATH command.




SELECT [VehicleID]
, [Name]
, (STUFF((SELECT CAST(', ' + [City] AS VARCHAR(MAX))
FROM [Location]
WHERE (VehicleID = Vehicle.VehicleID)
FOR XML PATH ('')), 1, 2, '')) AS Locations
FROM [Vehicle]



It's a lot easier than using a cursor, and seems to work fairly well.


php - using autocomplete value to get new value from sqlite and populate edittext

I have a autocomplete code that picks and displays options from the sqlite db based on the first letter/character entered. I want, when the right option is selected from list of displayed options, the value to be passed to a query and the result passed to an edittext field. The autocomplete change listener has a method




afterTextChanged(Editable s)


but it only seemingly accepts one character (not whole string). Any advice on how I can go about this? or an online resource to do further reading?

Thursday, 29 December 2016

RxJava Async task in Android


  1. What is the difference between them?


Observable.just(someMethodWhichThrowsException())
.subscribeOn(Schedulers.newThread())

This is equivalent to the following:


Object someResult = someMethodWhichThrowsException();
Observable.just(someResult)
.subscribeOn(Schedulers.newThread())

As you can see this makes the synchronous method call first, then passes it to Observable.just to become an Observable.


Observable.create(new Observable.OnSubscribe() {
@Override
public void call(Subscriber subscriber) {
...
}
})
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe();

This method, however, will run the code in the call block on subscription. You've told it you want to subscribe on a new thread (subscribeOn(Schedulers.newThread())), so the subscription happens on a new thread, and the code which gets run on subscription (the call block) gets run on that thread too. This is similar behaviour to calling Observable.defer.



  1. What is the best practice while creating async tasks?


Well, that's up to you and your desired behaviour. Sometimes you want the async code to begin running immediately (in which case you may want to cache it using one of the operators for that purpose). I'd definitely consider using the Async Utils library for this.


Other times, you'll want it to run only on subscription (which is the behaviour in the examples here) - for example if there are side-effects, or if you don't care when it's run and just want to use the built-ins to get something off the UI thread. Dan Lew mentions that Observable.defer is very handy for taking old code and getting it off the UI thread, during a conversion to Rx.

How to write a switch statement in Ruby



How do I write a switch statement in Ruby?


Answer



Ruby uses the case expression instead.



case x

when 1..5
"It's between 1 and 5"
when 6
"It's 6"
when "foo", "bar"
"It's either foo or bar"
when String
"You passed a string"
else
"You gave me #{x} -- I have no idea what to do with that."

end


Ruby compares the object in the when clause with the object in the case clause using the === operator. For example, 1..5 === x, and not x === 1..5.



This allows for sophisticated when clauses as seen above. Ranges, classes and all sorts of things can be tested for rather than just equality.



Unlike switch statements in many other languages, Ruby’s case does not have fall-through, so there is no need to end each when with a break. You can also specify multiple matches in a single when clause like when "foo", "bar".


shell - bash script: suppress intermediate output

I am running example scripts from "Kali Network Scanning" book.

Script is using hping3 to scan for a network, first of all it will scan then create a file to operate with. This file will be filtered for only alive addresses on the network:



#!/bin/bash

if [ $# != 1 ]; then
echo 1>&2 "Usage: $0 [/24 network]"
echo 1>&2 "Example: $0 192.168.1.0"
echo 1>&2 "Example will perform scan on network 192.168.1.0/24 and output file in output.txt file"
exit
fi


prefix=$(echo $1 | cut -d '.' -f 1-3)

for addr in $(seq 1 254); do
hping3 $prefix.$addr --icmp -c 1 >> handle.txt &
done
wait
grep len handle.txt | cut -d " " -f 2 | cut -d "-" -f 2 >> output.txt
rm handle.txt



The problem is the loop section is printing out the output.
I would greatly appreciate any help to fix this.



Thanks!

how to do overloading in javascript?

I am trying to learn overloading in javascript. I Googled it and there is a way to do that using arguments length and then by adding switch condition. But I am not interested in doing it like that. Actually I saw one good answer at
Function overloading in Javascript - Best practices but he did not give any example of overloading using his opinion. So, how do you do overloading in javascript.



Here is my code. I need to overload a method using the above solution. He said to do like that: http://jsfiddle.net/m84fg8ac/




function foo(a, b, opts) {

}


foo(1, 2, {"method":"add"});
foo(3, 4, {"test":"equals", "bar":"tree"});



How I will achieve this in my code?



function foo(a, b, opts) {

}

function foo(a) {
console.log("one argument pass");
}


function foo(a, b) {
console.log("two argument pass");
}

function foo(a, b, c) {
console.log("three argument pass");
}


foo(1);

foo(1,2);
foo(1,2,3);


here it is written
The best way to do function overloading with parameters is not to check the argument length or the types; checking the types will just make your code slow and you have the fun of Arrays, nulls, Objects, etc.
What most developers do is tack on an object as the last argument to their methods. This object can hold anything.

javascript - How does the following piece of expression evaluates to "10"




I have recently seen an expression from a source, which looks something like below -




++[[]][+[]]+[+[]]


Entering this into the Chrome (Windows 7, Version 27.0.1453.94 m) console shows a result of "10".



Can someone explain what's happening here?



JSFiddle.


Answer




JavaScript is fairly flexible about converting between data types. The first thing to notice is that +[] evaluates to 0.* That lets us rewrite the expression as:



++[[]][0] + [0]


The next thing to notice is that ++[[]][0] is the preincrement operator applied to the first element of [[]]. Normally you can't apply ++ to an array, but JavaScript kindly converts the first element to 0, so the result is that ++[[]][0] evaluates to 1 (the first element of [[]] having now been incremented). It is kind of like this:



var a = [[]];
var b = ++a[0];
// now a will be [1] and b will be 1



That leaves us with:



1 + [0]


JavaScript now converts the int and the array to strings (since [0] is not a numeric value) and concatenates them together. Done!



* My understanding of how +[] becomes 0 is that it is a two-step process: first, [] is converted to a string primitive, which is the empty string. The empty string then converts to a number, which is zero. Via the same route, [1] evaluates to '1' and then to 1, [2] evaluates to 2, etc. However, [1, 2] evaluates to '1,2' which evaluates to NaN. (The last because the decimal point separator is ., not ,. I don't know what would happen if my locale were different.)



java - What are Dependency Injection & Spring Framework about?

I think I can take a crack at the question, although I'm not sure that any answer will be satisfactory.



The easy answer is that Spring is combination of technologies:




  1. dependency injection, which uses the Hollywood principle to help you keep interface and implementation separate;

  2. aspect oriented programming, which isolates cross cutting concerns into modules that you can apply declaratively. The "hello world" of AOP is logging, but it's all over Spring (e.g. transactions, dynamic proxies for remoting, security, etc.) Think servlet filters and you'll have the idea;

  3. libraries to help with common tasks like persistence (JDBC, Hibernate, iBatis, JDO, JPA, etc.), remoting (RMI, HTTP, web services), asynch messaging (message driven POJOs), validating and binding, web MVC (Spring or Struts), utilities like e-mail, scheduling, security, etc.




But the deeper answer is that you're getting the benefit of Rod Johnson's experience as a consultant on Java EE projects. He distilled what worked for him on his gigs into Interface 21/Spring, and now you can have the benefit of all that for free.



The Spring team writes code that is designed, tested, and follows standards more rigorously than anything I'll ever write. (Imagine Juergen Hoeller browbeating Rod Johnson because his code didn't meet the standard prior to check-in.) I can count on their framework code when I use it and concentrate on my business problem. I'm not writing boiler plate code again and again.



For me, Spring is more about an architectural template that acts as a guide for creating web apps. Some people might say that it's over-engineered, and for certain problems they're correct, but for the kind of problems that I'm faced with on a regular basis Spring is just the ticket.



As for the subquestions:





What advantages do we have when using dependency injection frameworks?




Objects don't have to be responsible for managing their dependencies. Spring's application context is really just a big Factory Pattern from the GoF. It encourages you to design to an interface so you can change the implementation as needed. Your persistence interface might use a JDBC implementation today, Hibernate tomorrow; you might decide to auto generate a proxy to manage its transactional behavior. None of the client code has to change if you code to an interface.




The idea of describing classes with setter values and/or constructor parameters seems strange to me. Why do that? Because we can change the properties without recompiling the
project? Is that all what we gain?





Strange? You don't use properties or constructors in your code? You do it because that's the way most Java classes are written. Spring merely uses those mechanisms as a way to provide dependencies to the class.




Then, what objects should we describe in beans.xml ? All objects or only a few ?




Only the beans that have dependencies. I still call "new" for objects that are local to a particular method. They are created, used, and garbage collected in method scope. Those need not be under Spring's control.

PHP curl. Traversing search results

I am working on a website that allows people to search for an 'x' product and display the results in a table format for example.



I am planning on scraping the search data from another website using php curl. (the owner of the website being scraped is aware and allows it, so no legal issues there).



I already have a php curl code to go and login to the website, and do a search based on user inputs. I have no idea how to go thru the results of the search and output then in my website one by one.



PHP curl code:




$username = '********';
$password = '********';
$loginUrl = 'http://www.a-website.com/login.asp';

//init curl
$ch = curl_init();

//Set the URL to work with
curl_setopt($ch, CURLOPT_URL, $loginUrl);


// ENABLE HTTP POST
curl_setopt($ch, CURLOPT_POST, 1);

//Set the post parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, 'username=' . $username . '&password=' . $password . '&submit1=' . 'Login');

//Handle cookies for the login
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie stuff hure');


//Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL
//not to print out the results of its query.
//Instead, it will return the results as a string return value
//from curl_exec() instead of the usual true/false.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//execute the request (the login)
$store = curl_exec($ch);

/* * *****************SEARCH HERE****************** */

curl_setopt($ch, CURLOPT_URL, 'http://www.a-website.com/Index.asp');
//execute the request
$content = curl_exec($ch);


//Set the post parameters

curl_setopt($ch, CURLOPT_POSTFIELDS, 'search_txt_vs=' . '' . '&search_txt_UPC=' . '' . '&search_txt_Name=' . $searchString .
'&search_txt_Manufacturer=' . '' . '&submit=' . 'Search');
//execute the request (the search)

$Search = curl_exec($ch);

print CJSON::encode($Search);
print $Search;

//save the data to disk
print $content;


Here is the html code from the website Im scrapping (which btw is in old school table format)






























































































































Sort > NDC
Brand Name
Strength
 |  UD
Stock
Manufacturer
AWP
 /  Your Price
  UPC
Generic Alt/Name
Size
 |  Form
Category
1

[add]

00169347718
NOVOLIN 70/ 30U/ML CRT 5X3 ML

70-30 U/ML
YES
NOVO NORDISK PHARM
$

0.01 


 / $

0.01


000000000000

HUM INSULIN NPH/REG INSULIN HM
5X3ML
 

[return]
INSULIN

2

[add]

00169347418
NOVOLIN N 100 UN/ML CRT 5X3 ML
100 U/ML
YES
NNP
$

0.00 


 / $

0.01


000000000000
NPH HUMAN INSULIN ISOPHANE
5X3ML
 

[return]
INSULIN

3

[add]

00169231721
NOVOLIN INNO 70/30 PFS 5X3 ML
70-30 U/ML

YES
NOVO NORDISK PHARM
$


0.00 


 / $

0.01


000000000000
HUM INSULIN NPH/REG INSULIN HM
5X3ML
 

[return]
INSULIN

4

[add]

00169183311
NOVOLIN R 100 UN/ML VL 10 ML
100 U/ML

YES
NOVO NORDISK PHARM
$

99.00 

 / $


82.09


000169183311
INSULIN REGULAR HUMAN

10ML
 

[return]
INSULIN

5

[add]

00169183711
NOVOLIN 70/ 30U/ML VL 10 ML
70-30 U/ML
YES
NOVO NORDISK PHARM
$

99.00 

 / $


82.09


000169183711
HUM INSULIN NPH/REG INSULIN HM
10ML
 

[return]
INSULIN

6


[add]

00169183411
NOVOLIN N 100 UN/ML VL 10 ML
100 U/ML
YES

NOVO NORDISK PHARM
$

99.00 

 / $

82.09



000000000000
NPH HUMAN INSULIN ISOPHANE
10ML

 

[return]
INSULIN




html - Is it possible to select elements that do not have a child of a certain type?



I'm trying to select elements that are not the parents of elements. (Note: if it's relevant some of the anchors I want to select are childless.) I tried this:



a > :not(img) {}



and this:



a:not(> img) {}


but neither of them seem to work. How would I accomplish this in CSS?


Answer



There is a spec, currently in draft, for a :has() pseudo-class. No browser supports it yet. If the spec is someday approved and implemented, you'd be able to do this:



a:not(:has(img)) {

// Styles
}


The MDN page says that :has would never work in stylesheets, only in JavaScript; but in saying that, it links to a section of the spec about a "dynamic selector profile" that apparently no longer exists.



I think the browser vendors typically have a problem with implementing CSS features that require knowledge of the DOM that only exists after the selected element is created, so I don't know if we should get our hopes up for this. Someone who follows the mailing lists or is generally smarter than me might offer a better prognosis.


c# - Case insensitive 'Contains(string)'



Is there a way to make the following return true?



string title = "ASTRINGTOTEST";

title.Contains("string");


There doesn't seem to be an overload that allows me to set the case sensitivity.. Currently I UPPERCASE them both, but that's just silly (by which I am referring to the i18n issues that come with up- and down casing).



UPDATE
This question is ancient and since then I have realized I asked for a simple answer for a really vast and difficult topic if you care to investigate it fully.
For most cases, in mono-lingual, English code bases this answer will suffice. I'm suspecting because most people coming here fall in this category this is the most popular answer.
This answer however brings up the inherent problem that we can't compare text case insensitive until we know both texts are the same culture and we know what that culture is. This is maybe a less popular answer, but I think it is more correct and that's why I marked it as such.


Answer



To test if the string paragraph contains the string word (thanks @QuarterMeister)



culture.CompareInfo.IndexOf(paragraph, word, CompareOptions.IgnoreCase) >= 0



Where culture is the instance of CultureInfo describing the language that the text is written in.



This solution is transparent about the definition of case-insensitivity, which is language dependent. For example, the English language uses the characters I and i for the upper and lower case versions of the ninth letter, whereas the Turkish language uses these characters for the eleventh and twelfth letters of its 29 letter-long alphabet. The Turkish upper case version of 'i' is the unfamiliar character 'İ'.



Thus the strings tin and TIN are the same word in English, but different words in Turkish. As I understand, one means 'spirit' and the other is an onomatopoeia word. (Turks, please correct me if I'm wrong, or suggest a better example)



To summarise, you can only answer the question 'are these two strings the same but in different cases' if you know what language the text is in. If you don't know, you'll have to take a punt. Given English's hegemony in software, you should probably resort to CultureInfo.InvariantCulture, because it'll be wrong in familiar ways.


c - Why gcc does not give a warning or error when invalid mode is used in fopen()?



I am practicing some practice questions in FILE IO in C. Below is one of the programs.



#include
#include

int main()
{
char fname[]="poem.txt";

FILE *fp;
char ch;
fp = fopen ( fname, "tr");
if (fp == NULL)
{
printf("Unable to open file...\n");
exit(1);
}
while((ch =fgetc(fp)) != EOF)
{

printf("%c",ch);
}
printf("\n");

return 0;
}


As you can see in the statement




  fp = fopen ( fname, "tr");


The mode "tr" is not a valid mode (as I understand). I was expecting gcc to give an error (or a warning) while compiling the above program. However, gcc does not give any error (or warning) while compiling it.



However, as expected, when i run the program it exits printing "Unable to open file..." which means fopen() returned NULL , because there was error while opening file.



-bash-4.1$ ./a.out
Unable to open file...
-bash-4.1$



(The file poem.txt exists so this is because of the invalid mode given to fopen(). I checked by changing the mode to "r" and it works fine displaying the content of "poem.txt")



-bash-4.1$ ./a.out
THis is a poem.

-bash-4.1$



I was expecting gcc to give an error (or warning) message for the invalid mode.



Why gcc does not give any error (or warning) for this ?


Answer



This is Undefined Behavior:



Per Annex J.2 "Undefined Behavior", it is UDB if:




—The string pointed to by the mode argument in a call to the fopen function does not exactly match one of the specified character sequences (7.19.5.3).





Although Annex J is informative, looking at §7.19.5.3:




/3 The argument mode points to a string. If the string is one of the following, the file is open in the indicated mode. Otherwise, the behavior is undefined.




Basically, the compiler can blow you off here - a standard library function name (and behavior) can be used outside of the inclusion of a standard header (for example, non-standard extensions, completely user-defined behavior, etc.). The Standard specifies what a conforming library implementation shall include and how it shall behave, but does not require you to use that standard library (or define behavior for a specific implementation explicitly specified as UDB territory: at this point, if your parameter types match it's a legal function call).




A really good lint utility might help you here.


How does the "&" operator work in a PHP function?



Please see this code:




function addCounter(&$userInfoArray) {
$userInfoArray['counter']++;
return $userInfoArray['counter'];
}

$userInfoArray = array('id' => 'foo', 'name' => 'fooName', 'counter' => 10);
$nowCounter = addCounter($userInfoArray);

echo($userInfoArray['counter']);



This will show 11.



But! If you remove "&"operator in the function parameter, the result will be 10.



What's going on?


Answer



The & operator tells PHP not to copy the array when passing it to the function. Instead, a reference to the array is passed into the function, thus the function modifies the original array instead of a copy.



Just look at this minimal example:




function foo($a) { $a++; }
function bar(&$a) { $a++; }

$x = 1;
foo($x);
echo "$x\n";
bar($x);
echo "$x\n";

?>


Here, the output is:



1
2


– the call to foo didn’t modify $x. The call to bar, on the other hand, did.



c: size of void*



I'm a bit confused with a void* pointer in C. Especially after reading this question: Is the sizeof(some pointer) always equal to four?, where one person says there is no guarantee that sizeof(int *) == sizeof(double *)



My question is: is there a guarantee of sizeof(void*) >= sizeof(any other pointer type)?

In other words, can I always assign a some_type* pointer to a void* pointer and then get it back as some_type*?


Answer



Only data pointers. void * can hold any data pointer, but not function pointers.



Here is a C FAQ.




void *'s are only guaranteed to hold object (i.e. data) pointers; it
is not portable to convert a function pointer to type void *. (On some
machines, function addresses can be very large, bigger than any data

pointers.)




As for the first part, yes, different types can have pointers of different sizes:


Wednesday, 28 December 2016

What is the difference between declaration and definition of a variable in C++?

My question stems from studying Effective C++ by Scott Meyers.
In Item II of that book, following is written :




To limit the scope of a constant to a class, you must make it a member and, to ensure there's at most one copy of the constant, you must make it a static member.




That is correctly written. Then immediately the following example is given :




class GamePlayer {
private:
static const int NumTurns = 5;
int scores[NumTurns];
....
};


Then the following is written pertaining to the above example :





What you see above is a declaration and not a definition of NumTurns.




My First question is : What is the meaning of this statement ?



Immediately after that the following is mentioned :




Usually C++ requires that you provide a definition for anything you use, but class specific constants that are static and of integral type (e.g - integers, chars, bools) are an exception. As long as you don't take their address, you can declare them and use them without providing a definition. If you do take the address of a class constant, or if your compiler incorrectly insists on a definition even if you don't take the address, you provide a separate definition like this :

const int GamePlayer::Numturns; //definition of NumTurns




Why now it is a definition and not a declaration ?



I understand the difference in the context of a function but do not understand it in the context of a regular variable. Also, can someone expand on what the author means by




... if you do take the address of a class constant, or if your ..
part of the above quoted paragraph ?





P.S : I am a relatively newbie in C++.

html - RegEx match open tags except XHTML self-contained tags




I need to match all of these opening tags:








But not these:









I came up with this and wanted to make sure I've got it right. I am only capturing the a-z.



<([a-z]+) *[^/]*?>


I believe it says:




  • Find a less-than, then


  • Find (and capture) a-z one or more times, then

  • Find zero or more spaces, then

  • Find any character zero or more times, greedy, except /, then

  • Find a greater-than



Do I have that right? And more importantly, what do you think?


Answer



You can't parse [X]HTML with regex. Because HTML can't be parsed by regex. Regex is not a tool that can be used to correctly parse HTML. As I have answered in HTML-and-regex questions here so many times before, the use of regex will not allow you to consume HTML. Regular expressions are a tool that is insufficiently sophisticated to understand the constructs employed by HTML. HTML is not a regular language and hence cannot be parsed by regular expressions. Regex queries are not equipped to break down HTML into its meaningful parts. so many times but it is not getting to me. Even enhanced irregular regular expressions as used by Perl are not up to the task of parsing HTML. You will never make me crack. HTML is a language of sufficient complexity that it cannot be parsed by regular expressions. Even Jon Skeet cannot parse HTML using regular expressions. Every time you attempt to parse HTML with regular expressions, the unholy child weeps the blood of virgins, and Russian hackers pwn your webapp. Parsing HTML with regex summons tainted souls into the realm of the living. HTML and regex go together like love, marriage, and ritual infanticide. The

cannot hold it is too late. The force of regex and HTML together in the same conceptual space will destroy your mind like so much watery putty. If you parse HTML with regex you are giving in to Them and their blasphemous ways which doom us all to inhuman toil for the One whose Name cannot be expressed in the Basic Multilingual Plane, he comes. HTML-plus-regexp will liquify the n​erves of the sentient whilst you observe, your psyche withering in the onslaught of horror. Rege̿̔̉x-based HTML parsers are the cancer that is killing StackOverflow it is too late it is too late we cannot be saved the trangession of a chi͡ld ensures regex will consume all living tissue (except for HTML which it cannot, as previously prophesied) dear lord help us how can anyone survive this scourge using regex to parse HTML has doomed humanity to an eternity of dread torture and security holes using regex as a tool to process HTML establishes a breach between this world and the dread realm of c͒ͪo͛ͫrrupt entities (like SGML entities, but more corrupt) a mere glimpse of the world of reg​ex parsers for HTML will ins​tantly transport a programmer's consciousness into a world of ceaseless screaming, he comes, the pestilent slithy regex-infection wil​l devour your HT​ML parser, application and existence for all time like Visual Basic only worse he comes he comes do not fi​ght he com̡e̶s, ̕h̵i​s un̨ho͞ly radiańcé destro҉ying all enli̍̈́̂̈́ghtenment, HTML tags lea͠ki̧n͘g fr̶ǫm ̡yo​͟ur eye͢s̸ ̛l̕ik͏e liq​uid pain, the song of re̸gular exp​ression parsing will exti​nguish the voices of mor​tal man from the sp​here I can see it can you see ̲͚̖͔̙î̩́t̲͎̩̱͔́̋̀ it is beautiful t​he final snuffing of the lie​s of Man ALL IS LOŚ͖̩͇̗̪̏̈́T ALL I​S LOST the pon̷y he comes he c̶̮omes he comes the ich​or permeates all MY FACE MY FACE ᵒh god no NO NOO̼O​O NΘ stop the an​*̶͑̾̾​̅ͫ͏̙̤g͇̫͛͆̾ͫ̑͆l͖͉̗̩̳̟̍ͫͥͨe̠̅s ͎a̧͈͖r̽̾̈́͒͑e n​ot rè̑ͧ̌aͨl̘̝̙̃ͤ͂̾̆ ZA̡͊͠͝LGΌ ISͮ̂҉̯͈͕̹̘̱ TO͇̹̺ͅƝ̴ȳ̳ TH̘Ë͖́̉ ͠P̯͍̭O̚​N̐Y̡ H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ







Have you tried using an XML parser instead?







Moderator's Note



This post is locked to prevent inappropriate edits to its content. The post looks exactly as it is supposed to look - there are no problems with its content. Please do not flag it for our attention.




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