问:
Getting results even if row doesn't exist in JOIN table
I store 2 different backup types (Full or Log) and also have 2 different server types (Local or Azure) this query below brings back the correct results as 3 rows are returned, however when i delete a row which corresponds to this line in the SQL query:

```<code>AND (r4.Type = 'Full' AND r4.Server = 'Azure')
</code>```

Only 2 rows are then retrieved because their isn't a row which exists in the table for type 'Full' and server 'Azure'

This is the query i've done:

```<code>SELECT DISTINCT
   r1.Tenant,
   r1.Name,
   r1.DBName,
   r1.Server as Server1,
   r1.Type as Type1,
   r1.Date as Date1,
   r2.Type as Type2,
   r2.Date as Date2,
   r2.Server as Server2,
   r3.Type as Type3,
   r3.Date as Date3,
   r3.Server as Server3,
   r4.Type as Typ4,
   r4.Date as Date4,
   r4.Server as Server4
FROM #Results AS r1
JOIN #Results AS r2 ON r2.DBName = r1.DBName
JOIN #Results AS r3 ON r3.DBName = r1.DBName
JOIN #Results AS r4 ON r4.DBName = r1.DBName
WHERE
(r1.TYPE = 'Full' AND r1.Server = 'Local') AND
(r2.TYPE = 'Log' AND r2.Server = 'Local') AND
(r3.Type = 'Full' AND r3.Server = 'Azure') AND
(r4.Type = 'Log' AND r4.Server = 'Azure')
ORDER BY r1.Tenant
</code>```

As you can see from the screenshot above, this is the data retrieved. I expect another row containing the following:

Log, Local

Full, Local

Log, Azure

NULL, NULL (as a Full Azure backup doesn't exist)

Here is the data within the Result table:

答:
You will want to use a LEFT JOIN since you still want a result row for r1 and r2 when r3 and r4 are null.

You probably tried modifying all of the JOIN statments, but got the same results... Here's the problem. When you try:

```<code>SELECT * FROM table_1 t1
LEFT JOIN table_2 t2 ON t1.id = t2.t1_id
WHERE t2.some_column = 'a value'
</code>```

The LEFT JOIN is working properly, and returning a row with null t2 values, however this row is thrown away in the WHERE clause.  t2.some_column = 'a value' Can't be true, since t2.some_column = NULL

Solution:

```<code>SELECT * FROM table_1 t1
LEFT JOIN table_2 t2 ON t1.id = t2.t1_id AND t2.some_column = 'a value'
</code>```

Now any a t2 row without `some_column = 'a value' won't be included in the result set, however that's okay because we're using LEFT JOIN, so that row will consist of t1 values with NULL t2 values

Alternatively you could try: WHERE t2.is IS NULL OR t2.some_column = 'a value'

In relation to your query:

```<code>```select ...
FROM #Results AS r1
LEFT JOIN #Results AS r2 ON r2.DBName = r1.DBName AND (r2.TYPE = 'Log' AND r2.Server = 'Local')
LEFT JOIN #Results AS r3 ON r3.DBName = r1.DBName AND (r3.Type = 'Full' AND r3.Server = 'Azure')
LEFT JOIN #Results AS r4 ON r4.DBName = r1.DBName AND (r4.Type = 'Log' AND r4.Server = 'Azure')
WHERE (r1.TYPE = 'Full' AND r1.Server = 'Local')
ORDER BY r1.Tenant```
</code>```

Body:
I store 2 different backup types (Full or Log) and also have 2 different server types (Local or Azure) this query below brings back the correct results as 3 rows are returned, however when i delete a row which corresponds to this line in the SQL query:

AND (r4.Type = 'Full' AND r4.Server = 'Azure')

Only 2 rows are then retrieved because their isn't a row which exists in the table for type 'Full' and server 'Azure'

This is the query i've done:

SELECT DISTINCT
   r1.Tenant,
   r1.Name,
   r1.DBName,
   r1.Server as Server1,
   r1.Type as Type1,
   r1.Date as Date1,
   r2.Type as Type2,
   r2.Date as Date2,
   r2.Server as Server2,
   r3.Type as Type3,
   r3.Date as Date3,
   r3.Server as Server3,
   r4.Type as Typ4,
   r4.Date as Date4,
   r4.Server as Server4
FROM #Results AS r1
JOIN #Results AS r2 ON r2.DBName = r1.DBName
JOIN #Results AS r3 ON r3.DBName = r1.DBName
JOIN #Results AS r4 ON r4.DBName = r1.DBName
WHERE
(r1.TYPE = 'Full' AND r1.Server = 'Local') AND
(r2.TYPE = 'Log' AND r2.Server = 'Local') AND
(r3.Type = 'Full' AND r3.Server = 'Azure') AND
(r4.Type = 'Log' AND r4.Server = 'Azure')
ORDER BY r1.Tenant

As you can see from the screenshot above, this is the data retrieved. I expect another row containing the following:

Log, Local

Full, Local

Log, Azure

NULL, NULL (as a Full Azure backup doesn't exist)

Here is the data within the Result table:

Body:
You will want to use a LEFT JOIN since you still want a result row for r1 and r2 when r3 and r4 are null.

You probably tried modifying all of the JOIN statments, but got the same results... Here's the problem. When you try:

SELECT * FROM table_1 t1
LEFT JOIN table_2 t2 ON t1.id = t2.t1_id
WHERE t2.some_column = 'a value'

The LEFT JOIN is working properly, and returning a row with null t2 values, however this row is thrown away in the WHERE clause.  t2.some_column = 'a value' Can't be true, since t2.some_column = NULL

Solution:

SELECT * FROM table_1 t1
LEFT JOIN table_2 t2 ON t1.id = t2.t1_id AND t2.some_column = 'a value'

Now any a t2 row without `some_column = 'a value' won't be included in the result set, however that's okay because we're using LEFT JOIN, so that row will consist of t1 values with NULL t2 values

Alternatively you could try: WHERE t2.is IS NULL OR t2.some_column = 'a value'

In relation to your query:

```select ...
FROM #Results AS r1
LEFT JOIN #Results AS r2 ON r2.DBName = r1.DBName AND (r2.TYPE = 'Log' AND r2.Server = 'Local')
LEFT JOIN #Results AS r3 ON r3.DBName = r1.DBName AND (r3.Type = 'Full' AND r3.Server = 'Azure')
LEFT JOIN #Results AS r4 ON r4.DBName = r1.DBName AND (r4.Type = 'Log' AND r4.Server = 'Azure')
WHERE (r1.TYPE = 'Full' AND r1.Server = 'Local')
ORDER BY r1.Tenant```


来源: stackexchange

问:
How can I trigger a sequence of animations using asynchronous events?
I have an activity which contains a handler, which handles asynchronous messages. When I get a message, I want to trigger an animation; after that, when I get another message, I want to trigger another animation, but only after the last one has finished.

What's the cleanest way to do this?

答:
You can use an animation listener to determine when the animation has finished. Something like this:</p>

```<code>    Animation a = AnimationUtils.loadAnimation(this.getContext(), R.anim.animation);

    a.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {
            if(receivedMessage == true){
                startNextAnimation();
            }
        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can use an animation listener to determine when the animation has finished. Something like this:

    Animation a = AnimationUtils.loadAnimation(this.getContext(), R.anim.animation);

    a.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {
            if(receivedMessage == true){
                startNextAnimation();
            }
        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    });


答:
Try

```<code>^([^,]*,[^,]*),([^,]*),(.*)$
</code>```

and

```<code>\1\2\3
</code>```

Note that the 2nd and 3rd literal commas in the expression are outside parens.

EDIT: I guess it would have been simpler from a minimal edit standpoint to use ^([^,]*,[^,]*),([^,]*),(.*),  and \1\2. I wasn't sure off the top of my head all of the search and replace options that I might have been overlooking so it seemed safer to work with the whole line. In hindsight that was probably silly.

Title: Notepad++ - Remove second and third comma in a csv in one shot

Body:
i have a csv file having thousands of lines of data with comma delimited, i need to remove 2nd and 3rd commas from those lines

example below

8213201711,77,429,890,5d810ffc6
9801201711,103,088,818,5d810ffc
8113201711,102,829,857,5d810ffb
8113201711,104,186,726,5d810ffc
8101201711,86,337,068,5d810ffb1
8205201711,77,137,917,5d72788c9

I need

8213201711,77429890,5d810ffc6
9801201711,103088818,5d810ffc
8113201711,102829857,5d810ffb
8113201711,104186726,5d810ffc
8101201711,86337068,5d810ffb1
8205201711,77137917,5d72788c9

I tried to find

^([^,]*,[^,]*),(.*)$

and replace with

\1\2

but, its removing only 2 occurrence

Body:
Try

^([^,]*,[^,]*),([^,]*),(.*)$

and

\1\2\3

Note that the 2nd and 3rd literal commas in the expression are outside parens.

EDIT: I guess it would have been simpler from a minimal edit standpoint to use ^([^,]*,[^,]*),([^,]*),(.*),  and \1\2. I wasn't sure off the top of my head all of the search and replace options that I might have been overlooking so it seemed safer to work with the whole line. In hindsight that was probably silly.


问:
Can you navigate the contents of a Vector's index via a String?
Is it possible to do something similar to this in Haxe?

```<code>private var _bindingsFiltered:Vector<String>;
_bindingsFiltered = new Vector<String>();

_controller_touched_binding.action = "meta_start";
</code>```

What I would like to be able to do:

```<code>_bindingsFiltered[_controller_touched_binding.action] = "BUTTON_13";
trace(_bindingsFiltered["meta_start"]); //result: "BUTTON_13"
</code>```

I want to be able to override a specific index too (still accessed via a string), with a new value, rather than keep pushing new content to the end of the vector. I have been using 'openfl.utils.Object' to cheat for now but I am looking for a more reliable approach for the long run.

Is there a way to do this in Haxe?

If not, what are my options?

I would also be interested in a solution for this in AS3, if there is one (avoiding the Array class).

My goal is to find a method that I can use in both languages seamlessly (next-to-none, differences).

答:
Vector's cannot be indexed by string in Haxe. A vector is an array with a fixed size. This is the Haxe manual on that subject.

Instead of vectors, you can use a Map.

```<code>class Test {

    private var vector:Map<String, String> = new Map<String, String>();

    public function new() {
        var str = 'haxe';

        vector[str] = "is great";
        trace(vector[str]);
    }

    static function main() {
        new Test();
    }
}
</code>```

https://try.haxe.org/#F74Ba

Body:
Is it possible to do something similar to this in Haxe?

private var _bindingsFiltered:Vector<String>;
_bindingsFiltered = new Vector<String>();

_controller_touched_binding.action = "meta_start";

What I would like to be able to do:

_bindingsFiltered[_controller_touched_binding.action] = "BUTTON_13";
trace(_bindingsFiltered["meta_start"]); //result: "BUTTON_13"

I want to be able to override a specific index too (still accessed via a string), with a new value, rather than keep pushing new content to the end of the vector. I have been using 'openfl.utils.Object' to cheat for now but I am looking for a more reliable approach for the long run.

Is there a way to do this in Haxe?

If not, what are my options?

I would also be interested in a solution for this in AS3, if there is one (avoiding the Array class).

My goal is to find a method that I can use in both languages seamlessly (next-to-none, differences).

Body:
Vector's cannot be indexed by string in Haxe. A vector is an array with a fixed size. This is the Haxe manual on that subject.

Instead of vectors, you can use a Map.

class Test {

    private var vector:Map<String, String> = new Map<String, String>();

    public function new() {
        var str = 'haxe';

        vector[str] = "is great";
        trace(vector[str]);
    }

    static function main() {
        new Test();
    }
}

https://try.haxe.org/#F74Ba


问:
Special characters replace using regex in python
Just for learning I am trying to replace all the special characters present in the keyboard to replace with underscore'_'

```<code>List of characters= ~!@#$%^&*()+|}{:"?><-=[]\;',./
</code>```

string I created:

```<code>table = """123~!@#$%^&*()+|}{:"?><-=[]\;',./"""

import re

table1= re.sub(r'!~@#$%^&*()-+={}[]:;<.>?/\'"', '_', table)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.7/re.py", line 151, in sub
    return _compile(pattern, flags).sub(repl, string, count)
  File "/usr/lib64/python2.7/re.py", line 242, in _compile
    raise error, v # invalid expression
sre_constants.error: unexpected end of regular expression
</code>```

Unable to do so I am getting the above error.

How can I replace the special characters in the string using regex

Body:
Just for learning I am trying to replace all the special characters present in the keyboard to replace with underscore'_'

List of characters= ~!@#$%^&*()+|}{:"?><-=[]\;',./

string I created:

table = """123~!@#$%^&*()+|}{:"?><-=[]\;',./"""

import re

table1= re.sub(r'!~@#$%^&*()-+={}[]:;<.>?/\'"', '_', table)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.7/re.py", line 151, in sub
    return _compile(pattern, flags).sub(repl, string, count)
  File "/usr/lib64/python2.7/re.py", line 242, in _compile
    raise error, v # invalid expression
sre_constants.error: unexpected end of regular expression

Unable to do so I am getting the above error.

How can I replace the special characters in the string using regex

Body:
Just put it in a character class and rearrange the position of some characters (namely -, escaping +):

import re
table = """123~!@#$%^&*()+|}{:"?><-=[]\;',./"""

table1 = re.sub(r'[-\+!~@#$%^&*()={}\[\]:;<.>?/\'"]', '_', table)
print(table1)
# 123____________|___________\__,__


问:
R how to plot groups of data using ggplot
I have a data frame with data like

```<code>year    range            count
2011    '0 to 500'       10
2011    '500 to 1000'    100
2012    '0 to 500'       12
2012    '500 to 1000'    50
2013    '0 to 500'       22
2013    '500 to 1000'    75
</code>```

How can I use ggplot to plot Range on the x axis, count on the y axis and a line of each year?

答:
I don't think this is a duplicate so I've provided an answer. You data structure require some minimal treatment of text (to extract to and from) and probably geom_segments instead of geom_line.

```<code> s<-"year;range;count
 2011;'0 to 500';10
 2011;'500 to 1000';100
 2012;'0 to 500';12
 2012;'500 to 1000';50
 2013;'0 to 500';22
 2013;'500 to 1000';75"

 d<-read.delim(textConnection(s),header=TRUE,sep=";",strip.white=TRUE)
 d$range <- as.character(d$range) # remove factor
 d$range <- gsub("'","",d$range) # remove character
# strsplit returns a list, one per line, with two elements, here i'm getting
# each of those elements
d$from<-as.numeric(sapply(strsplit(d$range,' to '),function(X)X[1]))
d$to<-as.numeric(sapply(strsplit(d$range,' to '),function(X)X[2]))
d$year <- as.factor(d$year)
ggplot(d)+geom_segment(aes(x=from,xend=to,y=count,yend=count,col=year))
</code>```

Body:
I have a data frame with data like

year    range            count
2011    '0 to 500'       10
2011    '500 to 1000'    100
2012    '0 to 500'       12
2012    '500 to 1000'    50
2013    '0 to 500'       22
2013    '500 to 1000'    75

How can I use ggplot to plot Range on the x axis, count on the y axis and a line of each year?

Body:
I don't think this is a duplicate so I've provided an answer. You data structure require some minimal treatment of text (to extract to and from) and probably geom_segments instead of geom_line.

 s<-"year;range;count
 2011;'0 to 500';10
 2011;'500 to 1000';100
 2012;'0 to 500';12
 2012;'500 to 1000';50
 2013;'0 to 500';22
 2013;'500 to 1000';75"

 d<-read.delim(textConnection(s),header=TRUE,sep=";",strip.white=TRUE)
 d$range <- as.character(d$range) # remove factor
 d$range <- gsub("'","",d$range) # remove character
# strsplit returns a list, one per line, with two elements, here i'm getting
# each of those elements
d$from<-as.numeric(sapply(strsplit(d$range,' to '),function(X)X[1]))
d$to<-as.numeric(sapply(strsplit(d$range,' to '),function(X)X[2]))
d$year <- as.factor(d$year)
ggplot(d)+geom_segment(aes(x=from,xend=to,y=count,yend=count,col=year))


问:
How to start a spring boot tomcat server on a specified port through command prompt
I have a very simple "Hello World" kind of REST api created using Spring Boot that is accessible through http://localhost:8080/greeting/world without any problem.

I would like to start two more instances of this API on ports 8081 and 8082 but not able to do so. It says java.net.BindException: Address already in use: bind

Command Used:

```<code>mvn spring-boot:run -Dserver.port=8081
</code>```

application.yml

```<code>spring:
  application:
    name: world-greeting-service
</code>```

WorldGreetingServiceApplication.java

```<code>@RestController
@SpringBootApplication
public class WorldGreetingServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(WorldGreetingServiceApplication.class, args);
    }

    @RequestMapping("/greeting/world")
    public String greetWorld() {
        return "Hello World!";
    }

}
</code>```

Am I missing anything?

答:
Try using,</p>

```<code>mvn spring-boot:run -Drun.jvmArguments='-Dserver.port=8081'
</code>```

Body:
I have a very simple "Hello World" kind of REST api created using Spring Boot that is accessible through http://localhost:8080/greeting/world without any problem.

I would like to start two more instances of this API on ports 8081 and 8082 but not able to do so. It says java.net.BindException: Address already in use: bind

Command Used:

mvn spring-boot:run -Dserver.port=8081

application.yml

spring:
  application:
    name: world-greeting-service

WorldGreetingServiceApplication.java

@RestController
@SpringBootApplication
public class WorldGreetingServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(WorldGreetingServiceApplication.class, args);
    }

    @RequestMapping("/greeting/world")
    public String greetWorld() {
        return "Hello World!";
    }

}

Am I missing anything?

Body:
Try using,

mvn spring-boot:run -Drun.jvmArguments='-Dserver.port=8081'


问:
SQL - Grouping a 3 Column List Issue

I have list of values in a databse. There are many redundancies and I want to get rid of them. As you can see in the list below, dates [10/1/2011 - 7/1/2011) have a value of 0. I can make that into one entry with a start date of 10/1/2011 and an end date of 6/1/2011 and a value of 0 and delete all the other rows. I can do that for all the other similar values as well.

Here is my problem. I did this by writing a query that groups these together and then takes the Min(start date) as the start date and the Max(end date) as the end date. Notice that I have two groups of 0 though. When I group this in the query, the start date is 10/1/2010 and the end date is 2/1/2013. This is a problem elsewhere in my code because whenever it looks for a value at 2/1/2012 it finds 0 but it should be finding .955186.

Any suggestions on how I can write a query to account for this problem?

答:
This is a "gaps-and-islands" problem.

If I assume that the first column is sufficient for defining the groups, then you can use a difference of row_number()s:

```<code>select min(startdate), max(enddate), value
from (select t.*,
             row_number() over (order by startdate) as seqnum,
             row_number() over (partition by value order by startdate) as seqnum_v
      from t
     ) t
