Sunday 31 December 2017

r - How can two strings be concatenated?

How can I concatenate (merge, combine) two
values?
For example I
have:




tmp =
cbind("GAD", "AB")
tmp
# [,1] [,2]
# [1,] "GAD"
"AB"


My goal is to
concatenate the two values in "tmp" to one string:



tmp_new =
"GAD,AB"



Which
function can do this for me?

c - What is the difference between a definition and a declaration?

itemprop="text">

The meaning of both eludes
me.



itemprop="text">
class="normal">Answer



A
declaration introduces an identifier
and describes its type, be it a type, object, or function. A declaration is
what the compiler needs to accept
references to that identifier. These are declarations:



extern int bar;
extern
int g(int, int);
double f(int, double); // extern can be omitted for function
declarations
class foo; // no extern allowed for type
declarations


A
definition actually
instantiates/implements this identifier. It's what the linker
needs
in order to link references to those entities. These are
definitions corresponding to the above declarations:




int bar;
int
g(int lhs, int rhs) {return lhs*rhs;}
double f(int i, double d) {return
i+d;}
class foo
{};


A definition can
be used in the place of a declaration.



An
identifier can be declared as often as you want. Thus, the
following is legal in C and C++:




double f(int,
double);
double f(int, double);
extern double f(int, double); // the
same as the two above
extern double f(int,
double);


However, it
must be defined exactly once. If you forget to define something
that's been declared and referenced somewhere, then the linker doesn't know what to link
references to and complains about a missing symbols. If you define something more than
once, then the linker doesn't know which of the definitions to link
references to and complains about duplicated symbols.



/>


Since the debate what is a class
declaration vs. a class definition in C++
keeps coming up (in answers and comments to other questions) , I'll paste a quote from
the C++ standard here.
At 3.1/2, C++03
says:




A
declaration is a definition unless it [...] is a class name declaration
[...].




3.1/3 then
gives a few examples. Amongst
them:





[Example:
[...]
struct S { int a; int b; }; // defines S, S::a, and S::b
[...]
struct S; // declares S
—end
example


To sum it up: The C++
standard considers struct x; to be a
declaration and struct x {}; a
definition. (In other words, "forward
declaration" a misnomer
, since there are no other forms of
class declarations in C++.)



Thanks to href="https://stackoverflow.com/users/34509/johannes-schaub-litb">litb (Johannes
Schaub) who dug out the actual chapter and verse in one of his answers.


c# - Does a web.config substitute app.config?

itemprop="text">

I wrote a dll project in c#. I added a
service reference. A app.config was automatically generated.
In the same
solution I have an asp.net project.



If I copy
paste the relevant configuration from the app.config to the web.config and change the
client url - will it override the service url in the
app.config?



The funny thing is that everything
works OK even without copying this section to the web.config. How
come?



TIA




Answer






The config schema is
the same for web and app.config. There are some sections that will only make sense for
web apps, but generally not the other way around. You should be just fine copy-pasting
your configuration.



The web project only looks
at Web.config, so you will need to copy the configuration to your
web.config.


How do I display an alert dialog on Android?

style="font-weight: bold;">

Answer



I want to display a dialog/popup window with a message
to the user that shows "Are you sure you want to delete this entry?" with one button
that says 'Delete'. When Delete is touched, it should delete
that entry, otherwise nothing.



I have written a
click listener for those buttons, but how do I invoke a dialog or popup and its
functionality?

java - Parsing from String to Date throws Unparsable Date Error

itemprop="text">

I have an variable called
data, and it has today's date as in this format:
Thu May 24 13:14:41 BRT 2018. Then I format it to MySQL's Date
type format, which is yyyy-MM-dd. This code does
it:




String
dataFormatada = new
SimpleDateFormat("yyyy-MM-dd").format(data);


What
I want to do is to bring it back to Date type. I've tried somethings but they didn't
work. The main solution is to do as discribed in this other href="https://stackoverflow.com/questions/4496359/how-to-parse-date-string-to-date">
questioin, and with a little mod I got to what's suposely what I
want:



String target = "Thu Sep 28
20:29:30 JST 2000";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd",
Locale.ENGLISH);
Date result = df.parse(target);

System.out.println(result);



But
it doesn't work as I get this error when trying to
parse:



java.text.ParseException:
Unparseable date: "Thu Sep 28 20:29:30 JST
2000"


So I cannot just
reformat the data variable, and I cannot bring
dataFormatada back to Date format. How do I bring
dataFormatada to Date type formatted as
yyyy-MM-dd?


itemprop="text">
class="normal">Answer



Your
target String format is in EEE MMM dd HH:mm:ss zzz yyyy format.
So you need to use EEE MMM dd HH:mm:ss zzz yyyy as pattern
instead of yyyy-MM-dd.




 String target = "Thu
Sep 28 20:29:30 JST 2000";
DateFormat df = new SimpleDateFormat("EEE MMM dd
HH:mm:ss zzz yyyy", Locale.ENGLISH);
Date result = df.parse(target);


System.out.println(result);


And
if you want convert Date object i.e result to yyyy-MM-dd then
please use the below code.




DateFormat dfDateToStr = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);

String formattedDate = dfDateToStr.format(result);


System.out.println("Formatted Date String :
"+formattedDate);


c - UNUSED macro warning

itemprop="text">

So I found this href="https://stackoverflow.com/questions/4851075/universally-compiler-independent-way-of-implementing-an-unused-macro-in-c-c/4851173#4851173">macro
on SO:




#define
UNUSED(x) (void)(sizeof((x),
0))


and this (still)
produces the following warning:




main.c:11:36:
warning: left-hand operand of comma expression has no effect [-Wunused-value]

#define UNUSED(x) (void)(sizeof((x),
0))





Whereas
the simpler version, a normal void cast: #define
UNUSED(x) (void)(x)
is
warning-free.



What could be the reason behind
it? In general warnings are a sign of high-risk situations. Is here the given warning
really useful?



I am interested in
C-explanation.


itemprop="text">
class="normal">Answer



This macro
seems inappropriate for your compiler at the current warning
level.



You could use this simpler
version:




