Sunday, March 31, 2019

regex - In Java Regular Expression "1" (back reference) is not working



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");

android - java.io.IOException: Received authentication challenge is null

I need get a response code, but it's throw a IOException. I don't know what's the matter!




    try
{
url = new URL(urlBuilder.toString());
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setConnectTimeout(TIME_OUT);
conn.setRequestMethod(METHOD_GET);
conn.setRequestProperty("accept", "*/*");
conn.connect();
int responseCode = conn.getResponseCode(); //throw IOException:Received authentication challenge is null

if (responseCode == HTTP_OK)
{
inStream = conn.getInputStream();
response = getResponse(inStream);
}
else
{
response = "response code:"+responseCode;
}
} catch (Exception e)

{
throw e;
}
finally
{
conn.disconnect();
}
return response;
}



the IOException is :



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)

javascript - Add tags to the text outside of bbcode tags



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 {

outstr += '[text]' + m[4] + '[/text]' + m[5];
}
}
console.log(outstr);





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.



Demo on regex101



Regex explained:



  # 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
)

dom - php DomDocument: how can i print an attribute of an element?



how do I print the an attribute of an element?



example:




$doc = new DOMDocument();
@$doc->loadHTML($page);
$xpath = new DOMXPath($doc);
$arts= $xpath->query("/td");

foreach ($arts as $art) {
here i wanna print the attribute class of the td element, how do i do so ?
}

Answer




use DOMElement::getAttribute



$art->getAttribute('class');


also, simpleHTMLDOM is more suitable for dealing with html:



$html = str_get_html($page);
foreach($html->find('td') as $element)
echo $element->class.'
';

}

android - How to differentiate between long key press and regular key press?

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)

return true;
}
return super.onKeyLongPress(keyCode, event);
}


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?

memory management - How can I demonstrate a zombie object in Swift?



I've read How to demonstrate memory leak and zombie objects in Xcode Instruments? but that's for objective-c. The steps don't apply.



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.


javascript - Adding Keypress/keydown event on dynamic html

I have the following dynamic input html in my project




  $(this).html("");


Now i was trying to add validation for using only numeric in above input text field.



But being new to jquery i was wondering how do i add keypress event to it



Want to use following validation to it



function isNumber(evt) {

evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}


I tried follwoing but does not seem to work




$(this).html("");


EDIT



Any other way to add validation for using only number

Is JavaScript a pass-by-reference or pass-by-value language?

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?

'the-shawshank-redemption' tag wiki - Movies & TV



Prison movie of the 90s based on the writings of Stephen King, written and directed by Frank Darabont, generally resides as the top #1 movie on IMDB.







There is no tag wiki for this tag … yet!



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




All registered users may propose new tag wikis.



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


php - Shorthand for arrays: is there a literal syntax like {} or []?



What is the shorthand for array notation in PHP?