group by (seqnum - seqnum_v), value;
</code>```

Title: SQL - Grouping a 3 Column List Issue

Body:
This is a "gaps-and-islands" problem.

If I assume that the first column is sufficient for defining the groups, then you can use a difference of row_number()s:

select min(startdate), max(enddate), value
from (select t.*,
             row_number() over (order by startdate) as seqnum,
             row_number() over (partition by value order by startdate) as seqnum_v
      from t
     ) t
group by (seqnum - seqnum_v), value;


问:
How can I evaluate an integration to a number?
I have some functions set up like this:

```<code>f(x):=1-2**-x$
g(y):=integrate(f(x), x, 0, y)$
</code>```

and evaluated them:

```<code>f(1)$float(%);
g(1)$float(%);
</code>```

but for g(1), I got a symbolic answer instead of a numerical answer. Using float() was an attempt to get a numerical answer but it just turned all of the terms in the integral into floats.

How can I get g(1) as a number?

答:
Why not just do (by the definition of definite integral):

```<code>f(x):=1-2**-x$
gg(x):=''(integrate(f(x), x))$
g(y):=gg(y) - gg(0)$
</code>```

'' (quote-quote) operator is used to force the evaluation of the :='s right hand side before the assignment.

ContentLicense: CC BY-SA 2.5

Body:
I have some functions set up like this:

f(x):=1-2**-x$
g(y):=integrate(f(x), x, 0, y)$

and evaluated them:

f(1)$float(%);
g(1)$float(%);

but for g(1), I got a symbolic answer instead of a numerical answer. Using float() was an attempt to get a numerical answer but it just turned all of the terms in the integral into floats.

How can I get g(1) as a number?

Body:
Why not just do (by the definition of definite integral):

f(x):=1-2**-x$
gg(x):=''(integrate(f(x), x))$
g(y):=gg(y) - gg(0)$

'' (quote-quote) operator is used to force the evaluation of the :='s right hand side before the assignment.


问:
Capturing the output from python script which called through powershell
Currently i have the stuff in place in my TFS like below :

TFS Job calls powershell script1

powershell script1 calls powershell script2 (having module)

Powershell module calls the python script using Start process which returns the standard output through -RedirectStandardOutput. And the same is capturing/returning to TFS.

But the thing is all the output from python script is returning in one go and not able to get the line by line logs to TFS instantly.

Can anyone suggest if there is way to return the output from python script to TFS instantly line by line logs?

答: You'd have to make the Start-Process call asynchronously either using Jobs or Runspaces, and then constantly monitor the job/runspace child session for output to display.</p>


问:
Counting events and testing rxJava
I have following code:

```<code>private AtomicInteger numberOfGeneratedEvents;