#define
UNUSED(x)
(void)(sizeof(x))


x
will not be evaluated either but is used so the compiler should not
complain about x being unused, not about the left hand side of
the , operator being unused in the
expression.


kwargs reserved word in python. What does it mean?

I am using Python trying to figure out a key word and I
see the word, "kwargs", which I know is some kind of argument
in the called function but I can not find what it means or stands for anywhere.




For example, this entry in the
Python documents
says...



read_holding_registers(address,
count=1,
**kwargs)


Parameters:



address
– The starting address to read from
count – The number of registers to
read

unit – The slave unit this request is
targeting


It looks
like a reference to a pointer to pointer but that is all I
can
tell...



This does NOT even use
"**kwargs" in the parameters list It uses
what looks
to me like, "unit" instead of
"kwargs".



I can NOT
seem to find anywhere what kwargs
means.




Maybe it is "Key Word
arguments" ? What am I missing here ?



Any ideas
on help here ?
thank you !
boB

Movie where jury gets swapped just before a trial begins?




I was having a chat this morning about jury duty and I thought of a
scene from a film.


The set up is that whoever is being
tried in this case has the jury paid off, and the prosecutor or cops involved discover
this just as the trial is about to start.


They go talk to
the judge, and he comes back in looking all shaken and orders the bailiff to swap the
jury with a jury in another trial which is just about to
start.


When asked how they got him to do the swap the
prosecutor or cops say something like we showed him a list of names paid off, and the
his (the judge) was on the list.


Can someone tell me what
movie this is from?


itemprop="text">
class="normal">Answer


This is from href="http://www.imdb.com/title/tt0094226/">The Untouchables. Kevin Costner
(Eliot Ness) shows the list to the judge at the beginning of the trial of Al
Capone.


loops - Javascript Break Statement Goodness









Is
using labels to break loops, a good practice in javascript? Mention if it has any pros
and
cons



Ex:



var
i, j;
outer:
for(i in [0,1,2,3]) {


inner:
for(j in [0,1,2,3]) {
if(j == 1) {
break
outer;
}
}
console.log("inner")
}

console.log("outer");

CSS multiple selectors without comma

itemprop="text">

I am alittle confuse about CSS
Selectors, I understand that we can group multiple css selectors with a comma if they
share similar attributes, but what about multiple css selectors without commas e.g like
this:



.ui-datepicker-rtl {
direction: rtl; }
.ui-datepicker-rtl .ui-datepicker-prev { right: 2px; left:
auto; }
.ui-datepicker-rtl .ui-datepicker-next { left: 2px; right: auto;
}

itemprop="text">
class="normal">Answer



When you
use the comma,
like




#menu,
.item


you are saying:




all elements
whose id is menu AND all elements whose class is
item





When
you nest selectors without the comma, like



#menu
.item


you are saying




all elements that
has class item inside a container whose id is
menu





c# - Why is there huge performance hit in 2048x2048 versus 2047x2047 array multiplication?

itemprop="text">

I am making some matrix multiplication
benchmarking, as previously mentioned in
href="https://stackoverflow.com/questions/6058139/why-is-matlab-so-fast-in-matrix-multiplication">Why
is MATLAB so fast in matrix
multiplication?



Now I've got another
issue, when multiplying two 2048x2048 matrices, there is a big difference between C# and
others. When I try multiply only 2047x2047 matrices, it seems normal. Added some others
for comparsion too.




1024x1024 - 10
seconds.



1027x1027 - 10
seconds.



2047x2047 - 90
seconds.



2048x2048 - 300
seconds.



2049x2049 - 91 seconds.
(update)




2500x2500 - 166
seconds



That is three and a half minute
difference for the 2k by 2k case.



using 2dim
arrays



//Array init like
this
int rozmer = 2048;
float[,] matice = new float[rozmer,
rozmer];


//Main multiply code
for(int j = 0; j
< rozmer; j++)
{
for (int k = 0; k < rozmer; k++)

{
float temp = 0;
for (int m = 0; m < rozmer; m++)

{
temp = temp + matice1[j,m] * matice2[m,k];


}
matice3[j, k] = temp;
}

}

itemprop="text">
class="normal">Answer



This
probably has do with conflicts in your L2
cache.



Cache misses on matice1 are not the
problem because they are accessed sequentially.
However for matice2 if a full
column fits in L2 (i.e when you access matice2[0, 0], matice2[1, 0], matice2[2, 0] ...
etc, nothing gets evicted) than there is no problem with cache misses with matice2
either.




Now to go deeper in how
caches works, if byte address of your variable is X, than the cache line for it would be
(X >> 6) & (L - 1). Where L is total number of cache lines in your cache. L is
always power of 2.
The six comes from fact that 2^6 == 64 bytes is standard
size of cache line.



Now what does this mean?
Well it means that if I have address X and address Y and
(X >> 6) - (Y
>> 6) is divisible by L (i.e. some large power of 2), they will be stored in the
same cacheline.



Now to go back to your problem
what is the difference between 2048 and 2049,



when 2048 is your
size:




if you take &matice2[x, k]
and &matice2[y, k] the difference (&matice2[x, k] >> 6) -
(&matice2[y,k] >> 6) will be divisible by 2048 * 4 (size of float). So a large
power of 2.



Thus depending on size of your L2
you will have a lot of cache line conflicts, and only utilize small portion of your L2
to store a column, thus you wont actually be able to store full column in your cache,
thus you will get bad performance.



When size is
2049, then the difference is 2049 * 4 which is not power of 2 thus you will have less
conflicts and your column will safely fit into your
cache.



Now to test this theory there are couple
things you can do:



Allocate your array matice2
array like this matice2 [razmor, 4096], and run with razmor = 1024, 1025 or any size,
and you should see very bad performance compared to what you had before. This is because
you forcefully align all columns to conflict with each
other.




Then try matice2 [razmor,
4097] and run it with any size and you should see much better
performance.


python - Python3 - Generate string matching multiple regexes, without modifying them

itemprop="text">

I would like to generate string
matching my regexes using Python 3. For this I am using handy library called href="https://bitbucket.org/leapfrogdevelopment/rstr/" rel="nofollow
noreferrer">rstr.







  • ^[abc]+.

  • [a-z]+