I tried to use (doesn't work):



$list = {};


It will be perfect, if you give links on some information about other shorthands for PHP.


Answer



Update:
As of PHP 5.4.0 a shortened syntax for declaring arrays has been introduced:



$list = [];






Previous Answer:



There isn't. Only $list = array(); But you can just start adding elements.



$list[] = 1;

$list['myKey'] = 2;
$list[42] = 3;


It's perfectly OK as far as PHP is concerned. You won't even get a E_NOTICE for undefined variables.




E_NOTICE level error is issued in case
of working with uninitialized
variables, however not in the case of

appending elements to the
uninitialized array.




As for shorthand methods, there are lots scattered all over. If you want to find them just read The Manual.



Some examples, just for your amusement:




  1. $arr[] shorthand for array_push.


  2. The foreach construct

  3. echo $string1, $string2, $string3;

  4. Array concatenation with +

  5. The existence of elseif

  6. Variable embedding in strings, $name = 'Jack'; echo "Hello $name";


C++ chaining of the operator










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:



#include 
class Logger
{
public:

std::ostream &m_file;
Logger(std::ostream &o = std::cout):m_file(o){};

template
Logger &operator<<(const T &a) {
m_file< return *this;
}
};


int main()
{
Logger log;
log< >;
log<<"hi"<<" stackoverflow"< >;
return 0;
}


Or you can add a new overload of operator<< in class Logger to let compiler deduce the template parameters of std::endl:




#include 
class Logger
{
public:
std::ostream &m_file;
Logger(std::ostream &o = std::cout):m_file(o){};

template
Logger &operator<<(const T &a) {

m_file< return *this;
}

Logger &operator<<(std::ostream& (*pf) (std::ostream&)){
m_file< return *this;
}
};


int main()
{
Logger log;
log< log<<"hi"<<" stackoverflow"< return 0;
}


Also, if you don't need the output to be flushed immediately, you can use '\n' instead of endl.



Create new column based on existing columns in R Shiny

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 code for this Shiny app is below:



     library(shiny)
library(shinydashboard)
library(dplyr)

library(tidyr)
library(ggplot2)
library(ggrepel)
library(scales)
library(lubridate)
library(knitr)
library(foreign)
library(DT)
library(caret)
library(car)

library(data.table)
library(digest)
library(jsonlite)
library(httr)
library(reshape2)
library(zoo)
library(sqldf)
library(boot)
library(openxlsx)
library(readxl)


options(shiny.maxRequestSize = 30000*1024^2)
options(scipen = 999)

### Define app




    ui <- dashboardPage(


dashboardHeader(title = "My app"),

dashboardSidebar(

sidebarMenu(

menuItem("Upload Data", tabName = "data_upload", icon = icon("folder-
open"))


)

),

dashboardBody(

tags$head(tags$style(HTML('.main-header .logo {

font-family: "Bliss Pro Light", Times, "Times New Roman", serif;


font-weight: bold;

font-size: 30px;

}

'))),

tabItems(


tabItem(tabName = "data_upload",

fluidRow(

box(title = "Modelling data", status = "primary",

fileInput(inputId = "main_data", label = "Upload the data for modelling", accept = c('.csv', 'text/comma-separated-values,text/plain', 'text/csv', 'csv')),

checkboxInput(inputId = "header", label = "The data has headers", value = TRUE),


radioButtons(inputId = "sep", label = "Delimiter:", choices = c("Comma" = ",","Semicolon" = ";","Tab" = "\t"), selected = ";")

)
),
fluidRow(

box(title = "Divide modelling data into estimation & validation sample", status = "primary", width = 12,

selectizeInput(inputId = "time_var", label = "Select the time variable", choices = "", multiple = FALSE),


#frequency of the data

tags$b("Choose the frequency of your data"),

radioButtons(inputId = "frequency", label = "", choices = c("Monthly", "Quarterly"), selected = "Quarterly"),

#time format based on frequency - choices

tags$b("Select the time series variable format"),


conditionalPanel(condition = "input.frequency == 'Monthly'",

radioButtons(inputId = "format_monthly", label = "",

choices = c("month Year, e.g. Jan 2014 or January 2014" = "format_1", "month/day/Year, e.g. 2/26/2019" = "format_2"),

selected = "format_1")

),


conditionalPanel(condition = "input.frequency == 'Quarterly'",

radioButtons(inputId = "format_quarterly", label = "",

choices = c("Year quarter, e.g. 2014q3 or 2014Q3" = "format_3", "month/day/Year, e.g. 2/26/2019" = "format_4"),

selected = "format_3")

),


selectizeInput(inputId = "time_threshold", label = "Select time threshold for estimation and validation", choices = "", multiple = FALSE),

h6("Data before this threshold will be used for estimation, data after this threshold will be used for validation.")

)
)
)
)
)
)





server <- function(input, output, session) {

model_data <- reactive({

infile <- input$main_data




if (is.null(infile))

return(NULL)

read.csv(infile$datapath, header = input$header, sep = input$sep, stringsAsFactors = FALSE)

})


# update time_var choices
observe({

vchoices <- names(model_data())

updateSelectizeInput(session = session, inputId = "time_var", choices = vchoices)

})

observeEvent(input$frequency, {


if (input$frequency == "Monthly") {

if (input$format_monthly == "format_1") {
model_data()[, "time_var_use"] <- as.yearmon(model_data()[, input$time_var])
}

else if (input$format_monthly == "format_2") {
model_data()[, "time_var_use"] <- as.yearmon(as.Date(model_data()[, input$time_var], "%m/%d/%Y"))
}


}

if (input$frequency == "Quarterly") {

if (input$format_quarterly == "format_3") {
model_data()[, "time_var_use"] <- as.yearqtr(model_data()[, input$time_var])
}

else if (input$format_quarterly == "format_4") {

model_data()[, "time_var_use"] <- as.yearqtr(as.Date(model_data()[, input$time_var], "%m/%d/%Y"))
}

}

updateSelectizeInput(session, inputId = "time_threshold",

choices = as.character(unique(model_data()[, "time_var_use"])),

server = TRUE)


})


}




shinyApp(ui, server)



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:



     time var1 var2      var3
2015q1 8 1 0.6355182
2015q1 12 0 0.5498784
2015q1 23 1 0.9130934

2015q1 152 1 0.8938210
2015q2 563 1 0.2335470
2015q3 8 0 0.5802677
2015q4 2 0 0.8514926
2016q1 1 1 0.4712101
2016q1 14 0 0.9747804
2016q2 13 1 0.8571699
2016q2 14 1 0.8738486
2016q3 53 0 0.8467971
2016q4 75 0 0.3191140

2016q4 15 0 0.9608926


Based on the time column, my aim is to create time_var_use column within the app and then use its values for another input.

curl - Fetch data from other site (php & GET)

Answer


Answer




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.


java - 2 "for" loops twice faster than 1 loop

Answer



I noticed that the below code




    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?



Thanks for your much needed help on this one.

c++ - SSE optimisation for a loop that finds zeros in an array and toggles a flag + updates another array

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


How should I go about this using SSE intrinsics?

c++ - Double free or corruption after queue::push




#include 
using namespace std;

class Test{
int *myArray;

public:
Test(){
myArray = new int[10];
}


~Test(){
delete[] myArray;
}

};


int main(){
queue q

Test t;
q.push(t);
}


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:




Test(const Test& other){
myArray = new int[10];
memcpy( myArray, other.myArray, 10 );
}


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:




Test& operator= (const Test& other){
if (this != &other) {
memcpy( myArray, other.myArray, 10 );
}
return *this;
}


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.



c - Why do we cast return value of malloc?




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



As wiki says:




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








1. Emphases are mine.


Saturday, March 30, 2019

Updated text fields to JSON string - Javascript/JQuery

I have a dynamic form that has text fields which change to input boxes when they need to be updated.



When they have been updated and the user clicks submit I want to add the updated values to a json string which i can post to an ASP.NET script.



Here is the html of 2 rows in the table:




Colleague 1:














Del






Colleague 2:














Del





Here is the jQuery I'm using to detect which input boxes have been updated:



$("#subdetails").click(function () {
$("#mantab input[type=text]").each(function () {
if ($(this).val() !== this.defaultValue) {

//code to create json string

}
});
});


This is an example of a json string i would like to create if the following field were updated:



{
"1":{
"c1nametb": "newname",
"c1exttb": "22227",
}
"2":{
"c2eaddtb": "neweadd@company.co.uk",
"c2pnotb": "0111122210",
}
}


Can any one please help me with the code to create this string, or advise on a better way of doing this?



Thanks
Ryan

Polymorphism in C++



AFAIK:



C++ provides three different types of polymorphism.





  • Virtual functions

  • Function name overloading

  • Operator overloading



In addition to the above three types of polymorphism, there exist other kinds of polymorphism:




  • run-time


  • compile-time

  • ad-hoc polymorphism

  • parametric polymorphism



I know that runtime polymorphism can be achieved by virtual functions
and static polymorphism can be achieved by template functions



But for the other two






ad-hoc polymorphism:



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_;

    };

    struct Y : Base
    {
    Y(double n) : n_(n) { }
    Y& operator+=(int n) { n_ += n; return *this; }
    double n_;
    };

    void f(Base& x) { x += 2; } // run-time polymorphic dispatch




Other related mechanisms



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 expects1 is 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.".



        template 
        void do_ducky_stuff(const Duck& x) { x.walk().swim().quack(); }

        do_ducky_stuff(Vilified_Cygnet());



    • 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

  • SFINAE

  • CRTP

  • 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:



f(const std::string& x);
f("hello"); // invokes `std::string::string(const char*)`



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.


html - center h1 in the middle of screen





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



div{
height: 400px;
width: 800px;
background: red;
display: flex;
flex-direction: column;

justify-content: center;
text-align: center;
}

How to implement the factory method pattern in C++ correctly




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!
// ...
};


My natural way of thinking is then:



struct Vec2 {
static Vec2 fromLinear(float x, float y);
static Vec2 fromPolar(float angle, float magnitude);

// ...
};


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() {

return new Foo(some, args);
}
Foo createFooObjectInSomeWay() {
return Foo(some, args);
}
};


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);
};