@Before
public void setNumberOfGeneratedEvents() {
    numberOfGeneratedEvents = new AtomicInteger(0);
}

@Test
public void eventsShouldAppearDespiteException() {

    ThreadFactory timerThreadFactory = new ThreadFactoryBuilder()
            .setNameFormat("timer-service-%d")
            .build();

    Observable<Long> timerService = Observable
            .interval(1, 1, SECONDS)
            .observeOn(Schedulers.from(Executors.newFixedThreadPool(1, timerThreadFactory)))
            .doOnNext(aLong -> doSomeWork())
            .doOnError(throwable -> doWorkAfterException())
            .timeout(5, TimeUnit.SECONDS)
            .retry();

    timerService.subscribe();

    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    assertThat(numberOfGeneratedEvents.get()).isEqualTo(4);
}

private void doWorkAfterException() {
    System.out.println("Exception happened. This code should do something onError. ");
}

private Boolean doSomeWork() {
    numberOfGeneratedEvents.incrementAndGet();
    System.out.println("Work work. ");
    System.out.println("numberOfGeneratedEvents = " + numberOfGeneratedEvents.get());
    if (Math.random() > 0.5) {
        throw new NullPointerException("Random null pointer inside the work.");
    }
    return true;
}
</code>```

Which translates to following log output:

```<code>Work work.
numberOfGeneratedEvents = 1
Work work.
numberOfGeneratedEvents = 2
Work work.
numberOfGeneratedEvents = 3
Exception happened. This code should do something onError.
Work work.
numberOfGeneratedEvents = 4
Work work.
numberOfGeneratedEvents = 5
Exception happened. This code should do something onError.

Process finished with exit code 0
</code>```

What concerns me the most and what I do not totally understand is the fact, that last assertion in the last line of the test:

```<code>   assertThat(numberOfGeneratedEvents.get()).isEqualTo(4);
</code>```

actually goes green and test passes. The other time when I run it I get 4 as last value of numberOfGeneratedEvents on the console and test goes green too, so that's fine. What is wrong here and where's the randomness? Am I doing something bad with AtomicInteger?

答:
As a workaround which doesn't really explain anything (but works and looks logical) I've toned down the sleep() in test down to 4500ms. This way there are only 4 events emited each time.
Doesn't solve what was happening though, so if anyone could enlight me Ill wait in this thread.

Title: Counting events and testing rxJava

Body:
I have following code:

private AtomicInteger numberOfGeneratedEvents;

@Before
public void setNumberOfGeneratedEvents() {
    numberOfGeneratedEvents = new AtomicInteger(0);
}

@Test
public void eventsShouldAppearDespiteException() {

    ThreadFactory timerThreadFactory = new ThreadFactoryBuilder()
            .setNameFormat("timer-service-%d")
            .build();

    Observable<Long> timerService = Observable
            .interval(1, 1, SECONDS)
            .observeOn(Schedulers.from(Executors.newFixedThreadPool(1, timerThreadFactory)))
            .doOnNext(aLong -> doSomeWork())
            .doOnError(throwable -> doWorkAfterException())
            .timeout(5, TimeUnit.SECONDS)
            .retry();

    timerService.subscribe();

    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    assertThat(numberOfGeneratedEvents.get()).isEqualTo(4);
}

private void doWorkAfterException() {
    System.out.println("Exception happened. This code should do something onError. ");
}

private Boolean doSomeWork() {
    numberOfGeneratedEvents.incrementAndGet();
    System.out.println("Work work. ");
    System.out.println("numberOfGeneratedEvents = " + numberOfGeneratedEvents.get());
    if (Math.random() > 0.5) {
        throw new NullPointerException("Random null pointer inside the work.");
    }
    return true;
}

Which translates to following log output:

Work work.
numberOfGeneratedEvents = 1
Work work.
numberOfGeneratedEvents = 2
Work work.
numberOfGeneratedEvents = 3
Exception happened. This code should do something onError.
Work work.
numberOfGeneratedEvents = 4
Work work.
numberOfGeneratedEvents = 5
Exception happened. This code should do something onError.

Process finished with exit code 0

What concerns me the most and what I do not totally understand is the fact, that last assertion in the last line of the test:

   assertThat(numberOfGeneratedEvents.get()).isEqualTo(4);

actually goes green and test passes. The other time when I run it I get 4 as last value of numberOfGeneratedEvents on the console and test goes green too, so that's fine. What is wrong here and where's the randomness? Am I doing something bad with AtomicInteger?


问:
Trigger Amazon SNS message via Amazon Lambda
I have an Amazon Lambda instance and an Amazon SNS instance. The Lambda code watches for changes in our database and I would like it to make a call to Amazon SNS to send pushes to our users. For example:

When a user on one of our forums gets a new message, the Lambda code recognizes this change every time it is run (every 10 minutes) and should send a push to the user's smartphone via SNS.

I'm running into a wall when it comes to the documentation; Amazon's docs only talk about how to trigger Lambda code via SNS, but not the reverse. Does anyone have an example of how I can accomplish this?

答:
You can use the lambda below to push an SNS message to a user, but you must know what the endpoint ARN is for that user. For example, if in an Android app, when the user logs in you will have the app send a GCM (Google Cloud Messaging) token to your backend (via an API call that triggers a lambda, for example). Your backend, which is connected to GCM, can then use this token to lookup which endpoint ARN corresponds to such user and put that in the lambda below. Alternatively, you can have the app send the endpoint ARN directly to your backend, though I think it might be a bit less secure. Make sure you give IAM permissions to publish to your app via SNS. You can use the lambda below to push the message:

var AWS = require('aws-sdk');
var sns = new AWS.SNS({apiVersion: '2010-03-31'});

exports.handler = (event, context, callback) => {

    console.log(JSON.stringify(event))

var payload = {
"default": "The message string.",
"GCM":"{"+
   "\"notification\":{"+
       "\"body\":\"PUT NOTIFICATION BODY HERE\","+
       "\"title\":\"PUT NOTIFICATION TITLE HERE\""+
   "}"+
"}"
};

  payload = JSON.stringify(payload);

    var params = {
      TargetArn: 'PUT THE ENDPOINT ARN HERE',
      Subject: 'foo2',
      MessageStructure: 'json',
      Message: payload
    }
    sns.publish(params, function(err, data) {
      if (err) console.log(err, err.stack); // an error occurred
      else     console.log(data);           // successful response
    });

};```


问:
How to get the bounding box from a DbGeography MULTIPOINT?
Sorry if the question is not 100% related to SQL Server itself. But I thought it matches the topic close enough to post it here.

I'm using Entity Framework in my ASP.NET Web API project. While creating my POCOs I receive LatLngBounds from the browser client (Google Maps API).

I create a DbGeography (MULTIPOINT) instance from these incoming coordinates that represents my two points to re-create a rectangle.

Now I need the bounding box (polygon) of this MULTIPOINT construct. After some research I thought the STEnvelope function from the SqlGeometry assembly might help on this as I can not find a way to do this with the DbGeography type. Everything looks fine in the code until I try so save the object.

Please see this gist for example code an the error message from EF. See this gist for the generated SQL from EF.

Does it make sense to try it this way, or am I missing something important here and there's a much easier way?

答:
```<code> public static Tuple<double, double, double, double> GetEnvelopeFromPolygon(DbGeography polygon)
    {
        if (polygon == null)
        {
            return new Tuple<double, double, double, double>(0, 0, 0, 0);
        }

        var points = polygon.GetPointsFromPolygon();
        double minLat = double.MaxValue;
        double maxLat = double.MinValue;
        double minLon = double.MaxValue;
        double maxLon = double.MinValue;

        foreach (Tuple<double, double> point in points)
        {
            double lat = point.Item1;
            double lon = point.Item2;
            if (lat < minLat)
            {
                minLat = lat;
            }
            if (lat > maxLat)
            {
                maxLat = lat;
            }
            if (lon < minLon)
            {
                minLon = lon;
            }
            if (lon > maxLon)
            {
                maxLon = lon;
            }

        }

        var res = new Tuple<double, double, double, double>(minLat, maxLat, minLon, maxLon);
        return res;
    }

  public static IEnumerable<Tuple<double, double>> GetPointsFromPolygon(this System.Data.Entity.Spatial.DbGeography geo)
    {
        for (int i = 1; i < geo.PointCount; i++)
        {
            var p = geo.PointAt(i);
            yield return new Tuple<double, double>(p.Latitude.Value, p.Longitude.Value);
        }

        var pFinal = geo.PointAt(1);
        yield return new Tuple<double, double>(pFinal.Latitude.Value, pFinal.Longitude.Value);
    }
</code>```


问:
TensorFlow fails to compile
Getting the following errors which trying to compile TensorFlow from source.
Any thoughts would be helpful.</p>

```<code>bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `cublasGemmEx@libcublas.so.9.0'
bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `cublasZhpmv_v2@libcublas.so.9.0'
bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `cufftExecD2Z@libcufft.so.9.0'
bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `cublasSrotg_v2@libcublas.so.9.0'
bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `cufftExecR2C@libcufft.so.9.0'
bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `cublasSsyrk_v2@libcublas.so.9.0'
bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `cublasDgemm_v2@libcublas.so.9.0'
bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `cufftSetWorkArea@libcufft.so.9.0'
bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `cublasChemm_v2@libcublas.so.9.0'
bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `cublasZher2k_v2@libcublas.so.9.0'
bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `cufftExecC2C@libcufft.so.9.0'
bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `curandSetStream@libcurand.so.9.0'
bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `cublasDrotm_v2@libcublas.so.9.0'
bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `curandSetPseudoRandomGeneratorSeed@libcurand.so.9.0'
</code>```

答:
There seems to be a bug in our build. I was able to reproduce the same on my machine. Looks like the value of LD_LIBRARY_PATH does not always get properly propagated during bazel build. In my case, I was able to successfully build when I used this command:

```<code>bazel build  --config=opt --config=cuda tensorflow/tools/pip_package:build_pip_package --action_env="LD_LIBRARY_PATH=${LD_LIBRARY_PATH}"
</code>```

Title: TensorFlow fails to compile

Body:
Getting the following errors which trying to compile TensorFlow from source.
Any thoughts would be helpful.

bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `cublasGemmEx@libcublas.so.9.0'
bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `cublasZhpmv_v2@libcublas.so.9.0'
bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `cufftExecD2Z@libcufft.so.9.0'
bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `cublasSrotg_v2@libcublas.so.9.0'
bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `cufftExecR2C@libcufft.so.9.0'
bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `cublasSsyrk_v2@libcublas.so.9.0'
bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `cublasDgemm_v2@libcublas.so.9.0'
bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `cufftSetWorkArea@libcufft.so.9.0'
bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `cublasChemm_v2@libcublas.so.9.0'
bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `cublasZher2k_v2@libcublas.so.9.0'
bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `cufftExecC2C@libcufft.so.9.0'
bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `curandSetStream@libcurand.so.9.0'
bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `cublasDrotm_v2@libcublas.so.9.0'
bazel-out/host/bin/_solib_local/_U_S_Stensorflow_Spython_Cgen_Unn_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so: undefined reference to `curandSetPseudoRandomGeneratorSeed@libcurand.so.9.0'

Body:
There seems to be a bug in our build. I was able to reproduce the same on my machine. Looks like the value of LD_LIBRARY_PATH does not always get properly propagated during bazel build. In my case, I was able to successfully build when I used this command:

bazel build  --config=opt --config=cuda tensorflow/tools/pip_package:build_pip_package --action_env="LD_LIBRARY_PATH=${LD_LIBRARY_PATH}"


问:
Get N Largest Date Pandas
I had posted this question and need to expand on the application. I now need to get the N max date for each Vendor:

```<code>#import pandas as pd
#df = pd.read_clipboard()
#df['Insert_Date'] = pd.to_datetime(df['Insert_Date'])

# used in example below
#df2 = df.sort_values(['Vendor','InsertDate']).drop_duplicates(['Vendor'],keep='last')

Vendor  Insert_Date Total
Steph   2017-10-25  2
Matt    2017-10-31  13
Chris   2017-11-03  3
Steve   2017-10-23  11
Chris   2017-10-27  3
Steve   2017-11-01  11
</code>```

If I needed to get the 2nd max date expected output would be:

```<code>Vendor  Insert_Date Total
Steph   2017-10-25  2
Steve   2017-10-23  11
Matt    2017-10-31  13
Chris   2017-10-27  3
</code>```

I can easily get the 2nd max date by using df2 in the example df.loc[~df.index.isin(df2.index)] but if i need to get the 50th max value, that is a lot of dataframe building to use isin()...

I have also tried df.groupby('Vendor')['Insert_Date'].nlargest(N_HERE) which gets me close, but i then need to get the N value for each Vendor.

I have also tried filtering out the df by Vendor:

df.loc[df['Vendor']=='Chris', 'Insert_Date'].nlargest(2)

but if I try to get the second record with df.loc[df['Vendor']=='Chris', 'Insert_Date'].nlargest(2)[2] it returns: Timestamp('2017-11-03 00:00:00'). Instead i need to use df.loc[df['Vendor']=='Chris', 'Insert_Date'].nlargest(2)[1:2]. Why must I use list slicing here and not simply[2]?

In summary? how do I return the N largest date by Vendor?

答:
I will using head (You can pick the top n here I am using 2) and always drop_duplicates by the last.

```<code>df.sort_values('Insert_Date',ascending=False).groupby('Vendor').\
     head(2).drop_duplicates('Vendor',keep='last').sort_index()
Out[609]:
  Vendor Insert_Date  Total
0  Steph  2017-10-25      2
1   Matt  2017-10-31     13
3  Steve  2017-10-23     11
4  Chris  2017-10-27      3
</code>```

Title: Get N Largest Date Pandas

Body:
I had posted this question and need to expand on the application. I now need to get the N max date for each Vendor:

#import pandas as pd
#df = pd.read_clipboard()
#df['Insert_Date'] = pd.to_datetime(df['Insert_Date'])

# used in example below
#df2 = df.sort_values(['Vendor','InsertDate']).drop_duplicates(['Vendor'],keep='last')

Vendor  Insert_Date Total
Steph   2017-10-25  2
Matt    2017-10-31  13
Chris   2017-11-03  3
Steve   2017-10-23  11
Chris   2017-10-27  3
Steve   2017-11-01  11

If I needed to get the 2nd max date expected output would be:

Vendor  Insert_Date Total
Steph   2017-10-25  2
Steve   2017-10-23  11
Matt    2017-10-31  13
Chris   2017-10-27  3

I can easily get the 2nd max date by using df2 in the example df.loc[~df.index.isin(df2.index)] but if i need to get the 50th max value, that is a lot of dataframe building to use isin()...

I have also tried df.groupby('Vendor')['Insert_Date'].nlargest(N_HERE) which gets me close, but i then need to get the N value for each Vendor.

I have also tried filtering out the df by Vendor:

df.loc[df['Vendor']=='Chris', 'Insert_Date'].nlargest(2)

but if I try to get the second record with df.loc[df['Vendor']=='Chris', 'Insert_Date'].nlargest(2)[2] it returns: Timestamp('2017-11-03 00:00:00'). Instead i need to use df.loc[df['Vendor']=='Chris', 'Insert_Date'].nlargest(2)[1:2]. Why must I use list slicing here and not simply[2]?

In summary? how do I return the N largest date by Vendor?

Body:
I will using head (You can pick the top n here I am using 2) and always drop_duplicates by the last.

df.sort_values('Insert_Date',ascending=False).groupby('Vendor').\
     head(2).drop_duplicates('Vendor',keep='last').sort_index()
Out[609]:
  Vendor Insert_Date  Total
0  Steph  2017-10-25      2
1   Matt  2017-10-31     13
3  Steve  2017-10-23     11
4  Chris  2017-10-27      3


答:
I like @COLDSPEED's answer as its more direct. Here is one using nlargest which involves an intermediate step of creating nthlargest column</p>

```<code>n = 2
df1['nth_largest'] = df1.groupby('Vendor').Insert_Date.transform(lambda x: x.nlargest(n).min())
df1.drop_duplicates(subset = ['Vendor', 'nth_largest']).drop('Insert_Date', axis = 1)

    Vendor  Total   nth_largest
0   Steph   2   2017-10-25
1   Matt    13  2017-10-31
2   Chris   3   2017-10-27
3   Steve   11  2017-10-23
</code>```

Title: Get N Largest Date Pandas

Body:
I like @COLDSPEED's answer as its more direct. Here is one using nlargest which involves an intermediate step of creating nthlargest column

n = 2
df1['nth_largest'] = df1.groupby('Vendor').Insert_Date.transform(lambda x: x.nlargest(n).min())
df1.drop_duplicates(subset = ['Vendor', 'nth_largest']).drop('Insert_Date', axis = 1)

    Vendor  Total   nth_largest
0   Steph   2   2017-10-25
1   Matt    13  2017-10-31
2   Chris   3   2017-10-27
3   Steve   11  2017-10-23


问:
How to use SQL Joins and Selects to get results from a third table that matches the first two?
I have a Join statement on two tables(Table 1 and 2), which returns the City and State. I have another table(Table 3) which contains columns like Name, City, State, Country. I want to fetch all the rows from Table 3 whose City and State Columns matches with the rows of the Join result.

```<code>Select * from 3rdTable where City='' AND State='';
</code>```

Result from Join is like

```<code> - City | State
 - A    | B
 - C    | D
 - E    | F
</code>```

Example Result if only 1 row of the 3rd table matches

```<code> - C    |  D
</code>```

How can this be done?

答:
Just join in the 3rd table...

IF we assume table1 has both city and state in it...

```<code>SELECT A.City, A.State
FROM Table1 A
INNER JOIN table2 B
 on A.PK = B.A_FK
INNER JOIN table3 C
  on A.City = C.City
 and A.State = C.State
</code>```

This is the nature of an inner join: Include all rows from all tables where the joined data matches.

If you use  an OUTER join (left, right, full outer) then you get all records from one table and only those that match in the others, or full outer all records from all tables aligned where they match.

Body:
I have a Join statement on two tables(Table 1 and 2), which returns the City and State. I have another table(Table 3) which contains columns like Name, City, State, Country. I want to fetch all the rows from Table 3 whose City and State Columns matches with the rows of the Join result.

Select * from 3rdTable where City='' AND State='';

Result from Join is like

 - City | State
 - A    | B
 - C    | D
 - E    | F

Example Result if only 1 row of the 3rd table matches

 - C    |  D

How can this be done?

Body:
Just join in the 3rd table...

IF we assume table1 has both city and state in it...

SELECT A.City, A.State
FROM Table1 A
INNER JOIN table2 B
 on A.PK = B.A_FK
INNER JOIN table3 C
  on A.City = C.City
 and A.State = C.State

This is the nature of an inner join: Include all rows from all tables where the joined data matches.

If you use  an OUTER join (left, right, full outer) then you get all records from one table and only those that match in the others, or full outer all records from all tables aligned where they match.


问:
Treat .php File as Root Folder
So right now I have a index.php file that acts as an API in the root of a subdomain.

So if you go to http://some.domainname.com/index.php/items/ for example you get a response.
However if you go to http://some.domainname.com/items/ you get a 404 error.

I'm assuming there is some .htaccess rewrite command I can add to make this work but I haven't had any luck finding it.

答:
Here is an example based on how Magento does it:

```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
</IfModule>
</code>```

It will effectively remove the index.php from your urls, but it won't stop anyone from accessing a file that actually exists, like www.example.com/i-exist.php

Note:
This is specifically geared toward a site whose urls alway end with a trailing slash (/), like www.example.com/index.php/somepage/.  This is set with the RewriteBase / line.

Title: Treat .php File as Root Folder

Body:
Here is an example based on how Magento does it:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
</IfModule>

It will effectively remove the index.php from your urls, but it won't stop anyone from accessing a file that actually exists, like www.example.com/i-exist.php

Note:
This is specifically geared toward a site whose urls alway end with a trailing slash (/), like www.example.com/index.php/somepage/.  This is set with the RewriteBase / line.


问:
interface Builder Storyboard Compiler Error - exit 255 - What this error means?
I'm having this error and it came from nowhere. The compiler was working well until last week. My compiler is taking a lot of time to compile the code and almost all of the times are returning me this error.
I've been having a lot of trouble after the iOS 11 was release.
Do you know what it means?

I have Xcode9 and I'm asking if it's a problem with the new version or something like else. Also I don't know how to fix this, since I was searching for this answer this last 5 days with no success.

答:
After cleaning the project and derived data, try to uncheck the following option:</p>

```<code>Xcode->Preferences->General->Issues->"Show live issues"
</code>```

Body:
After cleaning the project and derived data, try to uncheck the following option:

Xcode->Preferences->General->Issues->"Show live issues"


问:
How to put an AVD (emulator) into OFFLINE mode?
I would like to test the behavior of my application when the user is in a no-signal zone or when his phone is in flight mode.

-> How do I put an Android Virtual Device into offline mode (where no connection to the internet is possible) ?

I have tried the following:

Activating flight mode via the AVD settings: surprisingly, this does NOT work (browsing  the internet is still possible in flight mode!)

Disabling the network connection on my PC: this obviously works, but is not satisfactory as I need Internet when I am testing my app

答: I'm seeing all the same problems.  DDMS doesn't fully kill it.  Neither does F8.  And neither does turning on airplane mode inside the emulator.  We should all probably star this issue someone logged in 2009.</p>


问:
Match based on a vector in R
Let's say we have a dataframe that contains individuals that are part of a group, e.g.: in the first column an ID, in the second column a time indicator, and in the third column are the ID's of the group members.

```<code>Data <- data.frame(TICKER = rep(rep(c(1, 2, 3), each = 3), 2),
               TIME = c(rep(2012, 9), rep(2013, 9)),
               PEER = c(2, 500, 503,
                        1, 3, 504,
                        507, 508, 2,
                        2, 500, 503,
                        1, 3, 504,
                        507, 508, 509))
</code>```

What I would like to achieve is that I get a fourth column with indicators that indicate if individuals have each other in the same group. That is, the following output:

```<code>ID    TIME    PEER    INDICATOR
1     2012    2       1
1     2012    500     0
1     2012    503     0
2     2012    1       1
2     2012    3       1
2     2012    504     0
3     2012    507     0
3     2012    508     0
3     2012    2       1
1     2013    2       1
1     2013    500     0
1     2013    503     0
2     2013    1       1
2     2013    3       0 [since individual 3 does not have individual 2 anymore]
2     2013    504     0
3     2013    507     0
3     2013    508     0
3     2013    509     0
</code>```

What would be the easiest way to achieve this?

Thanks :)

Title: Match based on a vector in R

Body:
Let's say we have a dataframe that contains individuals that are part of a group, e.g.: in the first column an ID, in the second column a time indicator, and in the third column are the ID's of the group members.

Data <- data.frame(TICKER = rep(rep(c(1, 2, 3), each = 3), 2),
               TIME = c(rep(2012, 9), rep(2013, 9)),
               PEER = c(2, 500, 503,
                        1, 3, 504,
                        507, 508, 2,
                        2, 500, 503,
                        1, 3, 504,
                        507, 508, 509))

What I would like to achieve is that I get a fourth column with indicators that indicate if individuals have each other in the same group. That is, the following output:

ID    TIME    PEER    INDICATOR
1     2012    2       1
1     2012    500     0
1     2012    503     0
2     2012    1       1
2     2012    3       1
2     2012    504     0
3     2012    507     0
3     2012    508     0
3     2012    2       1
1     2013    2       1
1     2013    500     0
1     2013    503     0
2     2013    1       1
2     2013    3       0 [since individual 3 does not have individual 2 anymore]
2     2013    504     0
3     2013    507     0
3     2013    508     0
3     2013    509     0

What would be the easiest way to achieve this?

Thanks :)

Body:
Here's a quick two-liner trick:

row_match <- apply(Data, 1, function(dr) paste0(sort(dr), collapse="_"))

Data$INDICATOR <- as.numeric(duplicated(row_match) | duplicated(row_match, fromLast = T))

> Data
   TICKER TIME PEER INDICATOR
1       1 2012    2         1
2       1 2012  500         0
3       1 2012  503         0
4       2 2012    1         1
5       2 2012    3         1
6       2 2012  504         0
7       3 2012  507         0
8       3 2012  508         0
9       3 2012    2         1
10      1 2013    2         1
11      1 2013  500         0
12      1 2013  503         0
13      2 2013    1         1
14      2 2013    3         0
15      2 2013  504         0
16      3 2013  507         0
17      3 2013  508         0
18      3 2013  509         0


问:
Visual Studio Code - unable to attach debugger to remote Node.js application
here is my debug configuration :

```<code>{
    "type": "node",
    "request": "attach",
    "name": "testServer",
    "address": "test.server.ip",
    "port": 5858,
    "localRoot": "${workspaceRoot}/test/server",
    "remoteRoot": "~/App/test/server"
}
</code>```

I have started remote application in debug mode successfully by using below command

```<code>node --debug app
</code>```

Then I start VS Code debugger using testServer configuration. it print error:

```<code>Debugging with legacy protocol because Node.js version could not be determined (Error: timeout)
</code>```

I am using VS Code version 1.16.1 on macOS sierra.

I guess it's not able to connect remote server because it's secured by SSH. But I can't see any configuration related to SSH in VS Code debugger's configuration.

I have already gone through some articles and issues like this
 andthis, but no help.

Thanks for any help.

答:
You'll need to start the remote application, and tell node to expose the port remotely with the following command:</p>

```<code>node app --inspect=0.0.0.0:5858
</code>```

Body:
here is my debug configuration :

{
    "type": "node",
    "request": "attach",
    "name": "testServer",
    "address": "test.server.ip",
    "port": 5858,
    "localRoot": "${workspaceRoot}/test/server",
    "remoteRoot": "~/App/test/server"
}

I have started remote application in debug mode successfully by using below command

node --debug app

Then I start VS Code debugger using testServer configuration. it print error:

Debugging with legacy protocol because Node.js version could not be determined (Error: timeout)

I am using VS Code version 1.16.1 on macOS sierra.

I guess it's not able to connect remote server because it's secured by SSH. But I can't see any configuration related to SSH in VS Code debugger's configuration.

I have already gone through some articles and issues like this
 andthis, but no help.

Thanks for any help.

Body:
You'll need to start the remote application, and tell node to expose the port remotely with the following command:

node app --inspect=0.0.0.0:5858