I
must find a generic way, how to create string that would match both my
regexes.





Modify both
regexes or join them in any way. This I consider as ineffective solution, especially in
the case if incompatible
regexes:



import
re
import rstr

regex1 =
re.compile(r'^[abc]+.')

regex2 =
re.compile(r'[a-z]+')

for index in range(0, 1000):

generated_string = rstr.xeger(regex1)
if re.fullmatch(regex2,
generated_string):
break;
else:
raise Exception('Regexes
are probably incompatibile.')

print('String matching both regexes
is:
{}'.format(generated_string))



Is
there any workaround or any magical library that can handle this? Any insights
appreciated.







Asker
already has the string, which he just want to check against
multiple regexes in the most elegant way. In my case we need to
generate string in a smart way that would match
regexes.



Answer





I solved this using a little
alternative approach. Notice second regex is basically insurance so only lowercase
letters are generated in our new string.



I used
Google's python package sre_yield which allows charset limitation. Package is also
available on PyPi. My
code:



import
sre_yield
import string

sre_yield.AllStrings(r'^[abc]+.',
charset=string.ascii_lowercase)[0]
# returns
`aa`



javascript - In what situation we must use localstorage instead of the cookies?





I'm trying to develop a html5 mobile web application using the
sencha touch. I need to save client's data in browser storage for a long time. At first
i used a localstorage to save them. But my colleague recommended to use cookies instead
of the localstorage. I need to warn you that i don't use user's data in server-side and
size of data is small. What should i use localstorage or cookies in this
case?



Answer




I think in this situation local Storage would
do better,because




  1. Cookies
    are used by server side and you said ,you don't use users's data in server
    side.

  2. Your data size is small and you need to store it
    for long time,cookie has expiration date,but with local storage there is no such,either
    you have remove it programmatic-ally using java script or by clearing browser
    cache.



java - ArrayList.add throws ArrayIndexOutOfBoundsException

I am trying to add a object to a ArrayList and its
throwing ArrayIndexOutOfBoundsException
Following is the code



private void
populateInboxResultHolder(List inboxErrors){
inboxList = new
ArrayList();
try{
inboxHolder = new
InboxResultHolder();
//Lots of Code

inboxList.add(inboxHolder);

}catch(Exception e){

e.printStackTrace();

}
}


And the
exception is



[3/7/12 15:41:26:715
UTC] 00000045 SystemErr R java.lang.ArrayIndexOutOfBoundsException
[3/7/12
15:41:26:721 UTC] 00000045 SystemErr R at
java.util.ArrayList.add(ArrayList.java:378)

[3/7/12 15:41:26:721
UTC] 00000045 SystemErr R at
com.ml.fusion.ui.common.web.bean.inbox.InboxSearchBean.populateInboxResultHolder(InboxSearchBean.java:388)

[3/7/12 15:41:26:721 UTC] 00000045 SystemErr R at
com.ml.fusion.ui.common.web.bean.inbox.InboxSearchBean.searchInboxErrors(InboxSearchBean.java:197)
[3/7/12
15:41:26:721 UTC] 00000045 SystemErr R at
com.ml.fusion.ui.common.web.bean.inbox.InboxSearchBean.viewInbox(InboxSearchBean.java:207)


But
according to the signature of ArrayList.add it should not throw this
exception.
Please help.

html - jQuery click function doesn't work after ajax call?





The jQuery click function works fine
here



            id="LangTable">delete



$('.deletelanguage').click(function(){

alert("success");
});



but
if I set some by ajax,
$('.deletelanguage').click doesn't
work.



for
example



function CreateRow(jdata)
{
$('#LangTable').append(' class="deletelanguage">delete
');
}

$.ajax({


url: "/jobseeker/profile/",
success:
CreateRow
});


Now
the $('.deletelanguage').click for the last
is not
working.



jsfiddle example : href="http://jsfiddle.net/suhailvs/wjqjq/">http://jsfiddle.net/suhailvs/wjqjq/



Note:
the CSS works fine here.




I want to
make these newly appended working with jQuery
click.



Answer




The problem is that .click only works for
elements already on the page.
You have to use something like
on if you are wiring up future
elements



$("#LangTable").on("click",".deletelanguage",
function(){

alert("success");
});



Python : write text to file line by line

This is how to print to a txt
file:



file = open("Exported.txt",
"w")
file.write("Text to write to file")
file.close() #This close()
is
important



Another
way to do so would to be:



with
open('Exported.txt', 'w') as file:
file.write("Text to write to
file")


This is a
program I made to write a txt
file:



import
os.path


def start():

print("What
do you want to do?")
print(" Type a to write a file")
print(" Type
b to read a file")
choice = input(" -")
if choice ==
"a":
create()
elif choice == "b":

read()

else:
print("Incorrect spelling of a or
b\n\n")
start()


def
create():

print()
filename = input("What do you want
the file to be called?\n")
if os.path.isfile(filename):


print("This file already exists")
print("Are you sure you would like to
overwrite?")
overwrite = input("y or n")
if overwrite ==
"y":
print("File has been overwritten")
write(filename)

else:
print("I will restart the program for you")
elif not
os.path.isfile(filename):
print("The file has not yet been
created")

write(filename)
else:

print("Error")





def
write(filename):
print()

print("What would you like the
word to end writing to be?")
keyword = input()
print("What would
you like in your file?")
text = ""
filename = open(filename,
'w')
while text != keyword:
filename.write(text)

filename.write("\n")
text =
input()



def read():

print()
print("You are now in the reading area")
filename =
input("Please enter your file name: -")
if
os.path.isfile(filename):
filename = open(filename, 'r')

print(filename.read())
elif not os.path.isfile(filename):

print("The file does not exist\n\n")

start()

else:

print("Error")


start()

javascript - state provider and route provider in angularJS

Below is my app.js
file



angular

.module('repoApp', [
'ngAnimate',
'ngAria',


'ngCookies',
'ngMessages',
'ngResource',

'ngRoute',
'ngSanitize',
'ngTouch',

'ui.bootstrap',
'ui.router'
])
.config(function
($routeProvider) {

$routeProvider
.when('/',
{
templateUrl: 'views/main.html',
controller:
'MainCtrl'
})
.when('/about', {
templateUrl:
'views/about.html',
controller: 'AboutCtrl'
})

.when('/login', {

templateUrl: 'views/loginPage.html',

controller: 'loginCtrl'
})
.otherwise({
redirectTo:
'/'
});
});
angular

.module('loginState',['ui.router']);



Below
is my states
file



angular

.module('repoApp')
.config(function ($stateProvider) {


$stateProvider.state('home1', {
url:'/home1',
templateUrl:
'views/modals/test.html'

})

.state('secondState',{
url:'/secondState',
templateUrl:
'views/modals/secondStateTest.html'
});

});


The problem is,
using my html i navigate to login
page.







but I am
trying to hit the state as soon my flow hit the
controller




angular.module('repoApp')

.controller('loginCtrl', function ($scope,$modal,$state) {

$scope.awesomeThings = [
'HTML5 Boilerplate',

'AngularJS',
'Karma'
];
$state.go('home1');

$scope.openDialog = function () {
$modal.open({


keyboard: 'static',
templateUrl: 'views/login/loginCred.html',

});
};

});


but I am not able
to hit the home state.
If I change my states file i.e




$stateProvider.state('home1',
{
url:'/login',
templateUrl: 'views/modals/test.html'

})


here I changed URL.
It works fine now.



I have a template from where
I want to navigate to a next
state





data-ng-click="openDialog()">open ME!
ui-sref="secondState">click
here



but
as soon I click this anchor tag it navigates me back to home page. ie not to the state I
intend to go.
The main issue is URL(i guess) any help will be
appreciated.

Undefined index in PHP

itemprop="text">












Good
day!



I am having the following error in my
code:



if
(!$_POST['SUBMIT']){ //ERROR: Undefined index
?>

Add
Employee



cellpadding="2">


width="100">SSN



width="100"> 



id="SSN">
type="SUBMIT" id="ADD" value="ADD">




}
else {
//code here

}
?>


How
can I remove the error above? Thank you.


class="post-text" itemprop="text">
class="normal">Answer





It should be a notice and not an
error.



To fix is you'll have to check whether
$_POST['submit'] is
set:



if(!isset($_POST['submit']))
{
...
}


Saturday 30 December 2017

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

itemprop="text">


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



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



Answer




In an interview with Rolling
Stone
, director href="http://www.rollingstone.com/movies/news/christopher-nolan-dark-knight-rises-isn-t-political-20120720">Christopher
Nolan insists his film is
apolitical:





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

Wall Street statement?



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

telling a story. If you're saying, “Have you made a film
that's
supposed to be criticizing the Occupy Wall Street movement?” –
well,
obviously, that's not true.




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



If the populist movement is

manipulated by somebody who is evil, that surely is a criticism of the
evil
person. You could also say the conditions the evil person is


exploiting are problematic and should be
addressed.



How can I make SQL case sensitive string comparison on MySQL?

itemprop="text">

I have a function that returns five
characters with mixed case. If I do a query on this string it will return the value
regardless of case.



How can I make MySQL string
queries case sensitive?


itemprop="text">
class="normal">Answer



href="http://dev.mysql.com/doc/refman/5.0/en/case-sensitivity.html"
rel="noreferrer">http://dev.mysql.com/doc/refman/5.0/en/case-sensitivity.html






The default character set and collation are latin1 and latin1_swedish_ci, so
nonbinary string comparisons are case insensitive by default. This means that if you
search with col_name LIKE 'a%', you get all column values that start with A or a. To
make this search case sensitive, make sure that one of the operands has a case sensitive
or binary collation. For example, if you are comparing a column and a string that both
have the latin1 character set, you can use the COLLATE operator to cause either operand
to have the latin1_general_cs or latin1_bin
collation:




col_name
COLLATE latin1_general_cs LIKE 'a%'
col_name LIKE 'a%' COLLATE
latin1_general_cs
col_name COLLATE latin1_bin LIKE 'a%'
col_name
LIKE 'a%' COLLATE
latin1_bin





If you want a column always to be treated in case-sensitive fashion, declare it
with a case sensitive or binary
collation.



c++ - Is memory barrier or atomic operation required in a busy-wait loop?

itemprop="text">


Consider the following
spin_lock() implementation, originally from href="https://stackoverflow.com/a/32658335/3169754">this
answer:



void
spin_lock(volatile bool* lock) {
for (;;) {
// inserts an acquire
memory barrier and a compiler barrier
if (!__atomic_test_and_set(lock,
__ATOMIC_ACQUIRE))
return;

while (*lock) // no
barriers; is it OK?

cpu_relax();

}
}


What I
already
know:




  • volatile
    prevents compiler from optimizing out *lock re-read on each
    iteration of the while
    loop;

  • volatile href="https://stackoverflow.com/questions/26307071/does-the-c-volatile-keyword-introduce-a-memory-fence">inserts
    neither memory nor compiler
    barriers;


  • such an implementation
    actually works in GCC for x86 (e.g. in Linux kernel) and some
    other architectures;

  • at least one memory and compiler
    barrier href="https://jfdube.wordpress.com/2012/03/08/understanding-memory-ordering/"
    rel="nofollow noreferrer">is required in
    spin_lock() implementation for a generic architecture; this
    example inserts them in href="https://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-Builtins.html" rel="nofollow
    noreferrer">__atomic_test_and_set().



Questions:




  1. Is
    volatile enough here or are there any architectures or
    compilers where memory or compiler barrier or atomic operation is required in the
    while loop?



    1.1
    According to C++
    standards?




    1.2 In practice, for known
    architectures and compilers, specifically for GCC and platforms it
    supports?


  2. Is this implementation
    safe on all architectures supported by GCC and Linux? (It is at
    least inefficient on some architectures,
    right?)

  3. Is the while loop safe
    according to C++11 and its memory
    model?



/>

There are several related questions, but I was
unable to construct an explicit and unambiguous answer from
them:





class="post-text" itemprop="text">
class="normal">Answer







  1. Is volatile enough here or are there any architectures or compilers where
    memory or compiler barrier or atomic operation is required in the while
    loop?





will the
volatile code see the change. Yes, but not necessarily as quickly as if there was a
memory barrier. At some point, some form of synchronization will occur, and the new
state will be read from the variable, but there are no guarantees on how much has
happened elsewhere in the
code.






1.1 According to C++
standards?




From
cppreference :
memory_order



It is the memory model
and memory order which defines the generalized hardware that the code needs to work on.
For a message to pass between threads of execution, an inter-thread-happens-before
relationship needs to occur. This requires
either...




  • A
    synchronizes-with B


  • A has a std::atomic
    operation before B

  • A indirectly synchronizes with B
    (through X).

  • A is sequenced before X which inter-thread
    happens before B

  • A interthread happens before X and X
    interthread happens before
    B.



As you are not
performing any of those cases there will be forms of your program where on some current
hardware, it may fail.



In practice, the end of a
time-slice will cause the memory to become coherent, or any form of barrier on the
non-spinlock thread will ensure that the caches are
flushed.




Not sure on the causes of
the volatile read getting the "current
value".




1.2 In
practice, for known architectures and compilers, specifically for GCC and platforms it
supports?




As the
code is not consistent with the generalized CPU, from C++11
then it is likely this code will fail to perform with versions of C++ which try to
adhere to the standard.



From href="http://en.cppreference.com/w/cpp/language/cv" rel="nofollow
noreferrer">cppreference : const volatile qualifiers
Volatile
access stops optimizations from moving work from before it to after it, and from after
it to before it.





"This
makes volatile objects suitable for communication with a signal handler, but not with
another thread of
execution"




So an
implementation has to ensure that instructions are read from the memory location rather
than any local copy. But it does not have to ensure that the volatile write is flushed
through the caches to produce a coherent view across all the CPUs. In this sense, there
is no time boundary on how long after a write into a volatile variable will become
visible to another thread.



Also see href="https://www.kernel.org/doc/html/v4.11/process/volatile-considered-harmful.html"
rel="nofollow noreferrer">kernel.org why volatile is nearly always wrong in
kernel






Is this implementation safe on all architectures supported by GCC and Linux?
(It is at least inefficient on some architectures,
right?)




There is
no guarantee the volatile message gets out of the thread which sets it. So not really
safe. On linux it may be
safe.




Is the while
loop safe according to C++11 and its memory
model?




No - as it
doesn't create any of the inter-thread messaging
primitives.



java - Why is try/catch needed in some cases but not others?





I've been doing some pure Java development recently, and I'm using
an external lib that exposes a small number of methods, each of which have the
possibility of throwing an
Exception.




Eclipse
won't let me compile my program unless I wrap each of those calls in a
try-catch block. So far, no big
deal.



Then I noticed some things, like
ArrayList.add(), which throws
IndexOutOfBoundsException. How is it that I can call something
like this without needing to wrap it in a try..catch? Obv, in
this particular case, it would be incredibly irritating if you had to do it each time,
but how and why is try-catch enforced in some situations, but
not others?


itemprop="text">
class="normal">Answer



href="http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html"
rel="noreferrer">Unchecked exceptions
(subclasses of Error or
RuntimeException) need no try..catch
block, and when there is no try...catch, the method need not to
declare itself to be throws (you can, of course, and some
consider declaring throws to be a good practice) . On the other
hand, checked ones do need the
try...catch, or declares
throws.


bash - How to use double or single brackets, parentheses, curly braces

itemprop="text">

I am confused by the usage of
brackets, parentheses, curly braces in Bash, as well as the difference between their
double or single forms. Is there a clear explanation?



Answer





In Bash,
test and [ are shell
builtins.



The href="http://mywiki.wooledge.org/BashFAQ/031" rel="noreferrer">double
bracket, which is a shell keyword, enables additional functionality. For
example, you can use && and ||
instead of -a and -o and there's a
regular expression matching operator
=~.



Also, in a simple
test, double square brackets seem to evaluate quite a lot quicker than single
ones.



$ time for ((i=0; i<10000000; i++)); do [[ "$i"
= 1000 ]]; done

real 0m24.548s
user
0m24.337s

sys 0m0.036s
$ time for ((i=0; i<10000000;
i++)); do [ "$i" = 1000 ]; done

real 0m33.478s
user
0m33.478s
sys
0m0.000s


The braces,
in addition to delimiting a variable name are used for href="http://tiswww.case.edu/php/chet/bash/bashref.html#Brace-Expansion"
rel="noreferrer">parameter expansion so you can do things
like:





  • Truncate
    the contents of a variable



    $
    var="abcde"; echo
    ${var%d*}
    abc

  • Make
    substitutions similar to
    sed



    $
    var="abcde"; echo
    ${var/de/12}
    abc12


  • Use
    a default value



    $ default="hello";
    unset var; echo
    ${var:-$default}
    hello

  • and
    several
    more




Also,
brace expansions create lists of strings which are typically iterated over in
loops:




$ echo
f{oo,ee,a}d
food feed fad

$ mv
error.log{,.OLD}
(error.log is renamed to error.log.OLD because the brace
expression
expands to "mv error.log error.log.OLD")

$ for
num in {000..2}; do echo "$num";
done
000

001
002

$ echo
{00..8..2}
00 02 04 06 08

$ echo {D..T..4}
D H
L P T



Note
that the leading zero and increment features weren't available before Bash
4.



Thanks to gboffi for reminding me about brace
expansions.



Double parentheses are used for
rel="noreferrer">arithmetic
operations
:



((a++))

((meaning
= 42))


for ((i=0; i<10;
i++))

echo $((a + b + (14 *
c)))


and they enable
you to omit the dollar signs on integer and array variables and include spaces around
operators for readability.



Single brackets are
also used for rel="noreferrer">array
indices:



array[4]="hello"


element=${array[index]}


Curly
brace are required for (most/all?) array references on the right hand
side.



ephemient's
comment reminded me that parentheses are also used for subshells. And that they are used
to create arrays.



array=(1 2
3)
echo
${array[1]}

2


deeper understanding of closure in Javascript

itemprop="text">


I was reading the comments
on an answer and saw href="https://stackoverflow.com/questions/15667093/how-to-understand-closure-in-javascript/15667314#comment22237952_15667362">this
comment:





[the closure] doesn't persist the state of foo so much as creates a special
scope containing (1) the returned function and (2) all the external variables referenced
at the time of the return. This special scope is called a closure.




OK, so far so
good. Now here is the interesting part that I didn't know
about:






Case in point... if you had another var defined in foo that was
not referenced in the return function, it would not exist
in the closure
scope.




I guess
that makes sense, but what implications does this have other than memory use /
perfomance
?



Question -- If all
variables in scope were included in the closure, what would that allow me to do that I
cannot do with the current model?


class="post-text" itemprop="text">
class="normal">Answer



I think
you're taking that comment too literally. The comment is just saying that you can't
access it outside the function scope (it's not publicly accessible), not that its not
available at all within the function. The returned function will have access to all of
the outer functions scope no matter what. You just can't access that scope outside the
outer function if the inner function doesn't provide a way of accessing
it.



For instance, this expression evaluates to
4:




function
testClosure(){
var x = 2;
return function(y){

alert(eval(y));
}

}

var closure =
testClosure();


closure("x+2");
//4


href="http://jsfiddle.net/dmRcH/" rel="nofollow
noreferrer">http://jsfiddle.net/dmRcH/



So
x is available despite not being directly
referenced



Further
research




It appears that chrome and
firefox at least do attempt to optimize this in the sense that if you're not providing
ANY way to reference the x variable, it doesn't show up as
being available in the debugger. Running this with a breakpoint inside a closure shows
x as unavailable on Chrome 26 and Firefox 18.



rel="nofollow
noreferrer">http://jsfiddle.net/FgekX/1/



But
thats just a memory management detail, not a relevant property of the language. If there
is any possible way that you could reference the variable, it is passed, and my
suspicion is that other browsers may not optimize this in the same way. Its always
better to code to the spec than to an implementation. In this case though the rule
really is: "if there's any possible way for you to access it, it will be
available"
. And also, don't use eval because it really will
keep your code from optimizing anything
.



templates - declaring a C++ set iterator













The
following code will not
compile:



#include

#include
using namespace
std;

template
void printSet(set
s){

set::iterator
it;
}

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

set s;
printSet(s);
return
0;
}



I
get an error saying:



set.cpp: In
function ‘void printSet(std::set,
std::allocator<_CharT> >)’:
set.cpp:7: error: expected `;' before
‘it’
set.cpp: In function ‘void printSet(std::set,
std::allocator<_CharT> >) [with T = int]’:
set.cpp:12: instantiated
from here
set.cpp:7: error: dependent-name
‘std::set,std::allocator<_CharT> >::iterator’ is
parsed as a non-type, but instantiation yields a type
set.cpp:7: note: say
‘typename std::set,std::allocator<_CharT>
>::iterator’ if a type is
meant



What
did I do wrong? I feel like I've hardly written anything, and already C++ gives me this
scary message.



In case it is helpful, it looks
like, if I comment out the line with the iterator, there are no errors. However, all the
examples I've seen online so far seem to declare iterators this way. I
think.



Answer




Precede your declaration with the keyword
typename,
thusly:



typename
set::iterator
it;


You need to do
this whenever you refer to a type that is dependent upon a template argument. In this
case, iterator is dependent on T. Otherwise, the compiler has
difficulty trying to figure out what iterator is, whether it's
a type, or a static member or something else. (well, technically, it doesn't try to
figure it out, its decision is already made, it just happens to be
wrong)




Note that if you have a
concrete type, for
example:



set::iterator
it;


The
typename is not necessary.



html - Find JavaScript handler connected to a button's click event





During some code investigating, I found a html submit button like
this:






I
know somewhere there is javascript code that handeles the button
click event. How can I find that javascript
code?



Answer




In
Firefox:





  1. F12

  2. Find
    the line you want to inspect

  3. Click on the small
    ev button at the end of the line (if there is nothing then
    no JavaScript is linked)

  4. See what is linked to
    it



In
Chrome:





  1. F12

  2. Click
    on the line you want to inspect

  3. Click on the
    "Event Listeners" Tab (where you see the styles by
    default)

  4. There you can see the linked
    events



In Edge:




  1. F12


  2. Click
    on the DOM Explorer tab

  3. Click on the line you want to
    inspect

  4. Click on the "Events"
    Tab (where you see the styles by default)

  5. There you can
    see the linked events



python - cannot import a module after os.chdir()





I have a python file with the class A
defined in it in a different directory than the one I am working in. I want to import a
module from that class in my script. I wrote something like this in
jupyter:




import
os
parent_dir = 'path/to/class'
os.chdir(parent_dir)
from
A import a


It works
perfectly fine and I get to execute the program. However when I run the script in the
same directory from the terminal, I get this
error:



ModuleNotFoundError: No
module named
'a'



I put a
os.getcwd() before the error to make sure it is in the same
directory, and when I go to that directory from the terminal and import the module
directly there are no errors. I wonder why I get this error when running the script.


style="font-weight: bold;">

Answer




Don't use os.chdir,
because it changes a global state, that can lead to unexpected behaviour somewhere
else.



Expand
sys.path:



import
sys
sys.path.append('/absolute/path/to/module')



r - How to persist changes in a text file using shiny?

itemprop="text">


I have a small shiny app
for annotating text
files.




  1. The UI provides
    fileInput to select .txt files. One of
    the files is the default when the app is launched.

  2. Next,
    Previous buttons allow user to display the contents of the
    file, one sentence at a time.

  3. User may select any text
    within a sentence and click the Add Markup button to annotate
    the sentence. The Action Button triggers javascript function
    addMarkup().

  4. The sentence is
    displayed after being marked
    up.




I am only
posting the shiny app code here. Complete code of the app is available on href="https://github.com/beyond2013/dynamicContent" rel="nofollow noreferrer">github
repository




library(shiny)
ui <- fluidPage(

tags$head(tags$script(src="textselection.js")),
titlePanel("Corpus Annotation
Utility"),
sidebarLayout(
sidebarPanel(

fileInput('fileInput', 'Select Corpus', accept = c('text', 'text','.txt')),

actionButton("Previous", "Previous"),

actionButton("Next",
"Next"),
actionButton("mark", "Add Markup")
),

mainPanel(
tags$h1("Sentence: "),

htmlOutput("sentence"),
tags$h1("Sentence marked up: "),

htmlOutput("sentenceMarkedUp")
)

)

)
server <- function(input, output) {

sourceData <- reactive({
corpusFile <- input$fileInput

if(is.null(corpusFile)){
return(readCorpus('data/news.txt'))

}
readCorpus(corpusFile$datapath)

})


corpus <- reactive({sourceData()})

values <- reactiveValues(current = 1)
observeEvent(input$Next,{

if(values$current >=1 & values$current < length(corpus())){

values$current <- values$current + 1
}
})

observeEvent(input$Previous,{
if(values$current > 1 & values$current
<= length(corpus())){
values$current <- values$current -
1

}
})
output$sentence <-
renderText(corpus()[values$current])
}
shinyApp(ui = ui, server =
server)



readCorpus()
function looks like
this:



readCorpus <-
function(pathToFile){

con <- file(pathToFile)

sentences <- readLines(con, encoding = "UTF-8")
close(con)

return(sentences)
}


My
question is how can I persist the sentences to a file after they have been
annotated?



href="https://i.stack.imgur.com/2hfTF.png" rel="nofollow noreferrer"> src="https://i.stack.imgur.com/2hfTF.png" alt="screenshot of the
app">




Update:
I
have gone through href="https://shiny.rstudio.com/articles/persistent-data-storage.html" rel="nofollow
noreferrer">Persistent data storage in Shiny apps, and hope that I will be
able to follow along the documentation regarding persistent storage. However I am still
unsure how to capture the sentence after it has been marked up.



Answer




You have two issues here - persisting the
changes, and then saving the output. I solved the problem using a bit of JS and a bit of
R code. I'll do a pull request on Github to submit the broader code. However, here's the
core of it.



In your Javascript that you use to
select things, you can use Shiny.onInputChange() to update an
element of the input vector. Doing this, you can create a
reactiveValues item for the corpus, and then update it with
inputs from your interface.



Below, you'll notice
that I switched from using a textnode to using just the inner HTML. Using a node, and
firstChild, as you had it before, you end up truncating the
sentence after the first annotation (since it only picks the stuff before
. Doing it this way seems to work
better.




window.onload =
function(){
document.getElementById('mark').addEventListener('click',
addMarkup);
}

function addMarkup(){
var
sentence = document.getElementById("sentence").innerHTML,

selection="";
if(window.getSelection){
selection =
window.getSelection().toString();
}

else
if(document.selection && document.selection.type != "Control"){

selection = document.selection.createRange().text;
}

if(selection.length === 0){
return;
}
marked =
"".concat(selection).concat("");
result =
sentence.replace(selection, marked);

document.getElementById("sentence").innerHTML = result;

Shiny.onInputChange("textresult",result);

}


Next,
I've tried to simplify your server.R code. You were using a
reactive context to pull from another reactive context
(sourceData into corpus), which seemed
unnecessary. So, I tried to refactor it a
bit.



library(shiny)
source("MyUtils.R")
ui
<- fluidPage(
tags$head(tags$script(src="textselection.js")),

titlePanel("Corpus Annotation Utility"),

sidebarLayout(

sidebarPanel(
fileInput('fileInput', 'Select Corpus', accept = c('text',
'text','.txt')),
actionButton("Previous", "Previous"),

actionButton("Next", "Next"),
actionButton("mark", "Add Markup"),

downloadButton(outputId = "save",label = "Download")),
mainPanel(

tags$h1("Sentence: "),
htmlOutput("sentence"))


)
)

server <- function(input, output) {

corpus <- reactive({
corpusFile <- input$fileInput

if(is.null(corpusFile)) {
return(readCorpus('data/news.txt'))
}
else {
return(readCorpus(corpusFile$datapath))


}
})

values <- reactiveValues(current =
1)
observe({
values$corpus <- corpus()
})

output$sentence <- renderText(values$corpus[values$current])


observeEvent(input$Next,{

if(values$current >=1 &
values$current < length(corpus())) {
values$current <- values$current +
1
}
})
observeEvent(input$Previous,{

if(values$current > 1 & values$current <= length(corpus())) {

values$current <- values$current - 1
}
})

observeEvent(input$mark,{

values$corpus[values$current] <-
input$textresult
})
output$save <- downloadHandler(filename =
"marked_corpus.txt",
content = function(file) {


writeLines(text = values$corpus,
con = file,
sep =
"\n")

})
}



Now,
the code has a few changes. The loading from file is basically the same. I was right
about my skepticism on isolate - replacing it with an
observe accomplishes what I wanted to do, whereas
isolate would only give you the initial load. Anyway, we use
observe to load the corpus values into the
reactiveValues object you created - this is to give us a place
to propagate changes to the data.



We keep the
remaining logic for moving forward and backward. However, we change the way the output
is rendered so that it looks at the reactiveValues object.
Then, we create an observer that updates the reactiveValues
object with the input from our updated Javascript. When this happens, the data gets
stored permanently, and you can also mark more than one sequence in the string (though I
have not done anything with nested marking or with removing marks). Finally, a save
function is added - the resulting strings are saved out with
used to show the marked
areas.



If you load a previously marked file, the
marks will show up again.


php - static::staticFunctionName()

itemprop="text">

I know what
self::staticFunctionName() and
parent::staticFunctionName() are, and how they are different
from each other and from
$this->functionName.



But
what is static::staticFunctionName()?



Answer




It's the keyword used in PHP 5.3+ to invoke
late static bindings.
Read all about it in the manual: href="http://php.net/manual/en/language.oop5.late-static-bindings.php"
rel="noreferrer">http://php.net/manual/en/language.oop5.late-static-bindings.php



/>


In summary,
static::foo() works like a dynamic
self::foo().



class
A {
static function foo() {
// This will be executed.

}
static function bar() {
self::foo();

}

}

class B extends A {
static
function foo() {
// This will not be executed.
// The above
self::foo() refers to A::foo().

}
}

B::bar();



static
solves this problem:



class A
{
static function foo() {
// This is overridden in the child
class.
}
static function bar() {

static::foo();

}
}

class B extends
A {
static function foo() {
// This will be executed.

// static::foo() is bound late.

}
}


B::bar();


static
as a keyword for this behavior is kind of confusing, since it's all but.
:)


css3 - CSS select first element with a certain class

What is the syntax for selecting the first element with a
certain class? Please specify whether that method of selection is part of CSS3 or
CSS2.1.

email - Error sending special characters on mail function (php)

I'm using the mail function on php to send a confirmation
email. It actually works, but just for some mails. For example, if you recieve that on a
gmail it's fine, but on a college mail it appears ? instead of special
characters.
The problem is that that mail includes a validation link,which
looks like www.myweb.com/confirmation.php?passkey=(passkey) and if the mail and the
special characters aren't send properly this link is also wrong (the = doesn't
appear).


I've already tried writting


iconv_set_encoding("internal_encoding",
"UTF-8");

on top of the mail
function, but it doesn't work. What can it be?


Thanks for
your help!

Friday 29 December 2017

'citizen-kane' tag wiki - Movies & TV

readability="9">


Relates to the film by Orson Welles
concerning the life of a newspaper owner, politician and magnate as presented through
the eyes of an investigative reporter.





readability="17">


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


design patterns - What are MVP and MVC and what is the difference?





When looking beyond the href="https://en.wikipedia.org/wiki/Rapid_application_development"
rel="noreferrer">RAD (drag-drop and configure) way of building user
interfaces that many tools encourage you are likely to come across three design patterns
called rel="noreferrer">Model-View-Controller, href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter"
rel="noreferrer">Model-View-Presenter and href="http://en.wikipedia.org/wiki/Model_View_ViewModel"
rel="noreferrer">Model-View-ViewModel. My question has three parts to
it:




  1. What issues do these
    patterns address?

  2. How are they
    similar?

  3. How are they
    different?


class="post-text" itemprop="text">
class="normal">Answer




Model-View-Presenter



In
MVP, the Presenter contains the UI business logic for the
View. All invocations from the View delegate directly to Presenter. The Presenter is
also decoupled directly from the View and talks to it through an interface. This is to
allow mocking of the View in a unit test. One common attribute of MVP is that there has
to be a lot of two-way dispatching. For example, when someone clicks the "Save" button,
the event handler delegates to the Presenter's "OnSave" method. Once the save is
completed, the Presenter will then call back the View through its interface so that the
View can display that the save has completed.



MVP tends to be a very natural pattern for
achieving separated presentation in Web Forms. The reason is that the View is always
created first by the ASP.NET runtime. You can href="http://www.codeplex.com/websf/Wiki/View.aspx?title=MVPDocumentation&referringTitle=bundles"
rel="noreferrer">find out more about both
variants.



Two primary
variations



Passive
View:
The View is as dumb as possible and contains almost zero logic. The
Presenter is a middle man that talks to the View and the Model. The View and Model are
completely shielded from one another. The Model may raise events, but the Presenter
subscribes to them for updating the View. In Passive View there is no direct data
binding, instead the View exposes setter properties which the Presenter uses to set the
data. All state is managed in the Presenter and not the
View.




  • Pro: maximum
    testability surface; clean separation of the View and
    Model

  • Con: more work (for example all the setter
    properties) as you are doing all the data binding yourself.



Supervising
Controller:
The Presenter handles user gestures. The View binds to the
Model directly through data binding. In this case it's the Presenter's job to pass off
the Model to the View so that it can bind to it. The Presenter will also contain logic
for gestures like pressing a button, navigation, etc.




  • Pro: by leveraging
    databinding the amount of code is reduced.

  • Con: there's
    less testable surface (because of data binding), and there's less encapsulation in the
    View since it talks directly to the
    Model.



Model-View-Controller



In
the MVC, the Controller is responsible for determining
which View to display in response to any action including when the application loads.
This differs from MVP where actions route through the View to the Presenter. In MVC,
every action in the View correlates with a call to a Controller along with an action. In
the web each action involves a call to a URL on the other side of which there is a
Controller who responds. Once that Controller has completed its processing, it will
return the correct View. The sequence continues in that manner throughout the life of
the application:




Action in the
View
-> Call to Controller
-> Controller Logic

-> Controller returns the
View.


One other big difference
about MVC is that the View does not directly bind to the Model. The view simply renders,
and is completely stateless. In implementations of MVC the View usually will not have
any logic in the code behind. This is contrary to MVP where it is absolutely necessary
because, if the View does not delegate to the Presenter, it will never get
called.



Presentation
Model



One other pattern to look at is the
Presentation Model pattern. In this pattern there is no
Presenter. Instead the View binds directly to a Presentation Model. The Presentation
Model is a Model crafted specifically for the View. This means this Model can expose
properties that one would never put on a domain model as it would be a violation of
separation-of-concerns. In this case, the Presentation Model binds to the domain model,
and may subscribe to events coming from that Model. The View then subscribes to events
coming from the Presentation Model and updates itself accordingly. The Presentation
Model can expose commands which the view uses for invoking actions. The advantage of
this approach is that you can essentially remove the code-behind altogether as the PM
completely encapsulates all of the behaviour for the view. This pattern is a very strong
candidate for use in WPF applications and is also called href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx"
rel="noreferrer">Model-View-ViewModel.



There
is a rel="noreferrer">MSDN article about the Presentation Model and a section in
the rel="noreferrer">Composite Application Guidance for WPF (former Prism)
about rel="noreferrer">Separated Presentation Patterns



javascript - How to pass props to {this.props.children}

itemprop="text">

I'm trying to find the proper way to
define some components which could be used in a generic
way:






value="2">




There
is a logic going on for rendering between parent and children components of course, you
can imagine

Blog Archive