void clientCode() {
Foo staticFoo;
auto_ptr dynamicFoo = new Foo();
FooFactory factory;
factory.createFooInSomeWay(&staticFoo);

factory.createFooInSomeWay(&dynamicFoo.get());
// ...
}


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!


There is an easy workaround for this:



struct Cartesian {
inline Cartesian(float x, float y): x(x), y(y) {}
float x, y;
};

struct Polar {
inline Polar(float angle, float magnitude): angle(angle), magnitude(magnitude) {}
float angle, magnitude;
};
Vec2(const Cartesian &cartesian);
Vec2(const Polar &polar);


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.


javascript - How to splice an element to the start of an array?




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
}

console.log(rotate(["Harry", "Sarah", "Oscar", "Tina"], 2));



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
}

alert(JSON.stringify(rotate(["Harry", "Sarah", "Oscar", "Tina"], 2)));

alert(JSON.stringify(rotate(["Harry", "Sarah", "Oscar", "Tina"], 1)));




security - How does SQL query parameterisation work?



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


java - What is a serialVersionUID and why should I use it?



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.



xampp - Undefined Index for $_POST (noob question!)






Possible Duplicate:
PHP: “Notice: Undefined variable” and “Notice: Undefined index”






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:





























Hope you can use this...


reactjs - TypeError: cannot read property setState of undefined



