I want to replace string "Cannot" with "Can not" and "cannot" with "can not". For that, I am using the code below:
String string = "I Cannot do it."; string = string.replaceAll("([Cc])annot", "\\1an not");
Desired string is "I Can not do it.".
String string = "I Cannot do it."; string = string.replaceAll("([Cc])annot", "\\1an not");
Desired string is "I can not do it". In Ruby '\1' replaces a string with the matched character C or c (using back reference). I don't know what to use in Java. Below is the Ruby regex which works fine:
"I Cannot do it".gsub!(/([Cc])annot/,'\1an not') # => "I Can not do it" "I cannot do it".gsub!(/([Cc])annot/,'\1an not') # => "I can not do it"
Answer
What about
String string = "I Cannot do it." string = string.replaceAll("([Cc])annot","$1an not");
05-03 20:14:01.577: WARN/System.err(1515): java.io.IOException: Received authentication challenge is null 05-03 20:14:01.596: WARN/System.err(1515): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.doRequestInternal(HttpURLConnectionImpl.java:1694) 05-03 20:14:01.577: INFO/QQWeiBo(1515): Received authentication challenge is null 05-03 20:14:01.577: WARN/System.err(1515): java.io.IOException: Received authentication challenge is null 05-03 20:14:01.577: WARN/System.err(1515): java.io.IOException: Received authentication challenge is null 05-03 20:14:01.596: WARN/System.err(1515): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.doRequestInternal(HttpURLConnectionImpl.java:1694) 05-03 20:14:01.596: WARN/System.err(1515): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.doRequest(HttpURLConnectionImpl.java:1649)
05-03 20:14:01.596: WARN/System.err(1515): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:1374) 05-03 20:14:01.596: WARN/System.err(1515): at com.szy.weibo.service.SyncHttp.httpGet(SyncHttp.java:72) 05-03 20:14:01.596: WARN/System.err(1515): at com.szy.weibo.service.Weibo.getRequestToken(Weibo.java:45) 05-03 20:14:01.606: WARN/System.err(1515): at com.szy.weibo.MainActivity.startWebView(MainActivity.java:95) 05-03 20:14:01.606: WARN/System.err(1515): at com.szy.weibo.MainActivity.authorization(MainActivity.java:83) 05-03 20:14:01.606: WARN/System.err(1515): at com.szy.weibo.MainActivity$1.onClick(MainActivity.java:71) 05-03 20:14:01.606: WARN/System.err(1515): at android.view.View.performClick(View.java:2408) 05-03 20:14:01.596: WARN/System.err(1515): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.doRequestInternal(HttpURLConnectionImpl.java:1694) 05-03 20:14:01.596: WARN/System.err(1515): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.doRequest(HttpURLConnectionImpl.java:1649) 05-03 20:14:01.596: WARN/System.err(1515): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:1374)
05-03 20:14:01.596: WARN/System.err(1515): at com.szy.weibo.service.SyncHttp.httpGet(SyncHttp.java:72) 05-03 20:14:01.596: WARN/System.err(1515): at com.szy.weibo.service.Weibo.getRequestToken(Weibo.java:45) 05-03 20:14:01.606: WARN/System.err(1515): at com.szy.weibo.MainActivity.startWebView(MainActivity.java:95) 05-03 20:14:01.606: WARN/System.err(1515): at com.szy.weibo.MainActivity.authorization(MainActivity.java:83) 05-03 20:14:01.606: WARN/System.err(1515): at com.szy.weibo.MainActivity$1.onClick(MainActivity.java:71) 05-03 20:14:01.606: WARN/System.err(1515): at android.view.View.performClick(View.java:2408) 05-03 20:14:01.596: WARN/System.err(1515): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.doRequest(HttpURLConnectionImpl.java:1649) 05-03 20:14:01.596: WARN/System.err(1515): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:1374) 05-03 20:14:01.596: WARN/System.err(1515): at com.szy.weibo.service.SyncHttp.httpGet(SyncHttp.java:72) 05-03 20:14:01.596: WARN/System.err(1515): at com.szy.weibo.service.Weibo.getRequestToken(Weibo.java:45)
05-03 20:14:01.606: WARN/System.err(1515): at com.szy.weibo.MainActivity.startWebView(MainActivity.java:95) 05-03 20:14:01.606: WARN/System.err(1515): at com.szy.weibo.MainActivity.authorization(MainActivity.java:83) 05-03 20:14:01.606: WARN/System.err(1515): at com.szy.weibo.MainActivity$1.onClick(MainActivity.java:71) 05-03 20:14:01.606: WARN/System.err(1515): at android.view.View.performClick(View.java:2408) 05-03 20:14:01.606: WARN/System.err(1515): at android.view.View$PerformClick.run(View.java:8816) 05-03 20:14:01.616: WARN/System.err(1515): at android.os.Handler.handleCallback(Handler.java:587) 05-03 20:14:01.627: WARN/System.err(1515): at android.os.Handler.dispatchMessage(Handler.java:92) 05-03 20:14:01.627: WARN/System.err(1515): at android.os.Looper.loop(Looper.java:123) 05-03 20:14:01.627: WARN/System.err(1515): at android.app.ActivityThread.main(ActivityThread.java:4627) 05-03 20:14:01.627: WARN/System.err(1515): at java.lang.reflect.Method.invokeNative(Native Method)
05-03 20:14:01.606: WARN/System.err(1515): at android.view.View$PerformClick.run(View.java:8816) 05-03 20:14:01.616: WARN/System.err(1515): at android.os.Handler.handleCallback(Handler.java:587) 05-03 20:14:01.627: WARN/System.err(1515): at android.os.Handler.dispatchMessage(Handler.java:92) 05-03 20:14:01.627: WARN/System.err(1515): at android.os.Looper.loop(Looper.java:123) 05-03 20:14:01.627: WARN/System.err(1515): at android.app.ActivityThread.main(ActivityThread.java:4627) 05-03 20:14:01.627: WARN/System.err(1515): at java.lang.reflect.Method.invokeNative(Native Method) 05-03 20:14:01.627: WARN/System.err(1515): at java.lang.reflect.Method.invoke(Method.java:521) 05-03 20:14:01.647: WARN/System.err(1515): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 05-03 20:14:01.647: WARN/System.err(1515): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 05-03 20:14:01.647: WARN/System.err(1515): at dalvik.system.NativeStart.main(Native Method)
05-03 20:14:01.606: WARN/System.err(1515): at android.view.View$PerformClick.run(View.java:8816) 05-03 20:14:01.616: WARN/System.err(1515): at android.os.Handler.handleCallback(Handler.java:587) 05-03 20:14:01.627: WARN/System.err(1515): at android.os.Handler.dispatchMessage(Handler.java:92) 05-03 20:14:01.627: WARN/System.err(1515): at android.os.Looper.loop(Looper.java:123) 05-03 20:14:01.627: WARN/System.err(1515): at android.app.ActivityThread.main(ActivityThread.java:4627) 05-03 20:14:01.627: WARN/System.err(1515): at java.lang.reflect.Method.invokeNative(Native Method) 05-03 20:14:01.627: WARN/System.err(1515): at java.lang.reflect.Method.invoke(Method.java:521) 05-03 20:14:01.647: WARN/System.err(1515): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 05-03 20:14:01.647: WARN/System.err(1515): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 05-03 20:14:01.647: WARN/System.err(1515): at dalvik.system.NativeStart.main(Native Method)
05-03 20:14:01.627: WARN/System.err(1515): at java.lang.reflect.Method.invoke(Method.java:521) 05-03 20:14:01.647: WARN/System.err(1515): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 05-03 20:14:01.647: WARN/System.err(1515): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 05-03 20:14:01.647: WARN/System.err(1515): at dalvik.system.NativeStart.main(Native Method)
I have a problem that I can not answer. I write an BBCODE editor with switch between a WYSIWYG editor and code editor.
The visual editor is built from a drag and drop blocs system (picture, text, ...)
In the visual editor, when an user drag a new text bloc, the content is automatically written between [text][/text] tags.
In the code editor, user can write free text without [text][/text] tags.
To be able to switch between the two editors, free text need to be added between [text][/text] tags in code editor.
Example :
I write text and bbcode in code editor :
Cum haec taliaque sollicitas eius aures everberarent expositas semper eius modi
rumoribus et patentes. [img]https://foo.com/fighters.png[/img] Denique Antiochensis ordinis vertices sub uno elogio iussit occidi ideo efferatus, quod ei celebrari vilitatem intempestivam urgenti, cum inpenderet inopia [img]https://foo.com/fighters1.png[/img] [img]https://foo.com/fighters2.png[/img] Utque proeliorum periti rectores [i]primo catervas[/i] densas opponunt et fortes, deinde leves armaturas, post iaculatores ultimasque subsidiales acies, si fors adegerit
If i switch to visual editor, the free text need to be added between [text][/text] like this:
[text]Cum haec taliaque sollicitas eius aures everberarent expositas semper eius modi rumoribus et patentes.[/text] [img]https://foo.com/fighters.png[/img] [text]Denique Antiochensis ordinis vertices sub uno elogio iussit occidi ideo efferatus, quod ei celebrari vilitatem intempestivam urgenti, cum inpenderet inopia[/text] [img]https://foo.com/fighters1.png[/img] [img]https://foo.com/fighters2.png[/img]
[text]Utque proeliorum periti rectores [i]primo catervas[/i] densas opponunt et fortes, deinde leves armaturas, post iaculatores ultimasque subsidiales acies, si fors adegerit[/text]
I think there are two ways:
Split text and bbcode with loops, and rebuild code with another loops.
Use a regex to get free text and replace it.
What the best way ? Do you think that possible to add the tags from a regex ?
Thank you, Thomas
Answer
Try with this:
const regex = /(\[(img|\w{4,})\][\s\S]*?\[\/\2\])(\n?)|([\s\S]+?)(\n?)(?=$|\[(?:img|\w{4,})\])/gi; let str = ` Cum haec taliaque sollicitas eius aures everberarent expositas semper eius modi rumoribus et patentes. [image]https://foo.com/fighters.png[/image] Denique Antiochensis ordinis vertices sub uno elogio iussit occidi ideo efferatus, quod ei celebrari vilitatem intempestivam urgenti, cum inpenderet inopia [image]https://foo.com/fighters1.png[/image] [image]https://foo.com/fighters2.png[/image]
Utque proeliorum periti rectores [i]primo catervas[/i] densas opponunt et fortes, deinde leves armaturas, post iaculatores ultimasque subsidiales acies, si fors adegerit`;
let m; let outstr = '';
while ((m = regex.exec(str)) !== null) { // This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) { regex.lastIndex++; }
// The result can be accessed through the `m`-variable. // m[1] == structure tags // m[4] == text content // m[3] nad m[5] are new lines (if present) if (typeof m[1] != 'undefined') { outstr += m[1] + m[3]; } else {
On the regex, you use the first capturing group to get rid of the structural tags. And the second group for the rest of the data. If the first group has data then it means we found an structural tag. We just accumlate it. If not, then it means it is text. So we accumulate it with the new [text] tags
Finally, on 3rd and 5th capturing group you have the new lines (if present)
The second capturing group is used for making the opening and closing tag equal.
# First option: an structural tag ([image]...[/image] ( # First capturing group
\[ # Literal '[' (img|\w{4,}) # img tag or tag with 4 or more letters (all structural tags) \] # Literal ']' [\s\S]*? # Any character 0 or more times, ungreedy \[\/\2\] # Closing tag. Word = same as opening tag )(\n?) # a new line may appear. Save it on third capturing group
# Second option: other text | ([\s\S]+?) # Any character 1 or more times, ungreedy. Third capturing group (\n?) # A new line may appear, Don't want it on the previous group
(?= # Lookahead. The following must appear (but we don't match it) $ # Either end of line | \[(?:img|\w{4,})\] # or some opening structural tag )
I'm trying to override the functionality of the back key press. When the user presses it once, I want it to come back to the previous screen. However, when the back key is long-pressed (for, let's say, two seconds or more), I want to exit the application.
By now, I have overriden these two methods in my activity:
@Override public boolean onKeyDown( int keyCode, KeyEvent event){ if (keyCode == KeyEvent.KEYCODE_BACK) {
//manage short keypress return true; } return super.onKeyDown(keyCode, event); }
@Override public boolean onKeyLongPress( int keyCode, KeyEvent event){ if (keyCode == KeyEvent.KEYCODE_BACK) { //manage long keypress (different code than short one)
But the onKeyLongPress callback is never called, because the event is always received by the onKeyDown method.
Is there any way of having both methods working? Or has it to be done all in the onKeyDown and use the number of repetitions/milliseconds to detect it?
From reading here I've understood zombies are objects which are:
deallocated
but something pointer is still trying to point to them and send messages to them.
not exactly sure how that's different from accessing a deallocated object.
I mean in Swift you can do:
var person : Person? = Person(name: "John")
person = nil print(person!.name)
Is person deallocated? Yes!
Are we trying to point to it? Yes!
So can someone share the most common mistake which leads to creating a dangling pointer?
Answer
This is not a dangling pointer or a zombie. When you use ! you're saying "if this is nil, then crash." You should not think of person as a pointer in Swift. It's a value. That value may be .some(T) or it may be .none (also called nil). Neither of those is dangling. They're just two different explicit values. Swift's nil is nothing like null pointers in other languages. It only crashes like null pointers when you explicitly ask it to.
To create zombies, you'll need to be using something like Unmanaged. This is extremely uncommon in Swift.
The primitive types (number, string, etc.) are passed by value, but objects are unknown, because they can be both passed-by-value (in case we consider that a variable holding an object is in fact a reference to the object) and passed-by-reference (when we consider that the variable to the object holds the object itself).
Although it doesn't really matter at the end, I want to know what is the correct way to present the arguments passing conventions. Is there an excerpt from JavaScript specification, which defines what should be the semantics regarding this?
I'm currently programming a logger class, but the operator<< method causes a compiler error. Here's a minimized version of the class, in file "logger.h":
#include class Logger { public: Logger() : m_file(std::cout) {}
template Logger &operator<<(const T &a) { m_file< return *this; }
protected: std::ostream& m_file; };
It is included in my main.cpp and works perfecly when I output a string literal:
log << "hi";
However, the following won't compile.
#include "logger.h" int main() { Logger log;
log << std::endl; }
The g++ compiler reports:
src/main.cpp:5: error: no match for 'operator<<' in 'log << std::endl'
Answer
Your problem is not about the chain of << , a single log << endl would also cause the problem. It is because std::endl is a template function:
template
basic_ostream& endl(basic_ostream& os);
One of the overload of operator<< in basic_ostream is:
template > class basic_ostream : virtual public basic_ios { public: basic_ostream& operator<<( basic_ostream& (*pf)(basic_ostream&));
//... };
So the template parameters can be deduced when std::cout< is used. However, when the left side is the class Logger, the compile cannot deduce the template parameters of endl. Explicitly give the template parameters can let program compile and work:
I am letting the user to upload the dataset into my R Shiny app and then I let him to specify the time variable of this dataset and whether it's in monthly or quarterly frequency. The data uploaded by the user are called model_data within the server. Then I want to create a new column in model_data named time_var_use which will be the time variable selected by the user, but converted to yearmon (for monthly data) or to yearqtr (for quarterly data) format.
I am struggling with the creation of this new variable time_var_use and with updating one of my inputs input$time_threshold based on the unique values of time_var_use.
The part of the code that does not work is observeEvent() at the end of the server environment. I am trying to create time_var_use column inside observeEvent and then update the values of input$time_threshold with it.
I didn't know how to attach an example CSV file here that I am uploading to the app (model_data from above), so I am just copying data from this example CSV file below:
I am trying to get data from a site and be able to manipulate it to display it on my own site. The site contains a table with ticks and is updated every few hours. Here's an example: http://www.astynomia.gr/traffic-athens.php
This data is there for everyone to use, and I will mention them on my own site just to be sure.
I've read something about php's cURL but I have no idea if this is the way to go. Any pointers/tutorials, or code anyone could provide so I can start somewhere would be very helpful. Also any pointers on how I can get informed as soon as the site is updated?
Answer
If you want to crawl the page, use something like Simple HTML DOM Parser for PHP. That'll server your purpose.
boolean hasFoundSurplusChangedSign = false; int h = 1; for(int k=0; k if (k==0){ mVCBArray[k]=mVBArray[k]; }else{ mVCBArray[k]=mVCBArray[k-1]+mVBArray[k]; } mMVTArray[k]= Math.min(mVCBArray[k],mVCAArray[k]); mSArray[k]= mVCBArray[k]-mVCAArray[k];
if (!hasFoundSurplusChangedSign && k>0){ if (Integer.signum(mSArray[k]) * Integer.signum(mSArray[k-1]) > 0){ h = k+1; }else{ hasFoundSurplusChangedSign = true; } } }
runs faster than this one :
boolean hasFoundSurplusChangedSign = false; int h = 1; for(int k=0; k if (k==0){ mVCBArray[k]=mVBArray[k]; }else{ mVCBArray[k]=mVCBArray[k-1]+mVBArray[k]; }
mMVTArray[k]= Math.min(mVCBArray[k],mVCAArray[k]); mSArray[k]= mVCBArray[k]-mVCAArray[k]; } for(int k=0; k if (!hasFoundSurplusChangedSign && k>0){ if (Integer.signum(mSArray[k]) * Integer.signum(mSArray[k-1]) > 0){ h = k+1; }else{ hasFoundSurplusChangedSign = true; }
} }
all the Arrays are int arrays. The size of each array is constant and equal to 1000. the for loops iterate roughly 100 times (ie size = 100 roughly).
So, the first code runs in average in 6 microsecond while the second code runs in 3.5 microsecond. It seems that splitting the loop into two smaller loops improve the performance of my code here. Why?
Is it the compiler that compile differently the two versions of my code? I read somewhere that it could be because the processor cannot put the whole loop code in its cache and so needs to swap between different cache zone, while in the second case, it could, so it goes faster. I am not sure to understand this argument. Does that sounds possible to you? Any other ideas?
A piece of C++ code determines the occurances of zero and keeps a binary flag variable for each number that is checked. The value of the flag toggles between 0 and 1 each time a zero is encountered in a 1 dimensional array.
I am attempting to use SSE to speed it up, but I am unsure of how to go about this. Evaluating the individual fields of __m128i is inefficient, I've read.
The code in C++ is:
int flag = 0; int var_num2[1000]; for(int i = 0; i<1000; i++) { if (var[i] == 0) { var_num2[i] = flag;
flag = !flag; //toggle value upon encountering a 0 } }
After I run this, I get a runtime error "double free or corruption". If I get rid of the destructor content (the delete) it works fine. What's wrong?
Answer
Let's talk about copying objects in C++.
Test t;, calls the default constructor, which allocates a new array of integers. This is fine, and your expected behavior.
Trouble comes when you push t into your queue using q.push(t). If you're familiar with Java, C#, or almost any other object-oriented language, you might expect the object you created earler to be added to the queue, but C++ doesn't work that way.
When we take a look at std::queue::push method, we see that the element that gets added to the queue is "initialized to a copy of x." It's actually a brand new object that uses the copy constructor to duplicate every member of your original Test object to make a new Test.
Your C++ compiler generates a copy constructor for you by default! That's pretty handy, but causes problems with pointer members. In your example, remember that int *myArray is just a memory address; when the value of myArray is copied from the old object to the new one, you'll now have two objects pointing to the same array in memory. This isn't intrinsically bad, but the destructor will then try to delete the same array twice, hence the "double free or corruption" runtime error.
How do I fix it?
The first step is to implement a copy constructor, which can safely copy the data from one object to another. For simplicity, it could look something like this:
Now when you're copying Test objects, a new array will be allocated for the new object, and the values of the array will be copied as well.
We're not completely out trouble yet, though. There's another method that the compiler generates for you that could lead to similar problems - assignment. The difference is that with assignment, we already have an existing object whose memory needs to be managed appropriately. Here's a basic assignment operator implementation:
The important part here is that we're copying the data from the other array into this object's array, keeping each object's memory separate. We also have a check for self-assignment; otherwise, we'd be copying from ourselves to ourselves, which may throw an error (not sure what it's supposed to do). If we were deleting and allocating more memory, the self-assignment check prevents us from deleting memory from which we need to copy.
Could someone explain to me why do some programmers use (char*) in front of the malloc? I know that it returns void but why do I want it to return just char memory? I'm sorry, I'm just a newbie in programming. Thank you
Answer
No need to cast return value of malloc as its return type is void*.
Can someone explain why do some programmers use (char *) in front of the malloc?
They are doing wrong (most probably) by casting it (in good programmers opinion).
malloc returns a void pointer (void *), which indicates that it is a pointer to a region of unknown data type. The use of casting is required in C++ due to the strong type system, whereas this is not the case in C1. The lack of a specific pointer type returned from malloc is type-unsafe behavior according to some programmers: malloc allocates based on byte count but not on type. This is different from the C++ new operator that returns a pointer whose type relies on the operand. One may "cast" this pointer to a specific type:
int *ptr; ptr = malloc(10 * sizeof (*ptr)); /* without a cast */ ptr = (int *)malloc(10 * sizeof (*ptr)); /* with a cast */ ptr = reinterpret_cast(malloc(10 * sizeof (*ptr))); /* with a cast, for C++ */
There are advantages and disadvantages to performing such a cast.
Advantages to casting:
Including the cast allows a program or function to compile as C++.
The cast allows for pre-1989 versions of malloc that originally returned a char *.
Casting can help the developer identify inconsistencies in type sizing should the destination pointer type change, particularly if the pointer is declared far from the malloc() call.
Disadvantages to casting:
Under the ANSI C standard, the cast is redundant.
Adding the cast may mask failure to include the header stdlib.h, in which the prototype for malloc is found. In the absence of a prototype for malloc, the standard requires that the C compiler assume malloc returns an int. If there is no cast, a warning is issued when this integer is assigned to the pointer; however, with the cast, this warning is not produced, hiding a bug. On certain architectures and data models (such as LP64 on 64-bit systems, where long and pointers are 64-bit and int is 32-bit), this error can actually result in undefined behavior, as the implicitly declared malloc returns a 32-bit value whereas the actually defined function returns a 64-bit value. Depending on calling conventions and memory layout, this may result in stack smashing. This issue is less likely to go unnoticed in modern compilers, as they uniformly produce warnings that an undeclared function has been used, so a warning will still appear. For example, GCC's default behavior is to show a warning that reads "incompatible implicit declaration of built-in function" regardless of whether the cast is present or not.
If the type of the pointer is changed, one must fix all code lines where malloc was called and cast (unless it was cast to a typedef).
If the range of actual types that can be used is finite and the combinations must be individually specified prior to use, this is called ad-hoc polymorphism.
parametric polymorphism:
If all code is written without mention of any specific type and thus can be used transparently with any number of new types it is called parametric polymorphism.
I can hardly understand them :(
can anyone explain them both if possible with an example? I hope the answers to this questions would be helpful for many new passouts from their colleges.
Answer
Understanding of / requirements for polymorphism
To understand polymorphism - as the term is used in Computing Science - it helps to start from a simple test for and definition of it. Consider:
Type1 x; Type2 y;
f(x); f(y);
Here, f() is to perform some operation and is being given values x and y as inputs.
To exhibit polymorphism, f() must be able to operate with values of at least two distinct types (e.g. int and double), finding and executing distinct type-appropriate code.
C++ mechanisms for polymorphism
Explicit programmer-specified polymorphism
You can write f() such that it can operate on multiple types in any of the following ways:
Preprocessing:
#define f(X) ((X) += 2) // (note: in real code, use a longer uppercase name for a macro!)
Overloading:
void f(int& x) { x += 2; }
void f(double& x) { x += 2; }
Templates:
template void f(T& x) { x += 2; }
Virtual dispatch:
struct Base { virtual Base& operator+=(int) = 0; };
struct X : Base { X(int n) : n_(n) { } X& operator+=(int n) { n_ += n; return *this; } int n_;
Compiler-provided polymorphism for builtin types, Standard conversions, and casting/coercion are discussed later for completeness as:
they're commonly intuitively understood anyway (warranting a "oh, that" reaction),
they impact the threshold in requiring, and seamlessness in using, the above mechanisms, and
explanation is a fiddly distraction from more important concepts.
Terminology
Further categorisation
Given the polymorphic mechanisms above, we can categorise them in various ways:
When is the polymorphic type-specific code selected?
Run time means the compiler must generate code for all the types the program might handle while running, and at run-time the correct code is selected (virtual dispatch)
Compile time means the choice of type-specific code is made during compilation. A consequence of this: say a program only called f above with int arguments - depending on the polymorphic mechanism used and inlining choices the compiler might avoid generating any code for f(double), or generated code might be thrown away at some point in compilation or linking. (all mechanisms above except virtual dispatch)
Which types are supported?
Ad-hoc meaning you provide explicit code to support each type (e.g. overloading, template specialisation); you explicitly add support "for this" (as per ad hoc's meaning) type, some other "this", and maybe "that" too ;-).
Parametric meaning you can just try to use the function for various parameter types without specifically doing anything to enable its support for them (e.g. templates, macros). An object with functions/operators that act like the template/macro expects1is all that template/macro needs to do its job, with the exact type being irrelevant. The "concepts" cut from C++11 help express and enforce such expectations - let's hope they make it into a later Standard.
Parametric polymorphism provides duck typing - a concept attributed to James Whitcomb Riley who apparently said "When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.".
Subtype (aka inclusion) polymorphism allows you to work on new types without updating the algorithm/function, but they must be derived from the same base class (virtual dispatch)
1 - Templates are extremely flexible. SFINAE (see also std::enable_if) effectively allows several sets of expectations for parametric polymorphism. For example, you might encode that when the type of data you're processing has a .size() member you'll use one function, otherwise another function that doesn't need .size() (but presumably suffers in some way - e.g. using the slower strlen() or not printing as useful a message in the log). You can also specify ad-hoc behaviours when the template is instantiated with specific parameters, either leaving some parameters parametric (partial template specialisation) or not (full specialisation).
"Polymorphic"
Alf Steinbach comments that in the C++ Standard polymorphic only refers to run-time polymorphism using virtual dispatch. General Comp. Sci. meaning is more inclusive, as per C++ creator Bjarne Stroustrup's glossary (http://www.stroustrup.com/glossary.html):
polymorphism - providing a single interface to entities of different types. Virtual functions provide dynamic (run-time) polymorphism through an interface provided by a base class. Overloaded functions and templates provide static (compile-time) polymorphism. TC++PL 12.2.6, 13.6.1, D&E 2.9.
This answer - like the question - relates C++ features to the Comp. Sci. terminology.
Discussion
With the C++ Standard using a narrower definition of "polymorphism" than the Comp. Sci. community, to ensure mutual understanding for your audience consider...
using unambiguous terminology ("can we make this code reusable for other types?" or "can we use virtual dispatch?" rather than "can we make this code polymorphic?"), and/or
clearly defining your terminology.
Still, what's crucial to being a great C++ programmer is understanding what polymorphism's really doing for you...
letting you write "algorithmic" code once and then apply it to many types of data
...and then be very aware of how different polymorphic mechanisms match your actual needs.
Run-time polymorphism suits:
input processed by factory methods and spat out as an heterogeneous object collection handled via Base*s,
implementation chosen at runtime based on config files, command line switches, UI settings etc.,
implementation varied at runtime, such as for a state machine pattern.
When there's not a clear driver for run-time polymorphism, compile-time options are often preferable. Consider:
the compile-what's-called aspect of templated classes is preferable to fat interfaces failing at runtime
optimisations (many including inlining and dead code elimination, loop unrolling, static stack-based arrays vs heap)
__FILE__, __LINE__, string literal concatenation and other unique capabilities of macros (which remain evil ;-))
templates and macros test semantic usage is supported, but don't artificially restrict how that support is provided (as virtual dispatch tends to by requiring exactly matching member function overrides)
Other mechanisms supporting polymorphism
As promised, for completeness several peripheral topics are covered:
compiler-provided overloads
conversions
casts/coercion
This answer concludes with a discussion of how the above combine to empower and simplify polymorphic code - especially parametric polymorphism (templates and macros).
Mechanisms for mapping to type-specific operations
> Implicit compiler-provided overloads
Conceptually, the compiler overloads many operators for builtin types. It's not conceptually different from user-specified overloading, but is listed as it's easily overlooked. For example, you can add to ints and doubles using the same notation x += 2 and the compiler produces:
type-specific CPU instructions
a result of the same type.
Overloading then seamlessly extends to user-defined types:
std::string x; int y = 0;
x += 'c'; y += 'c';
Compiler-provided overloads for basic types is common in high-level (3GL+) computer languages, and explicit discussion of polymorphism generally implies something more. (2GLs - assembly languages - often require the programmer to explicitly use different mnemonics for different types.)
> Standard conversions
The C++ Standard's fourth section describes Standard conversions.
The first point summarises nicely (from an old draft - hopefully still substantially correct):
-1- Standard conversions are implicit conversions defined for built-in types. Clause conv enumerates the full set of such conversions. A standard conversion sequence is a sequence of standard conversions in the following order:
Zero or one conversion from the following set: lvalue-to-rvalue conversion, array-to-pointer conversion, and function-to-pointer conversion.
Zero or one conversion from the following set: integral promotions, floating point promotion, integral conversions, floating point conversions, floating-integral conversions, pointer conversions, pointer to member conversions, and boolean conversions.
Zero or one qualification conversion.
[Note: a standard conversion sequence can be empty, i.e., it can consist of no conversions. ] A standard conversion sequence will be applied to an expression if necessary to convert it to a required destination type.
These conversions allow code such as:
double a(double x) { return x + 2; }
a(3.14); a(42);
Applying the earlier test:
To be polymorphic, [a()] must be able to operate with values of at least two distinct types (e.g. int and double), finding and executing type-appropriate code.
a() itself runs code specifically for double and is therefore not polymorphic.
But, in the second call to a() the compiler knows to generate type-appropriate code for a "floating point promotion" (Standard §4) to convert 42 to 42.0. That extra code is in the calling function. We'll discuss the significance of this in the conclusion.
> Coercion, casts, implicit constructors
These mechanisms allow user-defined classes to specify behaviours akin to builtin types' Standard conversions. Let's have a look:
int a, b;
if (std::cin >> a >> b) f(a, b);
Here, the object std::cin is evaluated in a boolean context, with the help of a conversion operator. This can be conceptually grouped with "integral promotions" et al from the Standard conversions in the topic above.
Implicit constructors effectively do the same thing, but are controlled by the cast-to type:
Implications of compiler-provided overloads, conversions and coercion
Consider:
void f() { typedef int Amount; Amount x = 13;
x /= 2; std::cout << x * 1.1; }
If we want the amount x to be treated as a real number during the division (i.e. be 6.5 rather than rounded down to 6), we only need change to typedef double Amount.
That's nice, but it wouldn't have been too much work to make the code explicitly "type correct":
void f() void f()
{ { typedef int Amount; typedef double Amount; Amount x = 13; Amount x = 13.0; x /= 2; x /= 2.0; std::cout << double(x) * 1.1; std::cout << x * 1.1; } }
But, consider that we can transform the first version into a template:
template void f() { Amount x = 13; x /= 2; std::cout << x * 1.1; }
It's due to those little "convenience features" that it can be so easily instantiated for either int or double and work as intended. Without these features, we'd need explicit casts, type traits and/or policy classes, some verbose, error-prone mess like:
template void f() { Amount x = Policy::thirteen; x /= static_cast(2); std::cout << traits::to_double(x) * 1.1; }
So, compiler-provided operator overloading for builtin types, Standard conversions, casting / coercion / implicit constructors - they all contribute subtle support for polymorphism. From the definition at the top of this answer, they address "finding and executing type-appropriate code" by mapping:
"away" from parameter types
from the many data types polymorphic algorithmic code handles
to code written for a (potentially lesser) number of (the same or other) types.
"to" parametric types from values of constant type
They do not establish polymorphic contexts by themselves, but do help empower/simplify code inside such contexts.
You may feel cheated... it doesn't seem like much. The significance is that in parametric polymorphic contexts (i.e. inside templates or macros), we're trying to support an arbitrarily large range of types but often want to express operations on them in terms of other functions, literals and operations that were designed for a small set of types. It reduces the need to create near-identical functions or data on a per-type basis when the operation/value is logically the same. These features cooperate to add an attitude of "best effort", doing what's intuitively expected by using the limited available functions and data and only stopping with an error when there's real ambiguity.
This helps limit the need for polymorphic code supporting polymorphic code, drawing a tighter net around the use of polymorphism so localised use doesn't force widespread use, and making the benefits of polymorphism available as needed without imposing the costs of having to expose implementation at compile time, have multiple copies of the same logical function in the object code to support the used types, and in doing virtual dispatch as opposed to inlining or at least compile-time resolved calls. As is typical in C++, the programmer is given a lot of freedom to control the boundaries within which polymorphism is used.
How can I center horizontally and vertically a text? I don't want to use position absolute because I try with it and my other div getting worse. Is there another way to do that ?
div {
height: 400px; width: 800px; background: red; }
This is title
Answer
you can use display flex it enables a flex context for all its direct children, and with flex direction establishes the main-axis, thus defining the direction flex items are placed in the flex container
There's this one thing in C++ which has been making me feel uncomfortable for quite a long time, because I honestly don't know how to do it, even though it sounds simple:
Goal: to make it possible to allow the client to instantiate some object using factory methods instead of the object's constructors, without unacceptable consequences and a performance hit.
By "Factory method pattern", I mean both static factory methods inside an object or methods defined in another class, or global functions. Just generally "the concept of redirecting the normal way of instantiation of class X to anywhere else than the constructor".
Let me skim through some possible answers which I have thought of.
0) Don't make factories, make constructors.
This sounds nice (and indeed often the best solution), but is not a general remedy. First of all, there are cases when object construction is a task complex enough to justify its extraction to another class. But even putting that fact aside, even for simple objects using just constructors often won't do.
The simplest example I know is a 2-D Vector class. So simple, yet tricky. I want to be able to construct it both from both Cartesian and polar coordinates. Obviously, I cannot do:
struct Vec2 { Vec2(float x, float y);
Vec2(float angle, float magnitude); // not a valid overload! // ... };
Which, instead of constructors, leads me to usage of static factory methods... which essentially means that I'm implementing the factory pattern, in some way ("the class becomes its own factory"). This looks nice (and would suit this particular case), but fails in some cases, which I'm going to describe in point 2. Do read on.
another case: trying to overload by two opaque typedefs of some API (such as GUIDs of unrelated domains, or a GUID and a bitfield), types semantically totally different (so - in theory - valid overloads) but which actually turn out to be the same thing - like unsigned ints or void pointers.
1) The Java Way
Java has it simple, as we only have dynamic-allocated objects. Making a factory is as trivial as:
class FooFactory { public Foo createFooInSomeWay() { // can be a static method as well, // if we don't need the factory to provide its own object semantics // and just serve as a group of methods return new Foo(some, args);
} }
In C++, this translates to:
class FooFactory { public: Foo* createFooInSomeWay() { return new Foo(some, args);
} };
Cool? Often, indeed. But then- this forces the user to only use dynamic allocation. Static allocation is what makes C++ complex, but is also what often makes it powerful. Also, I believe that there exist some targets (keyword: embedded) which don't allow for dynamic allocation. And that doesn't imply that the users of those platforms like to write clean OOP.
Anyway, philosophy aside: In the general case, I don't want to force the users of the factory to be restrained to dynamic allocation.
2) Return-by-value
OK, so we know that 1) is cool when we want dynamic allocation. Why won't we add static allocation on top of that?
class FooFactory { public: Foo* createFooInSomeWay() { return new Foo(some, args); } Foo createFooInSomeWay() {
return Foo(some, args); } };
What? We can't overload by the return type? Oh, of course we can't. So let's change the method names to reflect that. And yes, I've written the invalid code example above just to stress how much I dislike the need to change the method name, for example because we cannot implement a language-agnostic factory design properly now, since we have to change names - and every user of this code will need to remember that difference of the implementation from the specification.
class FooFactory { public: Foo* createDynamicFooInSomeWay() {
OK... there we have it. It's ugly, as we need to change the method name. It's imperfect, since we need to write the same code twice. But once done, it works. Right?
Well, usually. But sometimes it does not. When creating Foo, we actually depend on the compiler to do the return value optimisation for us, because the C++ standard is benevolent enough for the compiler vendors not to specify when will the object created in-place and when will it be copied when returning a temporary object by value in C++. So if Foo is expensive to copy, this approach is risky.
And what if Foo is not copiable at all? Well, doh. (Note that in C++17 with guaranteed copy elision, not-being-copiable is no problem anymore for the code above)
Conclusion: Making a factory by returning an object is indeed a solution for some cases (such as the 2-D vector previously mentioned), but still not a general replacement for constructors.
3) Two-phase construction
Another thing that someone would probably come up with is separating the issue of object allocation and its initialisation. This usually results in code like this:
class Foo { public: Foo() { // empty or almost empty } // ... };
class FooFactory { public: void createFooInSomeWay(Foo& foo, some, args); };
One may think it works like a charm. The only price we pay for in our code...
Since I've written all of this and left this as the last, I must dislike it too. :) Why?
First of all... I sincerely dislike the concept of two-phase construction and I feel guilty when I use it. If I design my objects with the assertion that "if it exists, it is in valid state", I feel that my code is safer and less error-prone. I like it that way.
Having to drop that convention AND changing the design of my object just for the purpose of making factory of it is.. well, unwieldy.
I know that the above won't convince many people, so let's me give some more solid arguments. Using two-phase construction, you cannot:
initialise const or reference member variables,
pass arguments to base class constructors and member object constructors.
And probably there could be some more drawbacks which I can't think of right now, and I don't even feel particularly obliged to since the above bullet points convince me already.
So: not even close to a good general solution for implementing a factory.
Conclusions:
We want to have a way of object instantiation which would:
allow for uniform instantiation regardless of allocation,
give different, meaningful names to construction methods (thus not relying on by-argument overloading),
not introduce a significant performance hit and, preferably, a significant code bloat hit, especially at client side,
be general, as in: possible to be introduced for any class.
I believe I have proven that the ways I have mentioned don't fulfil those requirements.
Any hints? Please provide me with a solution, I don't want to think that this language won't allow me to properly implement such a trivial concept.
Answer
First of all, there are cases when object construction is a task complex enough to justify its extraction to another class.
I believe this point is incorrect. The complexity doesn't really matter. The relevance is what does. If an object can be constructed in one step (not like in the builder pattern), the constructor is the right place to do it. If you really need another class to perform the job, then it should be a helper class that is used from the constructor anyway.
Vec2(float x, float y); Vec2(float angle, float magnitude); // not a valid overload!
The only disadvantage is that it looks a bit verbose:
Vec2 v2(Vec2::Cartesian(3.0f, 4.0f));
But the good thing is that you can immediately see what coordinate type you're using, and at the same time you don't have to worry about copying. If you want copying, and it's expensive (as proven by profiling, of course), you may wish to use something like Qt's shared classes to avoid copying overhead.
As for the allocation type, the main reason to use the factory pattern is usually polymorphism. Constructors can't be virtual, and even if they could, it wouldn't make much sense. When using static or stack allocation, you can't create objects in a polymorphic way because the compiler needs to know the exact size. So it works only with pointers and references. And returning a reference from a factory doesn't work too, because while an object technically can be deleted by reference, it could be rather confusing and bug-prone, see Is the practice of returning a C++ reference variable, evil? for example. So pointers are the only thing that's left, and that includes smart pointers too. In other words, factories are most useful when used with dynamic allocation, so you can do things like this:
class Abstract { public: virtual void do() = 0;
};
class Factory { public: Abstract *create(); };
Factory f; Abstract *a = f.create(); a->do();
In other cases, factories just help to solve minor problems like those with overloads you have mentioned. It would be nice if it was possible to use them in a uniform way, but it doesn't hurt much that it is probably impossible.
I'm new to Javascript and I'm trying to create a function that rotates the array depending on how many times num is === to. So if num = 2["Harry", "Sarah", "Oscar", "Tina"] becomes ["Oscar", "Tina", "Harry", "Sarah"]
Here is my code so far:
var count = 0;
function rotate(arr, num) { while (count < num) { arr.splice(0,0, "Tina"); arr.pop(); count++ } return arr }
For this Line - arr.splice(0,0, "Tina"); I want it to be so that it will bring whatever name is the fourth element to the front of the array, I'm not sure if this is possible? I am suppposed to do this method using splice. Thanks for any help?! :)
Edit: This question is different to other questions. I don't want a full blown solution for rotation, I just want to know if it's possible to splice the fourth element to the beginning?
Answer
Try shifting the array in a for loop:
function rotate(arr, num){ for(var i = 0; i < num; i++){ item = arr[arr.length-1] arr.splice(arr.length-1, 1); arr.unshift(item) } return arr }
I feel a little silly for asking this since I seem to be the only person in the world who doesn't get it, but here goes anyway. I'm going to use Python as an example. When I use raw SQL queries (I usually use ORMs) I use parameterisation, like this example using SQLite:
Method A:
username = "wayne" query_params = (username) cursor.execute("SELECT * FROM mytable WHERE user=?", query_params)
I know this works and I know this is the generally recommended way to do it. A SQL injection-vulnerable way to do the same thing would be something like this:
Method B:
username = "wayne"
cursor.execute("SELECT * FROM mytable WHERE user='%s'" % username)
As far I can tell I understand SQL injection, as explained in this Wikipedia article. My question is simply: How is method A really different to method B? Why is the end result of method A not the same as method B? I assume that the cursor.execute() method (part of Python's DB-API specification) takes care of correctly escaping and type-checking the input, but this is never explicitly stated anywhere. Is that all that parameterisation in this context is? To me, when we say "parameterisation", all that means is "string substitution", like %-formatting. Is that incorrect?
Answer
A parameterized query doesn't actually do string replacement. If you use string substitution, then the SQL engine actually sees a query that looks like
SELECT * FROM mytable WHERE user='wayne'
If you use a ? parameter, then the SQL engine sees a query that looks like
SELECT * FROM mytable WHERE user=
Which means that before it even sees the string "wayne", it can fully parse the query and understand, generally, what the query does. It sticks "wayne" into its own representation of the query, not the SQL string that describes the query. Thus, SQL injection is impossible, since we've already passed the SQL stage of the process.
(The above is generalized, but it more or less conveys the idea.)
Eclipse issues warnings when a serialVersionUID is missing.
The serializable class Foo does not declare a static final serialVersionUID field of type long
What is serialVersionUID and why is it important? Please show an example where missing serialVersionUID will cause a problem.
Answer
The docs for java.io.Serializable are probably about as good an explanation as you'll get:
The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named serialVersionUID that must be static, final, and of type long:
ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class serialVersionUID fields are not useful as inherited members.
I am just learning PHP and I keep getting an Undefined Index error. The book I'm learning from has an HTML form and a PHP page that processes the form, using the following format:
// The PHP starts with one line like this for each of the form fields in the HTML $how_long = $_POST ['howlong'];
// And there is one line for each one like this to output the form data: echo ' and were gone for ' . $how_long . ' ';
The example I'm working with has about 12 form fields.
What's odd is that not all of the variables throw this error, but I can't see a pattern to it.
I've checked that all HTML fieldnames match up with the PHP $_POST variable name I entered, and I've made certain that when I fill out the form and submit it that all fields are filled in with something. Interestingly, the completed code that can be downloaded for the book also throws this error.
I realize this code may not reflect best practices, it's from the first chapter of the book and obviously I am a noob :)
In case it makes a difference, I am using PHP 5.3.5 on XAMPP 1.7.4 with Windows 7 Home Premium.
Answer
Remember to set the method to POST on the form tag...
heres the code i used to try yours, and it worked to me:
in a file named test.php:
and in testProc.php:
if (isset($_POST)) { if (isset($_POST["howlong"])){ $howlong = $_POST['howlong']; echo ' and were gone for ' . $howlong . ' ';
} } ?>
Just as an advise, to make display manipulation with stylesheets i recommend to put forms within a table, like this:
Its a context issue, your mistake is that you didn't bind all the way down to the anonymous function. What you probably want to do is use arrow functions, try this:
I came across some Java code that had the following structure:
public MyParameterizedFunction(String param1, int param2) {
this(param1, param2, false); }
public MyParameterizedFunction(String param1, int param2, boolean param3) { //use all three parameters here }
I know that in C++ I can assign a parameter a default value. For example:
void MyParameterizedFunction(String param1, int param2, bool param3=false);
Does Java support this kind of syntax? Are there any reasons why this two step syntax is preferable?
Answer
No, the structure you found is how Java handles it (that is, with overloading instead of default parameters).
For constructors, See Effective Java: Programming Language Guide's Item 1 tip (Consider static factory methods instead of constructors) if the overloading is getting complicated. For other methods, renaming some cases or using a parameter object can help. This is when you have enough complexity that differentiating is difficult. A definite case is where you have to differentiate using the order of parameters, not just number and type.
I am writing a simple reverse proxy in java. So, I have access to all Http requests and responses exchanged between client and server. Sitting at the proxy I am trying to detect SQL Injection Attack.
where some regex are mentioned, but I suppose it's not that simple. It is impossible to write regex for all possible/valid SQL statements. Because so many databases are there in the market and SQL statements must follow some grammer rules.
Let me break down the problem to a simple question -
Given a string, can it be checked that whether it contains a valid SQL statement?
Can anyone tell me the best way to do it? Or, any library which does that for me?