问:
Angularjs Filter Table contents based on a property
I am getting into some angular development and I am building a very simple example, but somehow I am stuck... (Yes, yes I know angular 5 is out and I should't be doing it with angularjs, but I am just interested to compare the different approaches)

So my application has a simple Car object with an id, name and category.
The categories are exactly 3 and based on them I am showing 3 tabs and based on the currently selected tab, I add a car to this particular category.

Here is a screenshot:

So while the adding and removal work fine, the displaying/filtering of cars based on the category doesn't and I am not sure what is the right approach here.

My goal is that when I click on a 'tab', then I filter only the cars from that category.

This is part of my simple controller:

```<code>function CarController($scope, id, CarService) {
    $scope.allCars = [];

    $scope.name = '';
    $scope.currentCategory = 'Sport';
    $scope.categories = ['Sport', 'Luxury', 'Normal'];

    $scope.addCar = addCar;
    $scope.deleteCar = deleteCar;

    $scope.setCurrentCategoryItem = function (item) {
        $scope.currentCategory = item;
    };

function addCar() {
        CarService.addCar($scope.name, $scope.currentCategory);
        $scope.name = '';
    }
</code>```

Here I have a simple function that is responsible for persisting the data:

```<code>function addCar(name, category, callback) {
        callback = callback || angular.noop;
        var Car = ResourceService.getResource(url, id);

        var newCar = new Car();
        newCar.name = name;
        newCar.category = category;
        newCar.$save(callback);
    }
</code>```

And here is my html template:

```<code><div class="row">
<div class="col-xs-12">
    <h1>Cars</h1>
</div>
<div class="tabbable tabs-below">
    <ul class="nav nav-tabs">
        <li ng-repeat="category in categories" ng-class="{active: category == currentCategory}">
            <a href="" ng-click="setCurrentCategoryItem(category)">{{category}}</a>
        </li>
    </ul>

    <div id="{{currentCategory}}" class="tab-content">

    <hr/>
        <div class="tab-pane active" role="tabpanel">
            <div class="row">
                <div class="col-xs-12">
                    <form ng-submit="addCar()" novalidate name="form">
                        <div class="alert alert-danger" ng-show="form.name.$error.notIn">
                            No duplicates allowed!
                        </div>

                        <div class="row">
                            <div class="col-xs-9">
                                <fieldset class="form-group">
                                    <input type="text" class="form-control" placeholder={{currentCategory}}
                                           ng-model="name" required name="name"
                                           not-in="allCars"/>
                                </fieldset>
                            </div>
                            <div class="col-xs-3">
                                <button class="btn btn-success btn-block" type="submit"
                                        data-description="submitLink"
                                        ng-disabled="form.name.$pristine|| form.name.$error.required || form.name.$error.notIn">
                                    Add
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <table class="table table-striped">
                <tr data-ng-repeat="car in allCars">
                    <td>{{car.name}}</td>
                    <td class="text-right">
                        <button class="btn btn-danger" ng-click="deleteItem(car)">
                            <span class="glyphicon glyphicon-remove"></span>
                        </button>
                    </td>
                </tr>
            </table>
        </div>
    </div>
</div>
</code>```

答:
```<code>           <tr data-ng-repeat="car in allCars | filter: category">
                <td>{{car.name}}</td>
                <td class="text-right">
                    <button class="btn btn-danger" ng-click="deleteItem(car)">
                        <span class="glyphicon glyphicon-remove"></span>
                    </button>
                </td>
            </tr>
</code>```

Use the $filter filter it is automatically used when angular parses the text in an ng-repeat (or anywhere you're passing a string or array really and angular is parsing it).

Example above just filters any fields for the value supplied, the below example specifies some property called "category" for the currentCategory (on scope) value.

```<code>           <tr data-ng-repeat="car in allCars | filter: {category: currentCategory}">
                <td>{{car.name}}</td>
                <td class="text-right">
                    <button class="btn btn-danger" ng-click="deleteItem(car)">
                        <span class="glyphicon glyphicon-remove"></span>
                    </button>
                </td>
            </tr>
</code>```

Body:
I am getting into some angular development and I am building a very simple example, but somehow I am stuck... (Yes, yes I know angular 5 is out and I should't be doing it with angularjs, but I am just interested to compare the different approaches)

So my application has a simple Car object with an id, name and category.
The categories are exactly 3 and based on them I am showing 3 tabs and based on the currently selected tab, I add a car to this particular category.

Here is a screenshot:

So while the adding and removal work fine, the displaying/filtering of cars based on the category doesn't and I am not sure what is the right approach here.

My goal is that when I click on a 'tab', then I filter only the cars from that category.

This is part of my simple controller:

function CarController($scope, id, CarService) {
    $scope.allCars = [];

    $scope.name = '';
    $scope.currentCategory = 'Sport';
    $scope.categories = ['Sport', 'Luxury', 'Normal'];

    $scope.addCar = addCar;
    $scope.deleteCar = deleteCar;

    $scope.setCurrentCategoryItem = function (item) {
        $scope.currentCategory = item;
    };

function addCar() {
        CarService.addCar($scope.name, $scope.currentCategory);
        $scope.name = '';
    }

Here I have a simple function that is responsible for persisting the data:

function addCar(name, category, callback) {
        callback = callback || angular.noop;
        var Car = ResourceService.getResource(url, id);

        var newCar = new Car();
        newCar.name = name;
        newCar.category = category;
        newCar.$save(callback);
    }

And here is my html template:

Cars

            {{category}}

                    <form ng-submit="addCar()" novalidate name="form">

                            No duplicates allowed!

                                <fieldset class="form-group">
                                    <input type="text" class="form-control" placeholder={{currentCategory}}
                                           ng-model="name" required name="name"
                                           not-in="allCars"/>
                                </fieldset>

                                <button class="btn btn-success btn-block" type="submit"
                                        data-description="submitLink"
                                        ng-disabled="form.name.$pristine|| form.name.$error.required || form.name.$error.notIn">
                                    Add
                                </button>

                    </form>

                    {{car.name}}

                        <button class="btn btn-danger" ng-click="deleteItem(car)">

                        </button>

Body:
           <tr data-ng-repeat="car in allCars | filter: category">
                <td>{{car.name}}</td>
                <td class="text-right">
                    <button class="btn btn-danger" ng-click="deleteItem(car)">
                        <span class="glyphicon glyphicon-remove"></span>
                    </button>
                </td>
            </tr>

Use the $filter filter it is automatically used when angular parses the text in an ng-repeat (or anywhere you're passing a string or array really and angular is parsing it).

Example above just filters any fields for the value supplied, the below example specifies some property called "category" for the currentCategory (on scope) value.

           <tr data-ng-repeat="car in allCars | filter: {category: currentCategory}">
                <td>{{car.name}}</td>
                <td class="text-right">
                    <button class="btn btn-danger" ng-click="deleteItem(car)">
                        <span class="glyphicon glyphicon-remove"></span>
                    </button>
                </td>
            </tr>


答:
It is a gap and islands problem. You may use the following query (using SQL Server syntax, however, it can be easily altered).

```<code>select min(startdate) startDate, max(enddate) endDate, value
from
(
  select *,
         row_number() over (partition by value order by startDate) - (year(startDate) * 12) - month(startDate) grp
  from data
) t
group by value, grp
order by startDate
</code>```

It is using just one row_number() which may be better than two since the DBMS does not have to pass the table twice to generate the sequences.

Title: SQL - Grouping a 3 Column List Issue

Body:
I have list of values in a databse. There are many redundancies and I want to get rid of them. As you can see in the list below, dates [10/1/2011 - 7/1/2011) have a value of 0. I can make that into one entry with a start date of 10/1/2011 and an end date of 6/1/2011 and a value of 0 and delete all the other rows. I can do that for all the other similar values as well.

Here is my problem. I did this by writing a query that groups these together and then takes the Min(start date) as the start date and the Max(end date) as the end date. Notice that I have two groups of 0 though. When I group this in the query, the start date is 10/1/2010 and the end date is 2/1/2013. This is a problem elsewhere in my code because whenever it looks for a value at 2/1/2012 it finds 0 but it should be finding .955186.

Any suggestions on how I can write a query to account for this problem?

Body:
It is a gap and islands problem. You may use the following query (using SQL Server syntax, however, it can be easily altered).

select min(startdate) startDate, max(enddate) endDate, value
from
(
  select *,
         row_number() over (partition by value order by startDate) - (year(startDate) * 12) - month(startDate) grp
  from data
) t
group by value, grp
order by startDate

It is using just one row_number() which may be better than two since the DBMS does not have to pass the table twice to generate the sequences.


问:
JavaScript: How Can I Make A Var "Array" Work?
Is there a way to name a var using a sort of "Array?" My code is this:

```<code>for(var i = 0; i < (getHorizontalSquares * getVerticalSquares); i++){
    var Square[i] = document.createElement("div");
    Square[i].style.position = "relative";
    Square[i].style.float = "left";
    Square[i].style.width = "50px";
    Square[i].style.height = "50px";
    Square[i].id = "square" + (i + 1);
    for(var ii = 0; ii < 6; ii++){
        var TestColor = TestColorArray[Math.round(Math.random()*(TestColorArray.length - 1))];
        getTestColor += TestColor;
    }
    Square[i].style.backgroundColor = "#" + getTestColor;
    SquareCont.appendChild(Square[i]);
}
</code>```

I know my code doesn't work, but I want to implement the same idea so I can get a result of this:

```<code>var Square1...
var Square2...
var Square3...
var Square4...
var Square5...
etc
</code>```

I also tried doing a "Concentration" var, but it didn't work. How do I do this so the document doesn't append the same square multiple times?

答:
Your declaration syntax is not valid. But, I think the larger point you are trying to get to is to be able to populate an array with dynamically created elements and that you can do:

var squares = [];  // Array must exist before you can populate it

var testColorArray = ["green", "yellow", "blue", "orange", "silver"];
var getTestColor = null;

function makeSquares(count){

  for(var i = 0; i < count; i++){
    // Just create the element and configure it. No need to worry about the array yet
    var element = document.createElement("div");
    element.style.float = "left";
    element.style.width = "75px";
    element.style.height = "75px";
    element.id = "square" + (i + 1);
    element.style.backgroundColor = testColorArray[Math.floor(Math.random()* testColorArray.length)];
    element.textContent = element.id;
    squareCont.appendChild(element);

    // Now, add the element to the arrray
    squares.push(element);
  }

  // Test:
  console.log(squares);
}

makeSquares(10);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="squareCont"></div></code>```

Body:
Is there a way to name a var using a sort of "Array?" My code is this:

for(var i = 0; i < (getHorizontalSquares * getVerticalSquares); i++){
    var Square[i] = document.createElement("div");
    Square[i].style.position = "relative";
    Square[i].style.float = "left";
    Square[i].style.width = "50px";
    Square[i].style.height = "50px";
    Square[i].id = "square" + (i + 1);
    for(var ii = 0; ii < 6; ii++){
        var TestColor = TestColorArray[Math.round(Math.random()*(TestColorArray.length - 1))];
        getTestColor += TestColor;
    }
    Square[i].style.backgroundColor = "#" + getTestColor;
    SquareCont.appendChild(Square[i]);
}

I know my code doesn't work, but I want to implement the same idea so I can get a result of this:

var Square1...
var Square2...
var Square3...
var Square4...
var Square5...
etc

I also tried doing a "Concentration" var, but it didn't work. How do I do this so the document doesn't append the same square multiple times?

Body:
Your declaration syntax is not valid. But, I think the larger point you are trying to get to is to be able to populate an array with dynamically created elements and that you can do:

var squares = [];  // Array must exist before you can populate it

var testColorArray = ["green", "yellow", "blue", "orange", "silver"];
var getTestColor = null;

function makeSquares(count){

  for(var i = 0; i < count; i++){
    // Just create the element and configure it. No need to worry about the array yet
    var element = document.createElement("div");
    element.style.float = "left";
    element.style.width = "75px";
    element.style.height = "75px";
    element.id = "square" + (i + 1);
    element.style.backgroundColor = testColorArray[Math.floor(Math.random()* testColorArray.length)];
    element.textContent = element.id;
    squareCont.appendChild(element);

    // Now, add the element to the arrray
    squares.push(element);
  }

  // Test:
  console.log(squares);
}

makeSquares(10);

<div id="squareCont"></div>


问:
Problem with SELECT INTO using local variables
I need to create an SQL query to insert some data into a table based on the results of a SELECT query into a local variable.  My DB platform is MySQL 5.1, but I don't think that should make a difference here.  Basically, what I want to do is:

```<code>SELECT id INTO var_name FROM table1 WHERE some_column='something' LIMIT 1;
INSERT INTO table2 (`number`) VALUES (@var_name);
</code>```

I can't get past the first statement, though, as I get the error "Undeclared variable var_name".  I've also tried putting the statement in a BEGIN/END block, and a stored procedure, but then I encounter other errors which state only that there is an error on the SELECT line.  What am I doing wrong?

答:
Try </p>

```<code>INSERT INTO table2 (`number`)
SELECT id FROM table1 WHERE some_column='something' LIMIT 1
</code>```

OwnerDisplayName: sqook

Body:
I need to create an SQL query to insert some data into a table based on the results of a SELECT query into a local variable.  My DB platform is MySQL 5.1, but I don't think that should make a difference here.  Basically, what I want to do is:

SELECT id INTO var_name FROM table1 WHERE some_column='something' LIMIT 1;
INSERT INTO table2 (`number`) VALUES (@var_name);

I can't get past the first statement, though, as I get the error "Undeclared variable var_name".  I've also tried putting the statement in a BEGIN/END block, and a stored procedure, but then I encounter other errors which state only that there is an error on the SELECT line.  What am I doing wrong?

LastEditorDisplayName: John MacIntyre

Body:
Try

INSERT INTO table2 (`number`)
SELECT id FROM table1 WHERE some_column='something' LIMIT 1

OwnerDisplayName: Tomalak


问:
What unit test to write for a class using generics in Java?
Taking the very specific example of the JpaDao class defined in this article:

```<code>public abstract class JpaDao<K, E> implements Dao<K, E> {
    protected Class<E> entityClass;

    @PersistenceContext
    protected EntityManager entityManager;

    public JpaDao() {
        ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
        this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[1];
    }

    public void persist(E entity) { entityManager.persist(entity); }

    public void remove(E entity) { entityManager.remove(entity); }

    public E findById(K id) { return entityManager.find(entityClass, id); }
}
</code>```

would it be best to write unit tests for all the existing entities in the application (Order, Customer, Book, etc.), or would it be acceptable to write unit tests for just one entity, as hinted by this other question?  Are there any best practice regarding unit testing java classes using generics?

答: Like BalusC, I recommend testing concrete implementations.  The reason for this is that it conforms to the "You Ain't Gonna Need It" principle.  Add just enough tests so that the use case you're trying to implement passes.  Then, as you add more use cases, add more unit tests.</p>

Body:
Taking the very specific example of the JpaDao class defined in this article:

public abstract class JpaDao<K, E> implements Dao<K, E> {
    protected Class<E> entityClass;

    @PersistenceContext
    protected EntityManager entityManager;

    public JpaDao() {
        ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
        this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[1];
    }

    public void persist(E entity) { entityManager.persist(entity); }

    public void remove(E entity) { entityManager.remove(entity); }

    public E findById(K id) { return entityManager.find(entityClass, id); }
}

would it be best to write unit tests for all the existing entities in the application (Order, Customer, Book, etc.), or would it be acceptable to write unit tests for just one entity, as hinted by this other question?  Are there any best practice regarding unit testing java classes using generics?


问:
Should I error-check Close() on a response body?
The docs for net/http have the following example:

```<code>resp, err := http.Get("http://example.com/")
if err != nil {
    panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Printf("%s", body)
</code>```

Close returns an error, but it is not checked. Is there something I'm missing here? The importance of checking every error is frequently emphasized in go, but I see this defer resp.Body.Close() pattern a lot with no error checks.

答:
To add to @Mihailo option #2, call it option #2.1
Define function dclose() like so:

```<code>func dclose(c io.Closer) {
    if err := c.Close(); err != nil {
        log.Fatal(err)
    }
}
</code>```

use like so:

```<code>defer dclose(resp.Body)
</code>```

Also in your code the check for err!=nil can declare:

```<code>func errcheck(err error) {
    if err != nil {
        log.Fatal(err)
    }
}
</code>```

then use:

```<code>errcheck(err)
</code>```

then your code becomes:

```<code>resp, err := http.Get("http://example.com/")
errcheck(err)
defer dclose(resp.Body)

body, err := ioutil.ReadAll(resp.Body)
errcheck(err)

fmt.Printf("%s", string(body))
</code>```

IMHO a little cleaner perhaps? But I'll wait for the go aficionado's to correct me and highlight drawbacks.

EDIT

Thanks! @RayfenWindspear

Do replace log.Fatal(err) with log.Println(err) to avoid unnecessary panic.

EDIT2

dclose() to avoid confusion with go close()

Have fun!

Body:
The docs for net/http have the following example:

resp, err := http.Get("http://example.com/")
if err != nil {
    panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Printf("%s", body)

Close returns an error, but it is not checked. Is there something I'm missing here? The importance of checking every error is frequently emphasized in go, but I see this defer resp.Body.Close() pattern a lot with no error checks.

Body:
To add to @Mihailo option #2, call it option #2.1
Define function dclose() like so:

func dclose(c io.Closer) {
    if err := c.Close(); err != nil {
        log.Fatal(err)
    }
}

use like so:

defer dclose(resp.Body)

Also in your code the check for err!=nil can declare:

func errcheck(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

then use:

errcheck(err)

then your code becomes:

resp, err := http.Get("http://example.com/")
errcheck(err)
defer dclose(resp.Body)

body, err := ioutil.ReadAll(resp.Body)
errcheck(err)

fmt.Printf("%s", string(body))

IMHO a little cleaner perhaps? But I'll wait for the go aficionado's to correct me and highlight drawbacks.

EDIT

Thanks! @RayfenWindspear

Do replace log.Fatal(err) with log.Println(err) to avoid unnecessary panic.

EDIT2

dclose() to avoid confusion with go close()

Have fun!


问:
what is the recommended way for using the Kotlin double-bang for nullable class member
In kotlin if the variable is nullable the kotlin will ask for either using !! or check the null before using it.
In the case of having nullable class member, inside the class anywhere refereeing this member kotlin will warn for checking the nullable.

```<code>class ClassWithNullableMemebr {
      Var nullableMember: OtherClass? = null;

      constructor (obj: OtherClass) {
          nullableMember = obj
      }
      fun foo() {
          nullableMember!!.doSomething()
      }
      fun getTheOtherClassMember : OtherClass {
          return nullableMember!!
      }
 }
</code>```

If the nullableMember is guaranteed to initialized in constructor, how to avoid the use of !!.

In Java or other language they could check null once and throw if by design the member should never be null. Then inside the class the member will be just be referenced without worry.

Someone suggested do

```<code>if (nullableMember != null) {
    nullableMember!!.doSomething()
}
</code>```

This will still need the !! even after the check, and it makes the code looks not pretty.

For this case really using ?. is not much different than using !! since the nullableMember is assigned in the constructor, and the function return it can not avoid the !!.

I think if this nullableMember is guaranteed not null after instantiate the class the using !! shouldn't be considered to be bad coding style. And there is no other way to avoid it.

Does anyone have suggestion to avoid the use of '!!' in the case like this?

答:
If the nullableMember is guaranteed to initialized in constructor

In your case it isn't. It will be initialized if you call the secondary constructor, but you also have the primary, parameterless constructor which initializes it to null.

And if it is guaranteed to be initialized to non-null in the constructor, then as Oliver's comment says, it shouldn't be nullable! And it should be val if it's only set in the constructor (including secondary ones) or init blocks.

I.e. this class should be simplified to

```<code>class ClassWithNullableMemebr(val nullableMember: OtherClass) {
    fun foo() {
        nullableMember.doSomething()
    }
}
</code>```

Body:
In kotlin if the variable is nullable the kotlin will ask for either using !! or check the null before using it.
In the case of having nullable class member, inside the class anywhere refereeing this member kotlin will warn for checking the nullable.

class ClassWithNullableMemebr {
      Var nullableMember: OtherClass? = null;

      constructor (obj: OtherClass) {
          nullableMember = obj
      }
      fun foo() {
          nullableMember!!.doSomething()
      }
      fun getTheOtherClassMember : OtherClass {
          return nullableMember!!
      }
 }

If the nullableMember is guaranteed to initialized in constructor, how to avoid the use of !!.

In Java or other language they could check null once and throw if by design the member should never be null. Then inside the class the member will be just be referenced without worry.

Someone suggested do

if (nullableMember != null) {
    nullableMember!!.doSomething()
}

This will still need the !! even after the check, and it makes the code looks not pretty.

For this case really using ?. is not much different than using !! since the nullableMember is assigned in the constructor, and the function return it can not avoid the !!.

I think if this nullableMember is guaranteed not null after instantiate the class the using !! shouldn't be considered to be bad coding style. And there is no other way to avoid it.

Does anyone have suggestion to avoid the use of '!!' in the case like this?

Body:
If the nullableMember is guaranteed to initialized in constructor

In your case it isn't. It will be initialized if you call the secondary constructor, but you also have the primary, parameterless constructor which initializes it to null.

And if it is guaranteed to be initialized to non-null in the constructor, then as Oliver's comment says, it shouldn't be nullable! And it should be val if it's only set in the constructor (including secondary ones) or init blocks.

I.e. this class should be simplified to

class ClassWithNullableMemebr(val nullableMember: OtherClass) {
    fun foo() {
        nullableMember.doSomething()
    }
}


问:
How can I convert a string into a variable name in C#?
I have four pre-defined input keywords. (e.g num1, num2, etc) Based on these keywords the user will define a formula in a textbox.
Example:
num1 + num2 * num3 * (num3-num1)

Since this input will be taken from a textbox it will be a string.
How can convert these keywords from string to the variable name and execute the formula in my code?

I didn't find any suitable answer for this in other threads.

Any help is appreciated. Thanks

答:
You could do that by building a corresponding expression tree:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/expression-trees/</p>


问:
Java.lang.IllegalStateException: attempt to re-open an already-closed?
I got error from my Sqlite Android. I have code like this:

```<code>public int UpdatePhotoUser(String foto_user, int metode) {

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        int update = 0;

        if (metode == 1) {
            values.put(Variabel.KEY_USER_PHOTO, foto_user);
            try {
                update = db.update(
                        Variabel.TABLE_USER,
                        values, null, null);
            } catch (android.database.sqlite.SQLiteException e) {

            }
        } else if (metode == 2 && getUserDetails(Variabel.KEY_USER_PHOTO).equals(foto_user)) {
            values.put(Variabel.KEY_USER_PHOTO, "");
            try {
                update = db.update(
                        Variabel.TABLE_USER,
                        values, null, null);
            } catch (android.database.sqlite.SQLiteException e) {

            }
        }

        db.close();
        return update;
    }
</code>```

And I have Error at last line:

```<code>update = db.update(
                            Variabel.TABLE_USER,
                            values, null, null);
</code>```

This the eror:

```<code>Java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/data/com.ad.kamardagang.newseditor/databases/DB_KAMAR_DAGANG
            at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)
            at android.database.sqlite.SQLiteDatabase.updateWithOnConflict(SQLiteDatabase.java:1545)
            at android.database.sqlite.SQLiteDatabase.update(SQLiteDatabase.java:1522)
            at com.ad.kamardagang.newseditor.database_content.DatabaseHandler.UpdatePhotoUser(DatabaseHandler.java:613)
            at com.ad.kamardagang.newseditor.fragments.PhotoUserFragment.removeRespone(PhotoUserFragment.java:985)
            at com.ad.kamardagang.newseditor.fragments.PhotoUserFragment.access$600(PhotoUserFragment.java:62)
            at com.ad.kamardagang.newseditor.fragments.PhotoUserFragment$12.onResponse(PhotoUserFragment.java:879)
            at com.ad.kamardagang.newseditor.fragments.PhotoUserFragment$12.onResponse(PhotoUserFragment.java:875)
            at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
            at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
            at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
</code>```

edited:
exmple I call with :

```<code>db = new DatabaseHandler(getActivity());
 db.UpdatePhotoUser("http://a.png",1);
</code>```

when. I first call metode UpdatePhotoUser(String foto_user, int metode), but on second call its error. so how to fix it ?

答:
if anyone has similar issue try this it will resolve issue</p>

```<code>if (db == null || !db.isOpen())
{
  dbHelper = new MySQLiteHelper(this); //u can omit this but need to have an extra check dbHelper!=null
  db = dbHelper.getWritableDatabase();
}
</code>```

Body:
I got error from my Sqlite Android. I have code like this:

public int UpdatePhotoUser(String foto_user, int metode) {

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        int update = 0;

        if (metode == 1) {
            values.put(Variabel.KEY_USER_PHOTO, foto_user);
            try {
                update = db.update(
                        Variabel.TABLE_USER,
                        values, null, null);
            } catch (android.database.sqlite.SQLiteException e) {

            }
        } else if (metode == 2 && getUserDetails(Variabel.KEY_USER_PHOTO).equals(foto_user)) {
            values.put(Variabel.KEY_USER_PHOTO, "");
            try {
                update = db.update(
                        Variabel.TABLE_USER,
                        values, null, null);
            } catch (android.database.sqlite.SQLiteException e) {

            }
        }

        db.close();
        return update;
    }

And I have Error at last line:

update = db.update(
                            Variabel.TABLE_USER,
                            values, null, null);

This the eror:

Java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/data/com.ad.kamardagang.newseditor/databases/DB_KAMAR_DAGANG
            at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)
            at android.database.sqlite.SQLiteDatabase.updateWithOnConflict(SQLiteDatabase.java:1545)
            at android.database.sqlite.SQLiteDatabase.update(SQLiteDatabase.java:1522)
            at com.ad.kamardagang.newseditor.database_content.DatabaseHandler.UpdatePhotoUser(DatabaseHandler.java:613)
            at com.ad.kamardagang.newseditor.fragments.PhotoUserFragment.removeRespone(PhotoUserFragment.java:985)
            at com.ad.kamardagang.newseditor.fragments.PhotoUserFragment.access$600(PhotoUserFragment.java:62)
            at com.ad.kamardagang.newseditor.fragments.PhotoUserFragment$12.onResponse(PhotoUserFragment.java:879)
            at com.ad.kamardagang.newseditor.fragments.PhotoUserFragment$12.onResponse(PhotoUserFragment.java:875)
            at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
            at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
            at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

edited:
exmple I call with :

db = new DatabaseHandler(getActivity());
 db.UpdatePhotoUser("http://a.png",1);

when. I first call metode UpdatePhotoUser(String foto_user, int metode), but on second call its error. so how to fix it ?

Body:
if anyone has similar issue try this it will resolve issue

if (db == null || !db.isOpen())
{
  dbHelper = new MySQLiteHelper(this); //u can omit this but need to have an extra check dbHelper!=null
  db = dbHelper.getWritableDatabase();
}


问:
Using sd as a generic function in R
If I a have a class called foo, then it is straightforward to overload the summary function

```<code>summary.foo = function(x, ...) print("bar")
</code>```

However this technique does not work with the sd function, that is

```<code>> bar = createFooClass()
> sd.foo = function(x, ...) print("Hi")
> sd(bar)
  error: is.atomic(x) is not TRUE
</code>```

What is the correct way of overloading this function?

答:
You need to define a new generic for sd.

The easiest way is to use S4, because it handles the default "sd" method automatically:

```<code>setClass("foo", list(a = "numeric", names = "character"))

setGeneric("sd")

setMethod("sd", "foo",
          function(x,  na.rm = FALSE){
              print("This is a foo object!")
              callNextMethod(x@a)
              })

tf <- new("foo", a = 1:10)
sd(tf)
#[1] "This is a foo object!"
#[1] 3.027650
</code>```

Title: Using sd as a generic function in R

Body:
If I a have a class called foo, then it is straightforward to overload the summary function

summary.foo = function(x, ...) print("bar")

However this technique does not work with the sd function, that is

> bar = createFooClass()
> sd.foo = function(x, ...) print("Hi")
> sd(bar)
  error: is.atomic(x) is not TRUE

What is the correct way of overloading this function?

Body:
You need to define a new generic for sd.

The easiest way is to use S4, because it handles the default "sd" method automatically:

setClass("foo", list(a = "numeric", names = "character"))

setGeneric("sd")

setMethod("sd", "foo",
          function(x,  na.rm = FALSE){
              print("This is a foo object!")
              callNextMethod(x@a)
              })

tf <- new("foo", a = 1:10)
sd(tf)
#[1] "This is a foo object!"
#[1] 3.027650


问:
How to have an inset box-shadow start from the center rather than the border?
I currently have a box shadow stemming from the border of my  and I'm looking for a way to have the effect inversed, where the shadow starts from the center and fills out the rest of the background.
Pen

CODE:

var medalImg = document.getElementById("benefitsImgMed");
document.getElementById("benefitsImgMed").onclick = function() {
  imgClickFunction1()
};

function imgClickFunction1() {
  medalImg.style.boxShadow = "0px 0px 0px 100px white inset";
  setTimeout(doSomething, 1.6 /*Seconds*/ * 1000);

  function doSomething() {
    /*medalImg.style.borderStyle = "solid";*/
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: black;
}

#benefitsImgMed,
#benefitsImgLig,
#benefitsImgArr,
#benefitsImgNig {
  transition: 2s;
  cursor: pointer;
  z-index: 1;
  position: absolute;
  padding: 10px;
  border-color: white;
  border-width: 5px;
  border-radius: 50%;
  border-style: dashed;
}

#benefitsImgMed:hover {
  box-shadow: inset 0 0 0 50px white;
}

#benefitsImgMed {
  margin-left: 8%;
  margin-top: 6%;
  width: 13%;
  height: 13%;
}</code>```

```

答:
I looked over you code an changed a couple things. It seems like you may have some repetitive code by looking at them by id's.  So instead I implemented a custom attribute to help us to keep track of which one was clicked.  Additionally, I added an element on the inside that has very small width and height that draws a box-shadow outward.  Go ahead and give it a whirl:

function doSomething() {
  console.log('do something...')
}

$(".benefitImgs").click(function () {
  var which = $(this).attr('data-which');
  if (which === "med") {
    $(this).find(".benefitImgsInner").css("box-shadow", "0px 0px 0px 55px white")
    setTimeout(doSomething.bind(this),1.6*1000);
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{background-color:black;}

.benefitImgs {
  width: 13%;
  position: relative;
  margin-left: 8%;
  margin-top: 6%;
   transition: 2s;
   cursor:pointer;
   z-index:1;
    padding: 10px;
    border-color: white;
    border-width: 5px;
    border-radius: 50%;
    border-style: dashed;
}

.benefitImgsInner {
  z-index:-1;
  width:2px;
  height:2px;
  border-radius:50%;
  position:absolute;
  top: 50%;
  left: 50%;
  transition:all 2s ease-in-out;
  transform: translate(-50%, -50%);
}

.benefitImgs:hover .benefitImgsInner {
  transition:all 2s ease-in-out;
  box-shadow: 0 0 0 50px white;
}

.benefitsImgsImg {
    max-width:100%;
}</code>```

```

Body:
I currently have a box shadow stemming from the border of my  and I'm looking for a way to have the effect inversed, where the shadow starts from the center and fills out the rest of the background.
Pen

CODE:

var medalImg = document.getElementById("benefitsImgMed");
document.getElementById("benefitsImgMed").onclick = function() {
  imgClickFunction1()
};

function imgClickFunction1() {
  medalImg.style.boxShadow = "0px 0px 0px 100px white inset";
  setTimeout(doSomething, 1.6 /*Seconds*/ * 1000);

  function doSomething() {
    /*medalImg.style.borderStyle = "solid";*/
  }
}

body {
  background-color: black;
}

#benefitsImgMed,
#benefitsImgLig,
#benefitsImgArr,
#benefitsImgNig {
  transition: 2s;
  cursor: pointer;
  z-index: 1;
  position: absolute;
  padding: 10px;
  border-color: white;
  border-width: 5px;
  border-radius: 50%;
  border-style: dashed;
}

#benefitsImgMed:hover {
  box-shadow: inset 0 0 0 50px white;
}

#benefitsImgMed {
  margin-left: 8%;
  margin-top: 6%;
  width: 13%;
  height: 13%;
}

Body:
I looked over you code an changed a couple things. It seems like you may have some repetitive code by looking at them by id's.  So instead I implemented a custom attribute to help us to keep track of which one was clicked.  Additionally, I added an element on the inside that has very small width and height that draws a box-shadow outward.  Go ahead and give it a whirl:

function doSomething() {
  console.log('do something...')
}

$(".benefitImgs").click(function () {
  var which = $(this).attr('data-which');
  if (which === "med") {
    $(this).find(".benefitImgsInner").css("box-shadow", "0px 0px 0px 55px white")
    setTimeout(doSomething.bind(this),1.6*1000);
  }
});

body{background-color:black;}

.benefitImgs {
  width: 13%;
  position: relative;
  margin-left: 8%;
  margin-top: 6%;
   transition: 2s;
   cursor:pointer;
   z-index:1;
    padding: 10px;
    border-color: white;
    border-width: 5px;
    border-radius: 50%;
    border-style: dashed;
}

.benefitImgsInner {
  z-index:-1;
  width:2px;
  height:2px;
  border-radius:50%;
  position:absolute;
  top: 50%;
  left: 50%;
  transition:all 2s ease-in-out;
  transform: translate(-50%, -50%);
}

.benefitImgs:hover .benefitImgsInner {
  transition:all 2s ease-in-out;
  box-shadow: 0 0 0 50px white;
}

.benefitsImgsImg {
    max-width:100%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div class="benefitImgs" data-which="med">

<img src="https://static1.squarespace.com/static/59a7820e2994ca11766093d3/t/5a09f06d9140b7f3b7d84274/1510600813361/quality.png" class="benefitsImgsImg"/>

<div class="benefitImgsInner"></div>
</div>


答:
If it is guaranteed to be initialized on the constructor, then it doesn't need to be nullable at all.

You can have:

```<code>class ClassWithMember(val member: OtherClass) {
  fun foo() {
      member.doSomething()
  }
}
</code>```

Title: what is the recommended way for using the Kotlin double-bang for nullable class member

Body:
If it is guaranteed to be initialized on the constructor, then it doesn't need to be nullable at all.

You can have:

class ClassWithMember(val member: OtherClass) {
  fun foo() {
      member.doSomething()
  }
}


问:
ReactDOM is not rendering to dom
```<code><html>
<head></head>
<body>
    <div id='app'></div>
<script src="bundle.js"></script>
</body>
</html>
</code>```

and my index.js === bundle.js(webpack)

```<code>import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
  <h1>Hello, world!</h1>,
  document.getElementById('root')
);
</code>```

I got an error in console

ERROR in ./~/react-dom/index.js Module not found: Error: Cannot

   resolve module 'react/lib/ReactDOM' in

   E:\react_redux\react-redux\node_modules\react-dom @

   ./~/react-dom/index.js 3:17-46

and my package.json

```<code>"react": "^15.5.4",
"react-dom": "15.0.2",
</code>```

答:
You request react of at least version 15.5.4, and react-dom of exactly version 15.0.2.  They will not work with each other.

```<code>"react": "^15.5.4",
"react-dom": "15.0.2",
</code>```

Request react-dom version matching react version:

```<code>"react": "^15.5.4",
"react-dom": "^15.5.4",
</code>```

Title: ReactDOM is not rendering to dom

Body:
and my index.js === bundle.js(webpack)

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(

Hello, world!
,
  document.getElementById('root')
);

I got an error in console

ERROR in ./~/react-dom/index.js Module not found: Error: Cannot

   resolve module 'react/lib/ReactDOM' in

   E:\react_redux\react-redux\node_modules\react-dom @

   ./~/react-dom/index.js 3:17-46

and my package.json

"react": "^15.5.4",
"react-dom": "15.0.2",

Body:
You request react of at least version 15.5.4, and react-dom of exactly version 15.0.2.  They will not work with each other.

"react": "^15.5.4",
"react-dom": "15.0.2",

Request react-dom version matching react version:

"react": "^15.5.4",
"react-dom": "^15.5.4",