I am receiving the data from server but not able to display it on the browser. I am receiving error as:





caught (in promise) TypeError: Cannot read property 'setState' of undefined




import React from 'react';

import axios from 'axios';
class App extends React.Component {
constructor(props){
super(props);
this.state={

posts:'hello',
dos:[]
}

};


componentDidMount() {
axios.get(`http://192.168.1.9:8082`)
.then(function(data) {

console.log(data);
this.setState({dos:data});
});
}

render() {
return (

Hello World!!!

{this.state.posts}



{this.state.dos}



);
}
}

export default App;

Answer



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:




componentDidMount() {
axios.get(`http://192.168.1.9:8082`)
.then(data => this.setState({dos:data}););
}


Arrow functions always keep the context of this.



Alternate solution:




componentDidMount() {
axios.get(`http://192.168.1.9:8082`)
.then(function(data) {
console.log(data);
this.setState({dos:data});
}).bind(this);
}

methods - Does Java support default parameter values?



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.


What is the difference between implicit and explicit String declaration in java?

For Example..





String herName = new String("clark");



and



String hisName = "michal";



1) The first piece of code exactly does, it will create new string
object in the heap memory with reference .




2) The second line of code , its an string literal which create
string object in string constant pool, not in actually heap memory.




Then what's the benefit, ?

security - How to detect SQL Injection sitting at a reverse proxy?

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.



I got few links - (like for example)




http://www.symantec.com/connect/articles/detection-sql-injection-and-cross-site-scripting-attacks



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?

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

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