I'm wanting to make sure I understand pass-by-value vs pass-by-reference properly. In particular, I'm looking at the prefix/postfix versions of the increment ++ operator for an object.
Let's suppose we have the following class X:
class X{ private: int i; public: X(){i=0;} X& operator ++ (){ ++i; return *this; } //prefix increment
X operator ++ (int unused){ //postfix increment X ret(*this); i++;
return ret; }
operator int(){ return i; } //int cast };
First of all, have I implemented the prefix/postfix increment operators properly?
Second, how memory-efficient is the postfix operator, compared to the prefix operator? Specifically how many X object copies are created when each version of the operator is used?
An explanation of exactly what happens with return-by-reference vs return-by-value might help me understand.
Edit: For example, with the following code...
X a; X b=a++;
...are a and b now aliases?
Answer
This is a correct implementation. It is typical that a postfix operator will be worse on performance because you have to create another copy before doing the increment (and this is why I've gotten in the habit of always using prefix unless I need something else).
With return-by-reference, you're returning an l-value reference to the current object. The compiler would typically implement this by returning the address of the current object. This means that returning the object is as simple as returning a number.
However, with return-by-value, a copy must be done. This means there's more information to copy over during the return (instead of just an address) as well as a copy constructor to call. This is where your performance hit comes in.
The efficiency of your implementation looks on-par with typical implementations.
EDIT: With regards to your addendum, no, they are not aliases. You have created two separate objects. When you return by value (and when you created a new object from within the postfix increment operator) this new object is placed in a distinct memory location.
However, in the following code, a and b are aliases:
I have not been able to find a proper regex to match any string not ending with some condition. For example, I don't want to match anything ending with an a.
This matches
b ab 1
This doesn't match
a
ba
I know the regex should be ending with $ to mark the end, though I don't know what should preceed it.
Edit: The original question doesn't seem to be a legit example for my case. So: how to handle more than one character? Say anything not ending with ab?
My app that worked fine on iOS 7 doesn't work with the iOS 8 SDK.
CLLocationManager doesn't return a location, and I don't see my app under Settings -> Location Services either. I did a Google search on the issue, but nothing came up. What could be wrong?
Answer
I ended up solving my own problem.
Apparently in iOS 8 SDK, requestAlwaysAuthorization (for background location) or requestWhenInUseAuthorization (location only when foreground) call on CLLocationManager is needed before starting location updates.
There also needs to be NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription key in Info.plist with a message to be displayed in the prompt. Adding these solved my problem.
I'm new to JavaScript, and trying to get a JSON object to post on my website. However, I can't get a success response. Since I don't have a proper debugger, I don't see error messages.
This is my code so far, I've read that it could be a security problem and I should look for JSONP, but I haven't found any proper examples to understand it.
I'm writing a Server-side application based on NodeJS. The application listen on some TCP and UDP ports for incoming messages, when the messages arrive they are parsed and the relevant data are stored into a MySQL database. The whole thing works fine and NodeJS capability to handle parallel concurrent requests is amazing. However reading around the feedback about NodeJS dangers I've found something that brings confusion to me: the question is about callbacks. Imagine the code below:
function ParseMessage(payload,callback_ko,callback_ok) { // here we evaluate the parsed_message content, err is set if parsing errors occurs .... if(!err) { // if there are no errors invoke the callback_ok to let the flow continue passing the parsed content if(typeof callback_ok == 'function') { callback_ok(parsed_message); } else { // if error occurs invoke the callback_ko passing the payload to let the flow continue in another path, maybe attempt another parsing if(typeof callback_ko =='function') { callback_ko(payload); } } return; // <---- Ensure the functions ends }
The code if(typeof callback == 'function') is placed to avoid to call arguments passed to ParseMessage function that is not a function (in that case the ParseMessage simply must exit returning anything as result). My doubt is about the return; statement: I know the return statement MUST always be present (correct me if I'm wrong with that) in order to allow the async function ends properly. As we're not returning anything here (we're invoking callbacks here) we simply don't return anything on it, but I don't know if the place where return statement is written is the right one. In other words, should I place the return statement at the end of the function or should I have something like this, instead:
function ParseMessage(payload,callback_ko,callback_ok) { // here we evaluate the parsed_message content, err is set if parsing errors occurs .... if(!err) { // if there are no errors invoke the callback_ok to let the flow continue passing the parsed content if(typeof callback_ok == 'function') { callback_ok(parsed_message); } return; // <---- Ensure the functions ends else { // if error occurs invoke the callback_ko passing the payload to let the flow continue in another path, maybe attempt another parsing if(typeof callback_ko =='function') { callback_ko(payload); } return; // <---- Ensure the functions ends } }
I've found that someone also suggest to write something like return callback(payload);. What's the most correct strategy?
Let's say I'm using #include in C++ and I'm making a print statement. I can choose either to:
using namespace std; [...] cout << "Hello" << endl;
or
using std::cout; using std::endl; [...] cout << "Hello" << endl;
or
std::cout << "Hello" << std::endl;
I'm led to believe, and perhaps this is incorrect, that the first one is somewhat to be avoided, as it can add a lot of unnecessary bloat to your program. However, I don't know if there's any difference between the second and third styles in terms of performance. The majority of code that I see that uses libraries tends to use the third style; however for me if there's no tradeoff in using the second one, it seems like the cleanest and most readable method, especially if you're making a lot of calls to the functions or objects in question.
I have a textbox where i can type double quoted words like: hello i am "steve" and i can successfully insert the string into my database after mysqli_real_escape_string
php below:
$text_data = $_POST['description']; // hello my name is "steve" $final_text = mysqli_real_escape_string($this->conn,$text_data);
// the above without removing double quotes can be inserted into the db
but if it is single quotes and I convert to double quotes then it cannot be inserted.
$text_data = $_POST['description']; // hello my name is 'steve' $final_text = str_replace("'",'"',$text_data); $final_text = mysqli_real_escape_string($this->conn,$text_data);
so my questions are:
how come it works with double quotes? doesn't it needs to be removed or replaced with "/ something?
if the first case: double quotes work fine, then how come the second case when converted from single to double quotes cannot be inserted into the db?
Thanks a lot in advance
Answer
A couple things..
First I would do some reading on the differences between the single quote and the double quote's behaviors. Just so going forward you have a basis for the differences between the two.
Secondly lets look at the logic of your code:
If I replace the single quotes in your code like your code suggest your statement will look like this:
"hello my name is "steve""
No lets look closly at what happens between " and steve.
"hello my name is " steve ""
The reason your query is failing, I believe is because steve is not quoted anymore.
Using prepared statement is really your best solution to the problem.
Hope that helps
UPDATED:
$text_data = "hello my name is 'steve'"; $final_text = str_replace("'",'\"',$text_data);
I have an xml which has many number of rows. For a particular given attribute id, the element name and price value should be queried. For instance, my tree looks like:
How can I get the name and price value of an particular id(1 or 2 or 3)?
I tried minidom for parsing. My code is:
from xml.dom import minidom xmldoc = minidom.parse('D:/test.xml') nodes = xmldoc.getElementsByTagName('food') for node in nodes: if node.attributes['id'].value == '1':
????????????????????
And am unable to retrieve the name and price tag value. I checked lot of examples and none satisfied.
It Worked. Code is as follows:
import xml.etree.ElementTree as ET tree = ET.parse('D:/test.xml') root = tree.getroot()
for child in root: testing = child.get('id') if testing == '3': print child.tag, child.attrib print child.find('name').text print child.find('price').text
Answer
Check out the standard etree library. It allows you to parse an xml file into a Python object called an ElementTree. You can then call various methods on this object, such as .findall("./food/name").
This might get you started:
import xml.etree.ElementTree as ET tree = ET.parse('D:/test.xml') root = tree.getroot()
def get_info(food_id): for child in root.findall("*[@id='{0}']//".format(food_id)): print(child.text)
I have an application with a complex layout where the user could put (drag/drop) widgets (by choosing from a predefined set of 100+ widgets) where every widget is a custom implementation that displays a set of data (fetched using REST call) in a specific way. I've read tons of blog posts, stackoverflow questions and the official AngularJS docs but I cannot figure out how should I design my application to handle there requirements. Looking at demo apps, there is a single module (ng-app) and when constructing it in the .js file the dependent modules are declared as its dependencies, however i have a big set of widgets and somehow it's not advisable to describe them all there. I need suggession for the following questions:
How should I design my app and widgets - should i have a separate AngularJS module or each widget should be a directive to the main module?
If I design my widget as directives, is there a way to define dependency within a directive. I.e. to say that my directive uses ng-calender in its implementation?
If I design each widget as a separate module, is there a way to dynamically add the widget module as a dependency to the main module?
How should I design the controllers - one controller per widget probably?
How should i separate the state (scope) if i have multiple widgets from the same type in the view?
Are there bestpractices for designing reusable widgets with AngularJS?
EDIT
Useful references:
Answer
These are just general advices.
How should I design my app and widgets - should i have a separate AngularJS module or each widget should be a directive to the main module?
You're talking hundres of widgets, it seems natural to split them into several modules. Some widgets might have more in common than other widgets. Some might be very general and fit in other projects, others are more specific.
If I design my widget as directives, is there a way to define dependency within a directive. I.e. to say that my directive uses ng-calender in its implementation?
Dependencies to other modules are done on a module level, but there is no problem if module A depends on module B and both A and B depends on module C. Directives are a natural choice for creating widgets in Angular. If a directive depends on another directive you either define them in the same module, or create the dependency on a modular level.
If I design each widget as a separate module, is there a way to dynamically add the widget module as a dependency to the main module?
I'm not sure why you would want to do this, and I'm not sure how to do it. Directives and services are not initialized before they get used in Angular. If you have a huge library of directives (widgets) and know that you'll probably use some of them, but not all of them - but you don't know which ones will get used when the application gets initialized you can actually "lazy load" your directives after your module has been loaded. I've created an example here
The benefit is that you can get your application to load fast even if you have lots of code, because you don't have to load the scripts before you need them. The disadvantage is that there can be a considerably delay the first time a new directive is loaded.
How should I design the controllers - one controller per widget probably?
A widget will probably need its own controller. Controllers should generally be small, if they get big you can consider if there's any functionality that would fit better in a service.
How should i separate the state (scope) if i have multiple widgets from the same type in the view?
Widgets that need scope variables should without doubt have their own isolated scopes (scope:{ ... } in the directive configuration).
Are there bestpractices for designing reusable widgets with AngularJS?
Why the following guess is wrong ? (a software engineering company manager told me that it's almost correct but I don't understand why and I can't search for the answer in the Internet..)
int* ptr = new int; // Sorry I mistyped before
My claim :
left part (ptr) is of static memory allocation.
right part (new int) is of dynamic memory allocation.
// new edited : 1 Jan 2015 17:39 (UTC +08:00) what I am thinking is, It moves the pointer of stack down(or up?) to free a space for ptr. And find a empty space for a new int. And then store the address of this new int to ptr.
And the code is just running with no runtime exceptions!
The output was 58
How can it be? Isn't the memory of a local variable inaccessible outside its function?
Answer
How can it be? Isn't the memory of a local variable inaccessible outside its function?
You rent a hotel room. You put a book in the top drawer of the bedside table and go to sleep. You check out the next morning, but "forget" to give back your key. You steal the key!
A week later, you return to the hotel, do not check in, sneak into your old room with your stolen key, and look in the drawer. Your book is still there. Astonishing!
How can that be? Aren't the contents of a hotel room drawer inaccessible if you haven't rented the room?
Well, obviously that scenario can happen in the real world no problem. There is no mysterious force that causes your book to disappear when you are no longer authorized to be in the room. Nor is there a mysterious force that prevents you from entering a room with a stolen key.
The hotel management is not required to remove your book. You didn't make a contract with them that said that if you leave stuff behind, they'll shred it for you. If you illegally re-enter your room with a stolen key to get it back, the hotel security staff is not required to catch you sneaking in. You didn't make a contract with them that said "if I try to sneak back into my room later, you are required to stop me." Rather, you signed a contract with them that said "I promise not to sneak back into my room later", a contract which you broke.
In this situation anything can happen. The book can be there -- you got lucky. Someone else's book can be there and yours could be in the hotel's furnace. Someone could be there right when you come in, tearing your book to pieces. The hotel could have removed the table and book entirely and replaced it with a wardrobe. The entire hotel could be just about to be torn down and replaced with a football stadium, and you are going to die in an explosion while you are sneaking around.
You don't know what is going to happen; when you checked out of the hotel and stole a key to illegally use later, you gave up the right to live in a predictable, safe world because you chose to break the rules of the system.
C++ is not a safe language. It will cheerfully allow you to break the rules of the system. If you try to do something illegal and foolish like going back into a room you're not authorized to be in and rummaging through a desk that might not even be there anymore, C++ is not going to stop you. Safer languages than C++ solve this problem by restricting your power -- by having much stricter control over keys, for example.
UPDATE
Holy goodness, this answer is getting a lot of attention. (I'm not sure why -- I considered it to be just a "fun" little analogy, but whatever.)
I thought it might be germane to update this a bit with a few more technical thoughts.
Compilers are in the business of generating code which manages the storage of the data manipulated by that program. There are lots of different ways of generating code to manage memory, but over time two basic techniques have become entrenched.
The first is to have some sort of "long lived" storage area where the "lifetime" of each byte in the storage -- that is, the period of time when it is validly associated with some program variable -- cannot be easily predicted ahead of time. The compiler generates calls into a "heap manager" that knows how to dynamically allocate storage when it is needed and reclaim it when it is no longer needed.
The second method is to have a “short-lived” storage area where the lifetime of each byte is well known. Here, the lifetimes follow a “nesting” pattern. The longest-lived of these short-lived variables will be allocated before any other short-lived variables, and will be freed last. Shorter-lived variables will be allocated after the longest-lived ones, and will be freed before them. The lifetime of these shorter-lived variables is “nested” within the lifetime of longer-lived ones.
Local variables follow the latter pattern; when a method is entered, its local variables come alive. When that method calls another method, the new method's local variables come alive. They'll be dead before the first method's local variables are dead. The relative order of the beginnings and endings of lifetimes of storages associated with local variables can be worked out ahead of time.
For this reason, local variables are usually generated as storage on a "stack" data structure, because a stack has the property that the first thing pushed on it is going to be the last thing popped off.
It's like the hotel decides to only rent out rooms sequentially, and you can't check out until everyone with a room number higher than you has checked out.
So let's think about the stack. In many operating systems you get one stack per thread and the stack is allocated to be a certain fixed size. When you call a method, stuff is pushed onto the stack. If you then pass a pointer to the stack back out of your method, as the original poster does here, that's just a pointer to the middle of some entirely valid million-byte memory block. In our analogy, you check out of the hotel; when you do, you just checked out of the highest-numbered occupied room. If no one else checks in after you, and you go back to your room illegally, all your stuff is guaranteed to still be there in this particular hotel.
We use stacks for temporary stores because they are really cheap and easy. An implementation of C++ is not required to use a stack for storage of locals; it could use the heap. It doesn't, because that would make the program slower.
An implementation of C++ is not required to leave the garbage you left on the stack untouched so that you can come back for it later illegally; it is perfectly legal for the compiler to generate code that turns back to zero everything in the "room" that you just vacated. It doesn't because again, that would be expensive.
An implementation of C++ is not required to ensure that when the stack logically shrinks, the addresses that used to be valid are still mapped into memory. The implementation is allowed to tell the operating system "we're done using this page of stack now. Until I say otherwise, issue an exception that destroys the process if anyone touches the previously-valid stack page". Again, implementations do not actually do that because it is slow and unnecessary.
Instead, implementations let you make mistakes and get away with it. Most of the time. Until one day something truly awful goes wrong and the process explodes.
This is problematic. There are a lot of rules and it is very easy to break them accidentally. I certainly have many times. And worse, the problem often only surfaces when memory is detected to be corrupt billions of nanoseconds after the corruption happened, when it is very hard to figure out who messed it up.
More memory-safe languages solve this problem by restricting your power. In "normal" C# there simply is no way to take the address of a local and return it or store it for later. You can take the address of a local, but the language is cleverly designed so that it is impossible to use it after the lifetime of the local ends. In order to take the address of a local and pass it back, you have to put the compiler in a special "unsafe" mode, and put the word "unsafe" in your program, to call attention to the fact that you are probably doing something dangerous that could be breaking the rules.
In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This particular scene was quite strange and confused me pretty badly, because she's a mammoth, why did she hang on the tree like that?
Further, I've only watched the Ice Age3 and Ice Age4. Did I miss anything? Did they show any scene towards Peaches' mom's strange behavior in the previous parts?
Answer
In Ice Age 2, when Elle was first introduced, she thought she was a possum, thus hanging upside down in a tree to sleep. Some of her habits were taught to Peaches, thus the girl sleeping upside down.
In Ice Age 4, there was a line of dialogue from Peaches about being half possum. this came from the idea that Elle still believes herself to be a possum, but that Peaches' dad is a mammoth.
Well for one thing Ted is already an adult in his 30's and also isn't he telling the story to his kids in 2030 (which is only 18 years from now), so someone's voice does not change that much in 18 years! (Ted's voice hasn't changed that much in the 8 years the show has been on!)
i keep receiving this error each time i try to submit the a form deletion form.
Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\speedycms\deleteclient.php:47) in C:\xampp\htdocs\speedycms\deleteclient.php on line 106
is there something wrong with my code? what do i need to change to make it work?
// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False;
// When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers);
$arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && true) { $isValid = true;
mysql_select_db($database_speedycms, $speedycms); $query_delete = "SELECT * FROM tbl_accident WHERE id=$client_id"; $delete = mysql_query($query_delete, $speedycms) or die(mysql_error()); $row_delete = mysql_fetch_assoc($delete); $totalRows_delete = mysql_num_rows($delete); ?>
Are you sure you wish to delete the record for ?
thanking you in advance!
Answer
Lines 45-47:
?>
That's sending a couple of newlines as output, so the headers are already dispatched. Just remove those 3 lines (it's all one big PHP block after all, no need to end PHP parsing and then start it again), as well as the similar block on lines 60-62, and it'll work.
Notice that the error message you got actually gives you a lot of information to help you find this yourself:
Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\speedycms\deleteclient.php:47) in C:\xampp\htdocs\speedycms\deleteclient.php on line 106
The two bolded sections tell you where the item is that sent output before the headers (line 47) and where the item is that was trying to send a header after output (line 106).
I just learned that at school, but the teacher doesn't know why.
I can think of some good reasons, but I think there are cases when the initializing can be done later in the constructor- before you use the variables form the mother class, for example. OK, the variables should be initialized from the start, but that's not always necessary.
I"m guessing there are a more reasons for that why must super() be placed in the first line of the constructor.
So, why must I write super() in the first line of the constructor, when I'm inheriting a class?
I would like to check whether a variable is either an array or a single value in JavaScript.
I have found a possible solution...
if (variable.constructor == Array)...
Is this the best way this can be done?
Answer
There are several ways of checking if an variable is an array or not. The best solution is the one you have chosen.
variable.constructor === Array
This is the fastest method on Chrome, and most likely all other browsers. All arrays are objects, so checking the constructor property is a fast process for JavaScript engines.
If you are having issues with finding out if an objects property is an array, you must first check if the property is there.
Update May 23, 2019 using Chrome 75, shout out to @AnduAndrici for having me revisit this with his question This last one is, in my opinion the ugliest, and it is one of the slowest fastest. Running about 1/5 the speed as the first example. This guy is about 2-5% slower, but it's pretty hard to tell. Solid to use! Quite impressed by the outcome. Array.prototype, is actually an array. you can read more about it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
variable instanceof Array
This method runs about 1/3 the speed as the first example. Still pretty solid, looks cleaner, if you're all about pretty code and not so much on performance. Note that checking for numbers does not work as variable instanceof Number always returns false. Update: instanceof now goes 2/3 the speed!
This guy is the slowest for trying to check for an Array. However, this is a one stop shop for any type you're looking for. However, since you're looking for an array, just use the fastest method above.
Note: @EscapeNetscape has created another test as jsperf.com is down. http://jsben.ch/#/QgYAV I wanted to make sure the original link stay for whenever jsperf comes back online.
Both plots feature an adventure in the city of Chicago. There are some similar scenes such as the scene at the French restaurant and over-the-top musical numbers. The two movies had a very similar feel in many places and I can't help but compare them.
Were the creators of Ferris Bueller's Day Off inspired by Blues Brothers? Were specific parallels drawn intentionally?
the default created_at date keep printing out as an MySQL format : 2015-06-12 09:01:26. I wanted to print it as my own way like 12/2/2017, and other formats in the future.
a file called DataHelper.php and store it at /app/Helpers/DateHelper.php - and it looks like this
namespace App\Helpers;
class DateHelper {
public static function dateFormat1($date) { if ($date) { $dt = new DateTime($date);
return $dt->format("m/d/y"); // 10/27/2014 } }
}
to be able to called it in my blade view like
DateHelper::dateFormat1($user->created_at)
I'm not sure what to do next.
What is the best practice to create a custom helper function in php Laravel 5?
Answer
Within your app/Http directory, create a helpers.php file and add your functions.
Within composer.json, in the autoload block, add "files": ["app/Http/helpers.php"].
I have to update a field with a value which is returned by a join of 3 tables.
Example:
select im.itemid ,im.sku as iSku ,gm.SKU as GSKU ,mm.ManufacturerId as ManuId
,mm.ManufacturerName ,im.mf_item_number ,mm.ManufacturerID from item_master im, group_master gm, Manufacturer_Master mm where im.mf_item_number like 'STA%' and im.sku=gm.sku and gm.ManufacturerID = mm.ManufacturerID and gm.manufacturerID=34
I want to update the mf_item_number field values of table item_master with some other value which is joined in the above condition.
How can I do this in MS SQL Server?
Answer
UPDATE im SET mf_item_number = gm.SKU --etc FROM item_master im JOIN group_master gm
ON im.sku = gm.sku JOIN Manufacturer_Master mm ON gm.ManufacturerID = mm.ManufacturerID WHERE im.mf_item_number like 'STA%' AND gm.manufacturerID = 34
To make it clear... The UPDATE clause can refer to an table alias specified in the FROM clause. So im in this case is valid
Generic example
UPDATE A SET foo = B.bar FROM TableA A JOIN TableB B ON A.col1 = B.colx WHERE ...
There seem to be different views on using 'using' with respect to the std namespace.
Some say use ' using namespace std', other say don't but rather prefix std functions that are to be used with ' std::' whilst others say use something like this:
using std::string; using std::cout; using std::cin; using std::endl; using std::vector;
You can either use the == operator or the Object.equals(Object) method.
The == operator checks whether the two subjects are the same object, whereas the equals method checks for equal contents (length and characters).
if(objectA == objectB) { // objects are the same instance. i.e. compare two memory addresses against each other. } if(objectA.equals(objectB)) { // objects have the same contents. i.e. compare all characters to each other }
Which you choose depends on your logic - use == if you can and equals if you do not care about performance, it is quite fast anyhow.
String.intern() If you have two strings, you can internate them, i.e. make the JVM create a String pool and returning to you the instance equal to the pool instance (by calling String.intern()). This means that if you have two Strings, you can call String.intern() on both and then use the == operator. String.intern() is however expensive, and should only be used as an optimalization - it only pays off for multiple comparisons.
All in-code Strings are however already internated, so if you are not creating new Strings, you are free to use the == operator. In general, you are pretty safe (and fast) with