问:
Loader is not working
```<code><script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
     $('#sql').on ('click',function() {

       $('#loaderImg').show();

     });
    </script>
</code>```

And html

```<code><div class="container">
  <h1 class="text-center"></h1>
  <div id="loaderImg" style="display:none;background-color:white;width:100%;height:660px;">
     <img src="25.gif" alt="loader1" style="height:100px; width:100px;position:relative;left:500px;top:300px"></div>
     <input type="submit"  name="sql"  id="sql" onclick="myFunction1()" value="Import Database"   class="btn btn-danger"">
</code>```

I have a button 'import database'.When i clicks the button the loader should be shown until the loading complete.But my problem is the  loader image disappear suddenly after displays for a second.How can i solve this??

答:
Remove onclick from button.

code need to be:-

```<code><script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>

<div class="container">
    <h1 class="text-center"></h1>
    <div id="loaderImg" style="display:none;background-color:white;width:100%;height:660px;">
        <img src="25.gif" alt="loader1" style="height:100px; width:100px;position:relative;left:500px;top:300px"></div>
        <input type="submit"  name="sql"  id="sql" value="Import Database"  class="btn btn-danger">

<script type="text/javascript">
 $('#sql').on ('click',function() {

   $('#loaderImg').show();

 });
</script>
</code>```

Working example:-

$('#sql').on ('click',function() {

 $('#loaderImg').show();

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#loaderImg{
display:none;
background-color:white;
width:100%;
height:100px;
}

img{
height:100px;
width:100px;
position:absolute;
}</code>```

<input type="submit"  name="sql"  id="sql" value="Import Database"   class="btn btn-danger">

```

Title: Loader is not working

Body:
And html

     <input type="submit"  name="sql"  id="sql" onclick="myFunction1()" value="Import Database"   class="btn btn-danger"">

I have a button 'import database'.When i clicks the button the loader should be shown until the loading complete.But my problem is the  loader image disappear suddenly after displays for a second.How can i solve this??

Body:
Remove onclick from button.

code need to be:-

<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>

<div class="container">
    <h1 class="text-center"></h1>
    <div id="loaderImg" style="display:none;background-color:white;width:100%;height:660px;">
        <img src="25.gif" alt="loader1" style="height:100px; width:100px;position:relative;left:500px;top:300px"></div>
        <input type="submit"  name="sql"  id="sql" value="Import Database"  class="btn btn-danger">

<script type="text/javascript">
 $('#sql').on ('click',function() {

   $('#loaderImg').show();

 });
</script>

Working example:-

$('#sql').on ('click',function() {

 $('#loaderImg').show();

});

#loaderImg{
display:none;
background-color:white;
width:100%;
height:100px;
}

img{
height:100px;
width:100px;
position:absolute;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <h1 class="text-center"></h1>
    <div id="loaderImg">
     <img src="https://upload.wikimedia.org/wikipedia/commons/b/b1/Loading_icon.gif" alt="loader1">
     </div>
<input type="submit"  name="sql"  id="sql" value="Import Database"   class="btn btn-danger">
</div>


来源: stackexchange

问:
Live Ads Not displaying in my App in Playstore
I'v tested my App in test device, it displayed test Ads and everything worked fine but once my app went to production and when we get it from google playstore the ad is not displaying.It's already 2 days since my app is released.
Please suggest me what i have to do. Will it take more time?

My App comes under designed for families category.
Any app with designed for families category is able to display ads?

答:
I'v Checked in the admob Report
Till now i'v got 319 Admob network request but only 6 matched requests only 4 impressions that means designed for family category will get very very less ad fills.

For App designed for family category and kids.The only way to yield revenue is either through in-app purchase or through paid apps only.

ContentLicense: CC BY-SA 3.0


问:
Making background slide animation
I made a button group, and want when user select each button background of previous or next button move/slide to selected one, i made this effect with pure css and just used jquery to add or remove active class. now the problem is when you click on All button, then New it works fine, but if you click on Used the slide not work in right position.

For this effect i used transition and ::before, need to solve this with pure css or minimum jquery, not a lot of javascript or jquery codes.

The logic to move this background is:

```<code>.RadioButton .btn:first-child::before {
 right: 0;
 transition: .3s all ease;
}

.RadioButton .btn:nth-child(2)::before {
 transition: .3s all ease;
}

.RadioButton .btn:last-child::before {
  left: 0;
  transition: .3s all ease;
}
</code>```

The problem on .RadioButton .btn:nth-child(2)::before i can't use right:0 or left:0 because if i use each one, the slide effect not work in right position, any solution?

What i tried so far:

$('.RadioButton').each(function(){
 $(this).find('.btn').each(function(){
  $(this).click(function(){
   $(this).parent().find('.btn').removeClass('btn-active');
   $(this).addClass('btn-active');
  });
 });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
direction: rtl;
}

.RadioButton .btn {
    width: 33%;
    float: left;
    margin: 0;
    box-sizing: border-box;
    position: relative;
    font-size: 11px;
    min-height: 30px!important;
    line-height: 30px;
    border-radius: 5px;
    overflow: hidden;
    cursor: pointer;
    text-align: center;
}

.btn-default {
    border: 1px solid gray;
    color: gray;
}

.btn-group>.btn:first-child {
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
}

.btn-group>.btn:nth-child(2) {
    border-radius: 0;
}

.btn-group>.btn:last-child {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
}

.RadioButton .btn::before {
    content: "";
    height: 100%;
    width: 0%;
    background: gray;
    position: absolute;
    top: 0;
    transition: .3s all ease;
    z-index: -1;
}

.btn-active::before {
    width: 100%!important;
}

.RadioButton .btn:nth-child(2)::before {
 right: 0;
 transition: .3s all ease;
}

.RadioButton .btn:last-child::before {
  left: 0;
  transition: .3s all ease;
}

.btn-active:first-child::before {
 left: 0;
 transition: .3s all ease;
}

.btn-active:last-child::before {
  left: 0;
  transition: .3s all ease;
}

.btn.btn-default.btn-active {
    color: white;
}

.btn-group {
    clear: both;
    margin-top: 10px;
}</code>```

 Used
 New
 All

```

答:
change position center

$('.RadioButton').each(function(){
 $(this).find('.btn').each(function(){
  $(this).click(function(){
   $(this).parent().find('.btn').removeClass('btn-active');
   $(this).addClass('btn-active');
  });
 });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
direction: rtl;
}

.RadioButton .btn {
    width: 33%;
    float: left;
    margin: 0;
    box-sizing: border-box;
    position: relative;
    font-size: 11px;
    min-height: 30px!important;
    line-height: 30px;
    border-radius: 5px;
    overflow: hidden;
    cursor: pointer;
    text-align: center;
}

.btn-default {
    border: 1px solid gray;
    color: gray;
}

.btn-group>.btn:first-child {
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
}

.btn-group>.btn:nth-child(2) {
    border-radius: 0;
}

.btn-group>.btn:last-child {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
}

.RadioButton .btn::before {
    content: "";
    height: 100%;
    width: 0%;
    background: gray;
    position: absolute;
    top: 0;
    transition: .3s all ease;
    z-index: -1;
    left: 50%;
    transform: translateX(-50%);
}

.btn-active::before {
    width: 100%!important;
}

.RadioButton .btn:nth-child(2)::before {

 transition: .3s all ease;
}

.RadioButton .btn:last-child::before {

  transition: .3s all ease;
}

.btn-active:first-child::before {

 transition: .3s all ease;
}

.btn-active:last-child::before {

  transition: .3s all ease;
}

.btn.btn-default.btn-active {
    color: white;
}

.btn-group {
    clear: both;
    margin-top: 10px;
}</code>```

 Used
 New
 All

```

Title: Making background slide animation

Body:
I made a button group, and want when user select each button background of previous or next button move/slide to selected one, i made this effect with pure css and just used jquery to add or remove active class. now the problem is when you click on All button, then New it works fine, but if you click on Used the slide not work in right position.

For this effect i used transition and ::before, need to solve this with pure css or minimum jquery, not a lot of javascript or jquery codes.

The logic to move this background is:

.RadioButton .btn:first-child::before {
 right: 0;
 transition: .3s all ease;
}

.RadioButton .btn:nth-child(2)::before {
 transition: .3s all ease;
}

.RadioButton .btn:last-child::before {
  left: 0;
  transition: .3s all ease;
}

The problem on .RadioButton .btn:nth-child(2)::before i can't use right:0 or left:0 because if i use each one, the slide effect not work in right position, any solution?

What i tried so far:

$('.RadioButton').each(function(){
 $(this).find('.btn').each(function(){
  $(this).click(function(){
   $(this).parent().find('.btn').removeClass('btn-active');
   $(this).addClass('btn-active');
  });
 });
});

body {
direction: rtl;
}

.RadioButton .btn {
    width: 33%;
    float: left;
    margin: 0;
    box-sizing: border-box;
    position: relative;
    font-size: 11px;
    min-height: 30px!important;
    line-height: 30px;
    border-radius: 5px;
    overflow: hidden;
    cursor: pointer;
    text-align: center;
}

.btn-default {
    border: 1px solid gray;
    color: gray;
}

.btn-group>.btn:first-child {
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
}

.btn-group>.btn:nth-child(2) {
    border-radius: 0;
}

.btn-group>.btn:last-child {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
}

.RadioButton .btn::before {
    content: "";
    height: 100%;
    width: 0%;
    background: gray;
    position: absolute;
    top: 0;
    transition: .3s all ease;
    z-index: -1;
}

.btn-active::before {
    width: 100%!important;
}

.RadioButton .btn:nth-child(2)::before {
 right: 0;
 transition: .3s all ease;
}

.RadioButton .btn:last-child::before {
  left: 0;
  transition: .3s all ease;
}

.btn-active:first-child::before {
 left: 0;
 transition: .3s all ease;
}

.btn-active:last-child::before {
  left: 0;
  transition: .3s all ease;
}

.btn.btn-default.btn-active {
    color: white;
}

.btn-group {
    clear: both;
    margin-top: 10px;
}

 Used
 New
 All

Body:
change position center

$('.RadioButton').each(function(){
 $(this).find('.btn').each(function(){
  $(this).click(function(){
   $(this).parent().find('.btn').removeClass('btn-active');
   $(this).addClass('btn-active');
  });
 });
});

body {
direction: rtl;
}

.RadioButton .btn {
    width: 33%;
    float: left;
    margin: 0;
    box-sizing: border-box;
    position: relative;
    font-size: 11px;
    min-height: 30px!important;
    line-height: 30px;
    border-radius: 5px;
    overflow: hidden;
    cursor: pointer;
    text-align: center;
}

.btn-default {
    border: 1px solid gray;
    color: gray;
}

.btn-group>.btn:first-child {
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
}

.btn-group>.btn:nth-child(2) {
    border-radius: 0;
}

.btn-group>.btn:last-child {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
}

.RadioButton .btn::before {
    content: "";
    height: 100%;
    width: 0%;
    background: gray;
    position: absolute;
    top: 0;
    transition: .3s all ease;
    z-index: -1;
    left: 50%;
    transform: translateX(-50%);
}

.btn-active::before {
    width: 100%!important;
}

.RadioButton .btn:nth-child(2)::before {

 transition: .3s all ease;
}

.RadioButton .btn:last-child::before {

  transition: .3s all ease;
}

.btn-active:first-child::before {

 transition: .3s all ease;
}

.btn-active:last-child::before {

  transition: .3s all ease;
}

.btn.btn-default.btn-active {
    color: white;
}

.btn-group {
    clear: both;
    margin-top: 10px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="RadioButton btn-group" id="searchType">
 <a class="btn btn-default" data-val="0">Used</a>
 <a class="btn btn-default" data-val="1">New</a>
 <a class="btn btn-default btn-active" data-val="2">All</a>
</div>


问:
Error in the standards?
§5/4 C++ standard

```<code>i = 7, i++, i++;  // i becomes 9
i = ++i + 1;  //the behavior is unspecified
</code>```

That should be changed to

```<code>i = 7, i++, i++;  // the behavior is undefined
i = ++i + 1;  //the behavior is undefined
</code>```

right?

答:
That should be changed to

```<code>i = 7, i++, i++;  // the behavior is undefined
</code>```

Why? The standard is correct, this shouldn’t be changed, and this behaviour is well-defined.

A comma (,) introduces a sequence point into the calculation so the order of execution is defined.

ContentLicense: CC BY-SA 2.5

Title: Error in the standards?

Body:
§5/4 C++ standard

i = 7, i++, i++;  // i becomes 9
i = ++i + 1;  //the behavior is unspecified

That should be changed to

i = 7, i++, i++;  // the behavior is undefined
i = ++i + 1;  //the behavior is undefined

right?

Body:
That should be changed to

i = 7, i++, i++;  // the behavior is undefined

Why? The standard is correct, this shouldn’t be changed, and this behaviour is well-defined.

A comma (,) introduces a sequence point into the calculation so the order of execution is defined.


问:
Difference between React Component and React Element
What is the difference between React Component and React Element? The documentation mentions both but does not go into detail, some methods require components, other elements...</p>

答: A component is a factory for creating elements.</p>


问:
Spark out of memory no matter what i do
I'm trying to use spark to filter a large dataframe. As a pandas dataframe it would be somewhere around 70GB in memory.

I am able to load and filter this data using pandas, however really slowly because I have to swap to disk etc.

However when i try doing this using PySpark I run into memory errors from Java.

from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("Master").getOrCreate()
master = spark.read.csv(master_path, inferSchema=True, schema=schema, header=True)

master_desember = spark.sql("SELECT * FROM master_filter_ready WHERE born_month='12'")
master_desember = master_desember.toPandas()
```

Edit: So my question is how do I set memory on a spark session before I create it? Also How can I determine what values to use? At the moment I'm just guessing.

答:
After reading comments bellow my question about needing to set memory before creating the session I did this:

from pyspark.sql import SparkSession

builder = SparkSession.builder
builder = builder.config("spark.executor.memory", "2G")
builder = builder.config("spark.driver.memory", "10G")
builder = builder.config("spark.driver.maxResultSize", "5G")
spark = builder.appName("Master").getOrCreate()
```

This solved my issue. However, I'm not sure why these values worked as I'm not yet familiar enough with how Spark and PySpark works.

If any one have tips on when to set what values where, please answer bellow! :)

Title: Spark out of memory no matter what i do

Body:
I'm trying to use spark to filter a large dataframe. As a pandas dataframe it would be somewhere around 70GB in memory.

I am able to load and filter this data using pandas, however really slowly because I have to swap to disk etc.

However when i try doing this using PySpark I run into memory errors from Java.

from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("Master").getOrCreate()
master = spark.read.csv(master_path, inferSchema=True, schema=schema, header=True)

master_desember = spark.sql("SELECT * FROM master_filter_ready WHERE born_month='12'")
master_desember = master_desember.toPandas()

Edit: So my question is how do I set memory on a spark session before I create it? Also How can I determine what values to use? At the moment I'm just guessing.

Body:
After reading comments bellow my question about needing to set memory before creating the session I did this:

from pyspark.sql import SparkSession

builder = SparkSession.builder
builder = builder.config("spark.executor.memory", "2G")
builder = builder.config("spark.driver.memory", "10G")
builder = builder.config("spark.driver.maxResultSize", "5G")
spark = builder.appName("Master").getOrCreate()

This solved my issue. However, I'm not sure why these values worked as I'm not yet familiar enough with how Spark and PySpark works.

If any one have tips on when to set what values where, please answer bellow! :)


问:
Keeping the same Public DNS for an EC2 Instance
I understand, that a static IPv4 addresses would be more expensive for AWS, so it changes every time I restart the instance. But the Public DNS could be static, so I would not have to change the address in all my applications, after restarting the Instance.

Can I statically set the Instances Public DNS to something like "MyChoosenName.eu-west-1-compute.amazonaws.com"?

答:
No its not possible

Because each public ip address in AWS is binded to DNS, so what you
are attempting add sub-domain to the
"eu-west-1-compute.amazonaws.com" which is not possible you are not
owner of the domain provider.

The thingh you do is bind the public to some other domain which you own like

Mychoicename.abc.com like we do for other domain bindings either in

AWS route53 or other domain providers.


问:
LibGDX: Implement touch screen, without touching the screen
I'm using LibGDX.

Let's say that I wan't to jump - but not really touching the screen, I don't want to use a keyboard forsay, And implement the touch, like i was touching the screen.
Can i do that?

Can one let's say "test" the button without pressing it (from the touch screen of application / android / ios / etc..)?

Example of a button from InputListener:

```<code>final Image imageJumpButton = new Image(new Texture("jbjump.png"));
imageJumpButton.addListener(new InputListener() {

    @Override
    public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
        JOYSTICK_UP= true;
        return true;
    }

    @Override
    public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
        JOYSTICK_UP = false;
    }
});
</code>```

I thank you.

答:
Probably. I'm not sure if this working. Can't test now. You can use Actor fire(Event event) method.

```<code>imageJumpButton.fire(InputEvent.Type.touchDown);
</code>```

or

```<code>imageJumpButton.fire(InputEvent.Type.touchUp);
</code>```

Body:
I'm using LibGDX.

Let's say that I wan't to jump - but not really touching the screen, I don't want to use a keyboard forsay, And implement the touch, like i was touching the screen.
Can i do that?

Can one let's say "test" the button without pressing it (from the touch screen of application / android / ios / etc..)?

Example of a button from InputListener:

final Image imageJumpButton = new Image(new Texture("jbjump.png"));
imageJumpButton.addListener(new InputListener() {

    @Override
    public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
        JOYSTICK_UP= true;
        return true;
    }

    @Override
    public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
        JOYSTICK_UP = false;
    }
});

I thank you.

Body:
Probably. I'm not sure if this working. Can't test now. You can use Actor fire(Event event) method.

imageJumpButton.fire(InputEvent.Type.touchDown);

or

imageJumpButton.fire(InputEvent.Type.touchUp);


问:
liquibase data export crash with GC overhead limit exceeded
I would like to use liquibase to export data (like portable csv flat files) connecting to different large database (sybase or sqlserver DB)
The DB could store more than 100 tables and 10GB

I found command:

```<code>liquibase --defaultsFile=/db/liquibase/db.properties --changeLogFile=/db/liquibase/data.xml --diffTypes="data" generateChangeLog
</code>```

Result:

```<code>Unexpected error running Liquibase: GC overhead limit exceeded
</code>```

I increased java memory to 32GB and still crashing
I tested on a small database with 1 small table. Export was ok

Do we have limitations with liquibase export data?
Do not want to manage diff data. Just want to export data current state.
Thanks for your help

答: You could use the Jailer Tool to export data in liquibase format.</p>

Body:
I would like to use liquibase to export data (like portable csv flat files) connecting to different large database (sybase or sqlserver DB)
The DB could store more than 100 tables and 10GB

I found command:

liquibase --defaultsFile=/db/liquibase/db.properties --changeLogFile=/db/liquibase/data.xml --diffTypes="data" generateChangeLog

Result:

Unexpected error running Liquibase: GC overhead limit exceeded

I increased java memory to 32GB and still crashing
I tested on a small database with 1 small table. Export was ok

Do we have limitations with liquibase export data?
Do not want to manage diff data. Just want to export data current state.
Thanks for your help


问:
ANT - Run a single target but without dependencies
I know how to run a single target in ANT, but it also checks the "depends" attribute and runs those before the target. Is there a way to prevent this or a way to structure my ANT file so that I can do this more easily?</p>

答:
I made macro with piece of code, what I want.
Then made 2 targets, 1 calls macro with "arg1", 2nd with "arg2".
You can also make macro without accepting parameters.

```<code><macrodef name="macro-jar">
    <attribute name="dir" />
    <sequential>
        <jar destfile="${jar.name}">
            <fileset dir="@{dir}" .../>
            ...
            ...
        </jar>
    </sequential>
</macrodef>
</code>```

Calling it from 2 places in code:

1st:

```<code><macro-jar dir="${dir.build}" />
</code>```

2nd:

```<code><macro-jar dir="${dir.temp}" />
</code>```

Body:
I made macro with piece of code, what I want.
Then made 2 targets, 1 calls macro with "arg1", 2nd with "arg2".
You can also make macro without accepting parameters.

<macrodef name="macro-jar">
    <attribute name="dir" />
    <sequential>
        <jar destfile="${jar.name}">
            <fileset dir="@{dir}" .../>
            ...
            ...
        </jar>
    </sequential>
</macrodef>

Calling it from 2 places in code:

1st:

<macro-jar dir="${dir.build}" />

2nd:

<macro-jar dir="${dir.temp}" />


问:
How to force hibernate not to load subentities
I have A and B entities where A can have more Bs

```<code>@Entity
@Table(name = "A")
public class A {

@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "b_id", nullable = false, insertable = true, updatable = false)
private Set<B> bs;

}
</code>```

what I need is to say jpa somehow not to load set of Bs in special situations.

I tried it other way around, I defined fetch = FetchType.Lazy and then I say hibernate when i want to load B. Problem is however, that when i do a.getBs(), hibernate loads the bs even when i dont want this behaviour ( I wanted only check if B is loaded or not). It means I need to force hibernate with jpa not to load subentities later (a.getBs()) with lazy load mode OR to force not to load entities with eager load mode.

In jpa there is method Root.fetch(). I would need Root.unfetch()

答:
Hibernate provide functionality for the check without fetching.

If you keep Lazy fetching
you can add this method in the parent entity

```<code>public boolean isBLoaded() {
    if (bs instanceof HibernateProxy) {
        if (((HibernateProxy)bs ).getHibernateLazyInitializer().isUninitialized()) {
            return false;
        }
    }
    return true;
}
</code>```

The point is to not call the getter or you will fetch the association

Body:
I have A and B entities where A can have more Bs

@Entity
@Table(name = "A")
public class A {

@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "b_id", nullable = false, insertable = true, updatable = false)
private Set bs;

}

what I need is to say jpa somehow not to load set of Bs in special situations.

I tried it other way around, I defined fetch = FetchType.Lazy and then I say hibernate when i want to load B. Problem is however, that when i do a.getBs(), hibernate loads the bs even when i dont want this behaviour ( I wanted only check if B is loaded or not). It means I need to force hibernate with jpa not to load subentities later (a.getBs()) with lazy load mode OR to force not to load entities with eager load mode.

In jpa there is method Root.fetch(). I would need Root.unfetch()

Body:
Hibernate provide functionality for the check without fetching.

If you keep Lazy fetching
you can add this method in the parent entity

public boolean isBLoaded() {
    if (bs instanceof HibernateProxy) {
        if (((HibernateProxy)bs ).getHibernateLazyInitializer().isUninitialized()) {
            return false;
        }
    }
    return true;
}

The point is to not call the getter or you will fetch the association


问:
ReactiveUI command unsubscription
I have 2 Views and 2 ViewModels:

First View:

```<code>public partial class FirstView : Page
{
    FirstViewModel ViewModel;
    public FirstView()
    {
        ViewModel = new FirstViewModel();
        ViewModel.ShowSecondView.Subscribe(_ =>
        {
            NavigationService.Navigate(new SecondView(ViewModel.ChildViewModel));
        });

        this.DataContext = ViewModel;
        InitializeComponent();
    }
}
</code>```

First ViewModel:

```<code>public class FirstViewModel
{
    SecondViewModel ChildViewModel;
    public ReactiveCommand<Unit, Unit> ShowSecondView { get; set; }
    public FirstViewModel()
    {
        ChildViewModel = new SecondViewModel();
        ShowSecondView = ReactiveCommand.Create(() =>
        {
             ChildViewModel.Reconfigure(...);
        });
    }
}
</code>```

Second View:

```<code>public partial class SecondView : Page
{
    SecondViewModel ViewModel;
    public SecondView(SecondViewModel viewModel)
    {
        ViewModel = viewModel;
        ViewModel.GoBack.Subscribe(_ =>
        {
            DoSomethingHard();
            if(NavigationService != null)  NavigationService.GoBack();
        });
        this.DataContext = ViewModel;
        InitializeComponent();
    }
}
</code>```

Second ViewModel:

```<code>public class SecondViewModel
{
    public ReactiveCommand<Unit, Unit> GoBack { get; set; }
    public FirstViewModel()
    {
        VeryLongInitialization();
        GoBack = ReactiveCommand.Create(() => { });
    }
    public void Reconfigure(...)
    { ... }
}
</code>```

So, when I run FirstViewModel.ShowSecondView several times and run SecondViewModel.GoBack several times, DoSomethingHard() execute also several times on each created SecondView.

Why do I want create ChildViewModel in FilstViewModel once? Because creating of SecondViewModel takes long time. And I don't recreate every time SecondViewModel but only reconfigure it.

My question is how can I unsubscribe ViewModel.GoBack.Subscribe in SecondView?

P.S. Maybe I should not recreate SecondView in FirstView but reconfigure it as well as SecondViewModel?

UPDATE 1 (thanks to Julien Mialon)

I add IDisposable goBackSubscr and it works! Am I right to implement it?

```<code>public partial class SecondView : Page
{
    SecondViewModel ViewModel;
    IDisposable goBackSubscr;
    public SecondView(SecondViewModel viewModel)
    {
        ViewModel = viewModel;
        goBackSubscr = ViewModel.GoBack.Subscribe(_ =>
        {
            DoSomethingHard();
            if(NavigationService != null)  NavigationService.GoBack();
            goBackSubscr.Dispose();
        });
        this.DataContext = ViewModel;
        InitializeComponent();
    }
}
</code>```

答:
I think I know what you are trying to do. If I am right, you are trying to create a Wizard of some sort or something that displays one view model that can move to the next, and then that can move prior? If that sis the case then maybe you want to re-think how you are doing it.
For example, Why not manage the back and forth buttons in a view model that houses the two view models and have the child view models only create once when they are first required. Then, your navigation buttons can determine which view models are currently on and be enabled depending upon the logic.
In a Wizard type scenario, consider basing your child view models on a Base view model that may have a property or method called something like CanMoveNext() and CanMovePrior(). Internally, this can return true if it is ready. Much easier.</p>

Title: ReactiveUI command unsubscription

Body:
I have 2 Views and 2 ViewModels:

First View:

public partial class FirstView : Page
{
    FirstViewModel ViewModel;
    public FirstView()
    {
        ViewModel = new FirstViewModel();
        ViewModel.ShowSecondView.Subscribe(_ =>
        {
            NavigationService.Navigate(new SecondView(ViewModel.ChildViewModel));
        });

        this.DataContext = ViewModel;
        InitializeComponent();
    }
}

First ViewModel:

public class FirstViewModel
{
    SecondViewModel ChildViewModel;
    public ReactiveCommand<Unit, Unit> ShowSecondView { get; set; }
    public FirstViewModel()
    {
        ChildViewModel = new SecondViewModel();
        ShowSecondView = ReactiveCommand.Create(() =>
        {
             ChildViewModel.Reconfigure(...);
        });
    }
}

Second View:

public partial class SecondView : Page
{
    SecondViewModel ViewModel;
    public SecondView(SecondViewModel viewModel)
    {
        ViewModel = viewModel;
        ViewModel.GoBack.Subscribe(_ =>
        {
            DoSomethingHard();
            if(NavigationService != null)  NavigationService.GoBack();
        });
        this.DataContext = ViewModel;
        InitializeComponent();
    }
}

Second ViewModel:

public class SecondViewModel
{
    public ReactiveCommand<Unit, Unit> GoBack { get; set; }
    public FirstViewModel()
    {
        VeryLongInitialization();
        GoBack = ReactiveCommand.Create(() => { });
    }
    public void Reconfigure(...)
    { ... }
}

So, when I run FirstViewModel.ShowSecondView several times and run SecondViewModel.GoBack several times, DoSomethingHard() execute also several times on each created SecondView.

Why do I want create ChildViewModel in FilstViewModel once? Because creating of SecondViewModel takes long time. And I don't recreate every time SecondViewModel but only reconfigure it.

My question is how can I unsubscribe ViewModel.GoBack.Subscribe in SecondView?

P.S. Maybe I should not recreate SecondView in FirstView but reconfigure it as well as SecondViewModel?

UPDATE 1 (thanks to Julien Mialon)

I add IDisposable goBackSubscr and it works! Am I right to implement it?

public partial class SecondView : Page
{
    SecondViewModel ViewModel;
    IDisposable goBackSubscr;
    public SecondView(SecondViewModel viewModel)
    {
        ViewModel = viewModel;
        goBackSubscr = ViewModel.GoBack.Subscribe(_ =>
        {
            DoSomethingHard();
            if(NavigationService != null)  NavigationService.GoBack();
            goBackSubscr.Dispose();
        });
        this.DataContext = ViewModel;
        InitializeComponent();
    }
}


问:
Replacing character with File.separator using java.regex Pattern Matcher
I have a field called 'path' in back end database, which stores the path to certain resource. Instead of storing lots of backslashed (escaped) path for windows path, my idea is to let user enter the path with certain character as file separator (independent of OS).

For example:

original path:

```<code>\\\\server\\share\\
</code>```

with escaped path in db:

```<code>\\\\\\\\server\\\\share\\\\
</code>```

instead I want:

```<code>%%server%share%
</code>```

and later I wanted to replace those with java's File.separator for the real thing. For this job, the quickest solution I found is to use the java.regex Pattern Matcher.

My function for this job is:

```<code>private String convertToRealPathFromDB(String pth) {
    String patternStr = "%";
    String replaceStr = File.separator;
    String convertedpath;

    //Compile regular expression
    Pattern pattern = Pattern.compile(patternStr); //pattern to look for

    //replace all occurance of percentage character to file separator
    Matcher matcher = pattern.matcher(pth);
    convertedpath = matcher.replaceAll(replaceStr);

    System.out.println(convertedpath);

    return convertedpath;
}
</code>```

but the same File.separator which was supposed to save life is creating trouble with

java.lang.StringIndexOutOfBoundsException: String index out of range: 1

I have tested with other characters (for example: replace '%' with 'q') and this function works fine but File.separator and "\\\\" as replace string is not working.

I like to know it there is workaround for this. Or better, easier and elegant solution.

答:
I think you should store URIs in your database because they are platform independent.

Example, in Windows:

```<code>File f = new File("C:\\temp\\file.txt");
System.out.println(f.toURI());
</code>```

prints

```<code>file:/C:/temp/file.txt
</code>```

On Unix:

```<code>File f = new File("/path/to/file.txt");
System.out.println(f.toURI());
</code>```

prints

```<code>file:/path/to/file.txt
</code>```

To convert a URI to File:

```<code>File f = new File(new URI("file:/C:/temp/file.txt"));
</code>```

Body:
I have a field called 'path' in back end database, which stores the path to certain resource. Instead of storing lots of backslashed (escaped) path for windows path, my idea is to let user enter the path with certain character as file separator (independent of OS).

For example:

original path:

\\\\server\\share\\

with escaped path in db:

\\\\\\\\server\\\\share\\\\

instead I want:

%%server%share%

and later I wanted to replace those with java's File.separator for the real thing. For this job, the quickest solution I found is to use the java.regex Pattern Matcher.

My function for this job is:

private String convertToRealPathFromDB(String pth) {
    String patternStr = "%";
    String replaceStr = File.separator;
    String convertedpath;

    //Compile regular expression
    Pattern pattern = Pattern.compile(patternStr); //pattern to look for

    //replace all occurance of percentage character to file separator
    Matcher matcher = pattern.matcher(pth);
    convertedpath = matcher.replaceAll(replaceStr);

    System.out.println(convertedpath);

    return convertedpath;
}

but the same File.separator which was supposed to save life is creating trouble with

java.lang.StringIndexOutOfBoundsException: String index out of range: 1

I have tested with other characters (for example: replace '%' with 'q') and this function works fine but File.separator and "\\\\" as replace string is not working.

I like to know it there is workaround for this. Or better, easier and elegant solution.

Body:
I think you should store URIs in your database because they are platform independent.

Example, in Windows:

File f = new File("C:\\temp\\file.txt");
System.out.println(f.toURI());

prints

file:/C:/temp/file.txt

On Unix:

File f = new File("/path/to/file.txt");
System.out.println(f.toURI());

prints

file:/path/to/file.txt

To convert a URI to File:

File f = new File(new URI("file:/C:/temp/file.txt"));


问:
Passing strings between activities, intents not working
I am currently working on a project with a friend, where we have a website hosting login details and such. when a user logs in it returns a token to the app, to use as verification for further api calls by the user. (ie. getting the profile). i need to pass this token across other activities (it is a string), and i tried to use intents, but every time i try it comes up with a nullPointerException , where the class i'm calling the intent from can't find the extra i'm sending. i've tried putting the code for creating the intent at the top of the onCreate method, however this returns 401 errors from the server as (i assume) the token has no value because it hasn't been sent by the server using the JSONObject request yet.
here is the code for the main activity (all links removed)(i also didnt include all the imports and variable declarations as i figured they're un-necessary)

```<code>    String Name,Pass,tokenString;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.button);
    token = (TextView) findViewById(R.id.TV1);
    name = (EditText) findViewById(R.id.name);
    pass = (EditText) findViewById(R.id.pass);
    register = (Button) findViewById(R.id.button2);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

          Name = name.getText().toString();
            Pass = pass.getText().toString();

            if(Name.equals("") || Pass.equals("")){
                Toast.makeText(MainActivity.this, "Fields cannot be left empty!", Toast.LENGTH_SHORT).show();
            }

            StringRequest stringRequest = new StringRequest(Request.Method.POST, Url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {

                        JSONObject jsonObject =  new JSONObject(response);
                        setToken(jsonObject.getString("token"));

                        launchHomeActivity();

                    } catch (JSONException e) {
                        e.printStackTrace();

                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    if(error.networkResponse.statusCode==401) {
                        Toast.makeText(MainActivity.this, "Incorrect login details, please retry", Toast.LENGTH_SHORT).show();
                    }
                }
            }){
                protected Map<String,String> getParams() throws AuthFailureError{
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("key", "****");
                    params.put("email", Name);
                    params.put("password", Pass);
                    return params;
                }
            };
            MySingleton.getInstance(MainActivity.this).addToRequestQueue(stringRequest);
            name.setText("");
            pass.setText("");

        }

    });
    register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            launchRegisterActivity();
        }
    });

}
private void launchRegisterActivity() {

    Intent intent = new Intent(this, RegisterActivity.class);
    startActivity(intent);
}
private void launchHomeActivity() {

    Intent intent = new Intent(this, Home.class);
    startActivity(intent);
}

private void setToken(String token){
    tokenString = token;

}
public String getToken(){
    return tokenString;
}

public void createIntent(){
    Intent i = new Intent(this, Home.class);
    i.putExtra("Token", getToken());
    startActivity(i);
}
}
</code>```

here is the code for the home activity (the relevant bits) :

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    token = (TextView) findViewById(R.id.TV1) ;
    title = (TextView) findViewById(R.id.welcome_Txt);

    Bundle extras = getIntent().getExtras();

   final String tokenString = extras.getString("Token");

            StringRequest stringRequest = new StringRequest(Request.Method.GET, ProfileUrl, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        // JSONArray jsonArray = new JSONArray(response);
                        JSONObject jsonObject =  new JSONObject(response);
                         title.setText("Welcome back " +  jsonObject.getString("token") + "!");

                    } catch (JSONException e) {
                        e.printStackTrace();

                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }){
                protected Map<String,String> getParams() throws AuthFailureError{
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("key", "****");
                    params.put("Token", tokenString);
                    return params;
                }
            };
            MySingleton.getInstance(Home.this).addToRequestQueue(stringRequest);

        }
</code>```

Any help is greatly appreciated.

(p.s i'm very new to android studio, and learning as i go)

答:
try like this.</p>

```<code>Intent i = new Intent(this, Home.class);
i.putExtra("Token", getToken());
startActivity(i)

and on your Home activity get data like below code.

 Intent intent=getIntent();
 String token=intent.getStringExtra("token");
</code>```

Body:
I am currently working on a project with a friend, where we have a website hosting login details and such. when a user logs in it returns a token to the app, to use as verification for further api calls by the user. (ie. getting the profile). i need to pass this token across other activities (it is a string), and i tried to use intents, but every time i try it comes up with a nullPointerException , where the class i'm calling the intent from can't find the extra i'm sending. i've tried putting the code for creating the intent at the top of the onCreate method, however this returns 401 errors from the server as (i assume) the token has no value because it hasn't been sent by the server using the JSONObject request yet.
here is the code for the main activity (all links removed)(i also didnt include all the imports and variable declarations as i figured they're un-necessary)

    String Name,Pass,tokenString;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.button);
    token = (TextView) findViewById(R.id.TV1);
    name = (EditText) findViewById(R.id.name);
    pass = (EditText) findViewById(R.id.pass);
    register = (Button) findViewById(R.id.button2);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

          Name = name.getText().toString();
            Pass = pass.getText().toString();

            if(Name.equals("") || Pass.equals("")){
                Toast.makeText(MainActivity.this, "Fields cannot be left empty!", Toast.LENGTH_SHORT).show();
            }

            StringRequest stringRequest = new StringRequest(Request.Method.POST, Url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {

                        JSONObject jsonObject =  new JSONObject(response);
                        setToken(jsonObject.getString("token"));

                        launchHomeActivity();

                    } catch (JSONException e) {
                        e.printStackTrace();

                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    if(error.networkResponse.statusCode==401) {
                        Toast.makeText(MainActivity.this, "Incorrect login details, please retry", Toast.LENGTH_SHORT).show();
                    }
                }
            }){
                protected Map<String,String> getParams() throws AuthFailureError{
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("key", "****");
                    params.put("email", Name);
                    params.put("password", Pass);
                    return params;
                }
            };
            MySingleton.getInstance(MainActivity.this).addToRequestQueue(stringRequest);
            name.setText("");
            pass.setText("");

        }

    });
    register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            launchRegisterActivity();
        }
    });

}
private void launchRegisterActivity() {

    Intent intent = new Intent(this, RegisterActivity.class);
    startActivity(intent);
}
private void launchHomeActivity() {

    Intent intent = new Intent(this, Home.class);
    startActivity(intent);
}

private void setToken(String token){
    tokenString = token;

}
public String getToken(){
    return tokenString;
}

public void createIntent(){
    Intent i = new Intent(this, Home.class);
    i.putExtra("Token", getToken());
    startActivity(i);
}
}

here is the code for the home activity (the relevant bits) :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    token = (TextView) findViewById(R.id.TV1) ;
    title = (TextView) findViewById(R.id.welcome_Txt);

    Bundle extras = getIntent().getExtras();

   final String tokenString = extras.getString("Token");

            StringRequest stringRequest = new StringRequest(Request.Method.GET, ProfileUrl, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        // JSONArray jsonArray = new JSONArray(response);
                        JSONObject jsonObject =  new JSONObject(response);
                         title.setText("Welcome back " +  jsonObject.getString("token") + "!");

                    } catch (JSONException e) {
                        e.printStackTrace();

                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }){
                protected Map<String,String> getParams() throws AuthFailureError{
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("key", "****");
                    params.put("Token", tokenString);
                    return params;
                }
            };
            MySingleton.getInstance(Home.this).addToRequestQueue(stringRequest);

        }

Any help is greatly appreciated.

(p.s i'm very new to android studio, and learning as i go)

Body:
try like this.

Intent i = new Intent(this, Home.class);
i.putExtra("Token", getToken());
startActivity(i)

and on your Home activity get data like below code.

 Intent intent=getIntent();
 String token=intent.getStringExtra("token");


问:
How to use \copy in psql after connecting to a database via URI in a batch file?
I want to make a .bat file that will go to a directory, change code page (beacuse my folders contain characters from my native language) then open database in psql and then using \copy export some tables from DB to folder on my computer, then quit database and close the command. If I do it manually it works like a charm, but .bat file stops after entering database.

```<code>    cd C:\Program Files\PostgreSQL\9.6\bin
    chcp 1250
    psql "postgres://<heres_my_URI>"
    \copy <table_name> to 'G:\<path>\name.csv' with
 DELIMITER ',' header csv;
    \copy <table_name> to 'G:\<path>\name.csv' with
 DELIMITER ',' header csv;
    \q
    exit
</code>```

I want the .bat file to download csv's to the path and close itself after.

But .bat is doing fine until it enters database, then it just shows:

```<code><mydatabase_name> =>
</code>```

and until I press \q or

```<code>\copy <table_name> to 'G:\<path>\name.csv' with
     DELIMITER ',' header csv;
</code>```

manually, nothing will happen. After I quit DB, it shows me all the errors about \copy not being recognizable. How do I make it work? Thanks for help :)

答:
You could pass the sql with the command parameter:
psql "postgres://" -c "copy  to 'G:\\name.csv' with DELIMITER ',' header csv; copy  to 'G:\\name.csv' with
 DELIMITER ',' header csv;"</p>

Body:
I want to make a .bat file that will go to a directory, change code page (beacuse my folders contain characters from my native language) then open database in psql and then using \copy export some tables from DB to folder on my computer, then quit database and close the command. If I do it manually it works like a charm, but .bat file stops after entering database.

    cd C:\Program Files\PostgreSQL\9.6\bin
    chcp 1250
    psql "postgres://<heres_my_URI>"
    \copy <table_name> to 'G:\<path>\name.csv' with
 DELIMITER ',' header csv;
    \copy <table_name> to 'G:\<path>\name.csv' with
 DELIMITER ',' header csv;
    \q
    exit

I want the .bat file to download csv's to the path and close itself after.

But .bat is doing fine until it enters database, then it just shows:

<mydatabase_name> =>

and until I press \q or

\copy <table_name> to 'G:\<path>\name.csv' with
     DELIMITER ',' header csv;

manually, nothing will happen. After I quit DB, it shows me all the errors about \copy not being recognizable. How do I make it work? Thanks for help :)


问:
Three.js move camera distance to object by z
I'm rotating a PerspectiveCamera with orbitControls around an object. Now I want to move the camera closer to the object but keep the actual rotation.

My coordinate to set the distance to the objects are output as [0,0,100].

But my CameraPosition is [-500, 96, 1772]. How can I keep the "rotation" but move the camera closer to the object to a distance of 100.

Do I need to use getAzimuthalAngle() or getPolarAngle()?

答:
For example, like this, if you object is not in the center of a scene:

```<code>camera.position.sub(obj.position).setLength(100).add(obj.position);
</code>```

If the object is in the center:

```<code>camera.position.setLength(100);
</code>```

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(25, 0, 100);
var renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var controls = new THREE.OrbitControls(camera, renderer.domElement);

scene.add(new THREE.GridHelper(100, 100));

var obj = new THREE.Mesh(new THREE.CubeGeometry(10, 10, 10), new THREE.MeshBasicMaterial({
  color: "red",
  wireframe: true
}));
obj.position.set(25, 0, 0);
scene.add(obj);
controls.target.copy(obj.position);
controls.update();

stepCloser.addEventListener("click", onClick, false);

function onClick() {
  camera.position.sub(obj.position).setLength(100).add(obj.position);
}

render();

function render() {
  requestAnimationFrame(render);
  renderer.render(scene, camera);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  overflow: hidden;
  margin: 0;
}</code>```

<button id="stepCloser" style="position: absolute;">
  100 units to the object
</button>```

Body:
For example, like this, if you object is not in the center of a scene:

camera.position.sub(obj.position).setLength(100).add(obj.position);

If the object is in the center:

camera.position.setLength(100);

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(25, 0, 100);
var renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var controls = new THREE.OrbitControls(camera, renderer.domElement);

scene.add(new THREE.GridHelper(100, 100));

var obj = new THREE.Mesh(new THREE.CubeGeometry(10, 10, 10), new THREE.MeshBasicMaterial({
  color: "red",
  wireframe: true
}));
obj.position.set(25, 0, 0);
scene.add(obj);
controls.target.copy(obj.position);
controls.update();

stepCloser.addEventListener("click", onClick, false);

function onClick() {
  camera.position.sub(obj.position).setLength(100).add(obj.position);
}

render();

function render() {
  requestAnimationFrame(render);
  renderer.render(scene, camera);
}

body {
  overflow: hidden;
  margin: 0;
}

<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<button id="stepCloser" style="position: absolute;">
  100 units to the object
</button>


问:
Powershell equivalent to $_ in bash
In bash, to get argument from last command we call $_.
I have searched but couldn't find what is equivalent to bash's $_ in PowerShell ?
Example:

```<code>$ mkdir 20171206
$ cd $_
</code>```

Now bash current working directory would be 20171206 and I am trying to achieve same via PowerShell.

Is it possible ?

答:
Apparently, $_ in bash means "last argument of previous command".

The closest approximation of that is $$, which is defined as:

Contains the last token in the last line received by the session.

However, I don't know if that means PowerShell's $$ behaves like bash's $_ or if it behaves like bash's !$.  I think it's closer to !$, but I'm on my Chromebook at the moment and can't confirm.

Edit:  It's like !$:

```<code>PS C:\> Get-Location > a.txt
PS C:\> $$
a.txt
</code>```

So there's no direct equivalent to bash's $_.

Keep in mind, though, that PowerShell strongly favors objects and pipes, so retaining the bash convention of thinking about everything in terms of plain text and space-delimited tokens won't serve you as well.  The best way to do this in PowerShell is:

```<code>mkdir 20171206 | cd
</code>```

Or, if you're not using any of the default PowerShell aliases and functions (I'm not sure what gets retained on Linux PowerShell, for example):

```<code>New-Item 20171206 -ItemType Directory | Set-Location
</code>```

Title: Powershell equivalent to $_ in bash

Body:
In bash, to get argument from last command we call $_.
I have searched but couldn't find what is equivalent to bash's $_ in PowerShell ?
Example:

$ mkdir 20171206
$ cd $_

Now bash current working directory would be 20171206 and I am trying to achieve same via PowerShell.

Is it possible ?

Body:
Apparently, $_ in bash means "last argument of previous command".

The closest approximation of that is $$, which is defined as:

Contains the last token in the last line received by the session.

However, I don't know if that means PowerShell's $$ behaves like bash's $_ or if it behaves like bash's !$.  I think it's closer to !$, but I'm on my Chromebook at the moment and can't confirm.

Edit:  It's like !$:

PS C:\> Get-Location > a.txt
PS C:\> $$
a.txt

So there's no direct equivalent to bash's $_.

Keep in mind, though, that PowerShell strongly favors objects and pipes, so retaining the bash convention of thinking about everything in terms of plain text and space-delimited tokens won't serve you as well.  The best way to do this in PowerShell is:

mkdir 20171206 | cd

Or, if you're not using any of the default PowerShell aliases and functions (I'm not sure what gets retained on Linux PowerShell, for example):

New-Item 20171206 -ItemType Directory | Set-Location


问:
html table with javascript sp
Basically, I am a beginner who recently started working with Javascript and I want to simplify my code. How can I simplify this? How would I apply a loop because it is too long to declare it by a single code if I want to change the id. Not manually changing in the html, but using a Javascript to change the value in html?

```<code><table border="2" cellpadding="4">
    <tbody>
        <tr>
            <td id="cell1"> one </td>
            <td id="cell2"> two </td>
            <td id="cell3"> three </td>
        </tr>
        <tr>
            <td id="cell4"> four </td>
            <td id="cell5"> five </td>
            <td id="cell6"> six </td>
        </tr>
    </tbody>
</table>

document.getElementById("cell1").innerHTML="1";
document.getElementById("cell2").innerHTML="2";
document.getElementById("cell3").innerHTML="3";
document.getElementById("cell4").innerHTML="4";
document.getElementById("cell5").innerHTML="5";
document.getElementById("cell6").innerHTML="6";
</code>```

答:
try this code using for loop

var items = document.getElementsByTagName('td');
for (var i = 0, j = 1; i <= items.length - 1; i++, j++) {
  items[i].innerHTML = j;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border="2" cellpadding="4">
  <tbody>
    <tr>
      <td id="cell1"> one </td>
      <td id="cell2"> two </td>
      <td id="cell3"> three </td>
    </tr>
    <tr>
      <td id="cell4"> four </td>
      <td id="cell5"> five </td>
      <td id="cell6"> six </td>
    </tr>
  </tbody>
</table></code>```

Title: html table with javascript sp

Body:
Basically, I am a beginner who recently started working with Javascript and I want to simplify my code. How can I simplify this? How would I apply a loop because it is too long to declare it by a single code if I want to change the id. Not manually changing in the html, but using a Javascript to change the value in html?

             one
             two
             three

             four
             five
             six

document.getElementById("cell1").innerHTML="1";
document.getElementById("cell2").innerHTML="2";
document.getElementById("cell3").innerHTML="3";
document.getElementById("cell4").innerHTML="4";
document.getElementById("cell5").innerHTML="5";
document.getElementById("cell6").innerHTML="6";

Body:
try this code using for loop

var items = document.getElementsByTagName('td');
for (var i = 0, j = 1; i <= items.length - 1; i++, j++) {
  items[i].innerHTML = j;
}

<table border="2" cellpadding="4">
  <tbody>
    <tr>
      <td id="cell1"> one </td>
      <td id="cell2"> two </td>
      <td id="cell3"> three </td>
    </tr>
    <tr>
      <td id="cell4"> four </td>
      <td id="cell5"> five </td>
      <td id="cell6"> six </td>
    </tr>
  </tbody>
</table>


答:
```<code>i = 7, i++, i++; // i becomes 9
</code>```

is perfectly fine. Operator = has higher precedence than ,so the expression is equivalent to

```<code>(i = 7), i++, i++;
</code>```

which is perfectly well defined behaviour because , is a sequence point.

As far as

```<code>i = ++i + 1; //the behavior is unspecified
</code>```

is concerned the behaviour is undefined in C++03 but well defined in C++0x. If you have the C++0x draft you can check out in section 1.9/15

```<code>i = i++ + 1; // the behavior is undeﬁned
</code>```

Title: Error in the standards?

Body:
§5/4 C++ standard

i = 7, i++, i++;  // i becomes 9
i = ++i + 1;  //the behavior is unspecified

That should be changed to

i = 7, i++, i++;  // the behavior is undefined
i = ++i + 1;  //the behavior is undefined

right?

Body:
i = 7, i++, i++; // i becomes 9

is perfectly fine. Operator = has higher precedence than ,so the expression is equivalent to

(i = 7), i++, i++;

which is perfectly well defined behaviour because , is a sequence point.

As far as

i = ++i + 1; //the behavior is unspecified

is concerned the behaviour is undefined in C++03 but well defined in C++0x. If you have the C++0x draft you can check out in section 1.9/15

i = i++ + 1; // the behavior is undeﬁned


问:
Android Toggle Button - Material Design
How do I implement the Toggle Buttons as specified in Material Design guidelines here?

Is it available out of the box from Android Design Support Library or is there any third party library available?

答:
You can use SwitchCompat if your activity has backwards compatibility.See below example.

```<code><android.support.v7.widget.SwitchCompat
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"/>
</code>```

Happy coding :D

Title: Android Toggle Button - Material Design

Body:
You can use SwitchCompat if your activity has backwards compatibility.See below example.

<android.support.v7.widget.SwitchCompat
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"/>

Happy coding :D


问:
symmetricds with in-memory hsqldb
So, i'm trying to migrate mysql db to hsqldb in memory. I'm using symmetricds for this. I've started the symmetricds as a service connected to mysql with following properties:

```<code>engine.name=corp-000
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost/corp?tinyInt1isBit=false
db.user=root
db.password=
registration.url=
sync.url=http://localhost:31415/sync/corp-000
group.id=corp
external.id=000
job.purge.period.time.ms=7200000
job.routing.period.time.ms=5000
job.push.period.time.ms=10000
job.pull.period.time.ms=10000
initial.load.create.first=true
auto.registration=true
auto.reload=true
</code>```

Created and loaded all the sym tables with the required data.

Next i created a clientnode through java using ClientSymmetricEngine. This is my java code:

```<code>public ClientNode(File file) throws FileNotFoundException, IOException {
  propFile = file;
  Properties propertiesFile = new Properties();
  propertiesFile.load(new FileReader(propFile));
  cEngine = new ClientSymmetricEngine(propertiesFile, true);
  //getcEngine().openRegistration("store", "001");// client is the name of the node group and 001 is the ID
  getcEngine().setup();
  getcEngine().start();
  }
public ClientSymmetricEngine getcEngine() {
  return cEngine;
}
</code>```

This is the clientNode property file:

```<code>engine.name=store-001
db.driver=org.hsqldb.jdbcDriver
db.url=jdbc:hsqldb:mem:store001
db.user=sa
db.password=
registration.url=http://localhost:31415/sync/corp-000
group.id=store
external.id=001
job.routing.period.time.ms=5000
job.push.period.time.ms=10000
job.pull.period.time.ms=10000
</code>```

Following is my code to startup the clientNode and fetch data from the replicated table running on the same JVM:

```<code>public static void main(String[] args) {
  try {
    new ClientNode(new File("C:/Train/src/main/resources/store-001.properties"));
    Thread.currentThread();
    Thread.sleep(40000);
    Class.forName("org.hsqldb.jdbcDriver");
    con = DriverManager.getConnection("jdbc:hsqldb:mem:store001;create=false", "sa", "");
    System.out.println("Connection created successfully");
    stmt = con.createStatement();
    rs = stmt.executeQuery("SELECT item_id, name FROM item");
    while (rs.next()) {
      System.out.println(rs.getInt("item_id") + " | " + rs.getString("name"));
    }
  } catch (Exception e) {
    e.printStackTrace(System.out);
  }
}
</code>```

When i run the main(), i see that symmetricds does the replication from mysql to hsql. But when i try to fetch the same data from hsql, i get the table object not found exception.

```<code>java.sql.SQLException: user lacks privilege or object not found: ITEM
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.fetchResult(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.executeQuery(Unknown Source)
at hsqlDB.FetchData.<init>(FetchData.java:24)
at hsqlDB.ConnectDatabase.main(ConnectDatabase.java:15)
</code>```

Attaching the full stacktrace.

I would appreciate it if someone could tell me what i'm doing wrong here.

答:
If you look at the statement it uses to create the table, the table name and column names are quoted, which makes them case sensitive.  Change your SQL query to use the same case and quoting, like this:</p>

```<code>rs = stmt.executeQuery("SELECT \"item_id\", \"name\" FROM \"item\"");
</code>```

Title: symmetricds with in-memory hsqldb

Body:
So, i'm trying to migrate mysql db to hsqldb in memory. I'm using symmetricds for this. I've started the symmetricds as a service connected to mysql with following properties:

engine.name=corp-000
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost/corp?tinyInt1isBit=false
db.user=root
db.password=
registration.url=
sync.url=http://localhost:31415/sync/corp-000
group.id=corp
external.id=000
job.purge.period.time.ms=7200000
job.routing.period.time.ms=5000
job.push.period.time.ms=10000
job.pull.period.time.ms=10000
initial.load.create.first=true
auto.registration=true
auto.reload=true

Created and loaded all the sym tables with the required data.

Next i created a clientnode through java using ClientSymmetricEngine. This is my java code:

public ClientNode(File file) throws FileNotFoundException, IOException {
  propFile = file;
  Properties propertiesFile = new Properties();
  propertiesFile.load(new FileReader(propFile));
  cEngine = new ClientSymmetricEngine(propertiesFile, true);
  //getcEngine().openRegistration("store", "001");// client is the name of the node group and 001 is the ID
  getcEngine().setup();
  getcEngine().start();
  }
public ClientSymmetricEngine getcEngine() {
  return cEngine;
}

This is the clientNode property file:

engine.name=store-001
db.driver=org.hsqldb.jdbcDriver
db.url=jdbc:hsqldb:mem:store001
db.user=sa
db.password=
registration.url=http://localhost:31415/sync/corp-000
group.id=store
external.id=001
job.routing.period.time.ms=5000
job.push.period.time.ms=10000
job.pull.period.time.ms=10000

Following is my code to startup the clientNode and fetch data from the replicated table running on the same JVM:

public static void main(String[] args) {
  try {
    new ClientNode(new File("C:/Train/src/main/resources/store-001.properties"));
    Thread.currentThread();
    Thread.sleep(40000);
    Class.forName("org.hsqldb.jdbcDriver");
    con = DriverManager.getConnection("jdbc:hsqldb:mem:store001;create=false", "sa", "");
    System.out.println("Connection created successfully");
    stmt = con.createStatement();
    rs = stmt.executeQuery("SELECT item_id, name FROM item");
    while (rs.next()) {
      System.out.println(rs.getInt("item_id") + " | " + rs.getString("name"));
    }
  } catch (Exception e) {
    e.printStackTrace(System.out);
  }
}

When i run the main(), i see that symmetricds does the replication from mysql to hsql. But when i try to fetch the same data from hsql, i get the table object not found exception.

java.sql.SQLException: user lacks privilege or object not found: ITEM
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.fetchResult(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.executeQuery(Unknown Source)
at hsqlDB.FetchData.<init>(FetchData.java:24)
at hsqlDB.ConnectDatabase.main(ConnectDatabase.java:15)

Attaching the full stacktrace.

I would appreciate it if someone could tell me what i'm doing wrong here.

Body:
If you look at the statement it uses to create the table, the table name and column names are quoted, which makes them case sensitive.  Change your SQL query to use the same case and quoting, like this:

rs = stmt.executeQuery("SELECT \"item_id\", \"name\" FROM \"item\"");


问:
Why does ElasticSearch use "must" and "should" rather than the more conventional boolean names "and"/"or"?
Is there a semantic difference between should and or? Or some engineering reason?

For example, I could imagine that it could help make an ElasticSearch query look different from a query in another search language.

Understanding the design decision would guide me in the intended uses of the query language.

答: Must and should are more comfortable to build complex boolean logic query. If you have to build only simple queries and you want to use and and or operators you could use query string query https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html . I suggest to take a look here, that is explained the use of must should operators https://www.elastic.co/blog/lost-in-translation-boolean-operations-and-filters-in-the-bool-query</p>


问:
How to save the attachment from an incoming email in Django's FileField?
I'm trying to save any attachments of incoming emails to a FileField in Django.

The model looks like this:

```<code>class Email(models.Model):
  ...
  attachment = models.FileField(upload_to='files/%Y/%m/%d', null=True, blank=True)
  ...

  def __unicode__(self):
    return self.contents[:20]
</code>```

I wrote this function to return the attachments.

```<code>def get_attachments(email_object):
    attachments = []
    for part in email_object.walk():
        # content_type = part.get_content_type()
        content_disposition = part.get("Content-Disposition")
        if content_disposition and content_disposition.lower().startswith("attachment"):
            attachments.append(part)
    return attachments
</code>```

Now I have a list of instances of the email object, and I'm not sure how to save them as a file in the FileField. attachment.get_content_type() returns image/jpeg. But how do I go from here to making it somehting that can be saved in the file field?

Thanks for all help.

答:
To save a email attachment to the directory and save the record in the model, you need to do the following,</p>

```<code>#firstly change your model design
#an email can have 0 - n attachments

class EmailAttachment(models.Model):
    email = models.ForeignKey(Email)
    document = models.FileField(upload_to='files/%Y/%m/%d')

#if you want to save an attachment
# assume message is multipart
# 'msg' is email.message instance
for part in msg.get_payload():
    if 'attachment' in part.get('Content-Disposition',''):
        attachment = EmailAttachment()
        #saving it in a <uuid>.msg file name
        #use django ContentFile to manage files and BytesIO for stream
        attachment.document.save(uuid.uuid4().hex + ".msg",
            ContentFile(
                BytesIO(
                    msg.get_payload(decode=True)
                ).getvalue()
            )
        )
</code>```

Body:
I'm trying to save any attachments of incoming emails to a FileField in Django.

The model looks like this:

class Email(models.Model):
  ...
  attachment = models.FileField(upload_to='files/%Y/%m/%d', null=True, blank=True)
  ...

  def __unicode__(self):
    return self.contents[:20]

I wrote this function to return the attachments.

def get_attachments(email_object):
    attachments = []
    for part in email_object.walk():
        # content_type = part.get_content_type()
        content_disposition = part.get("Content-Disposition")
        if content_disposition and content_disposition.lower().startswith("attachment"):
            attachments.append(part)
    return attachments

Now I have a list of instances of the email object, and I'm not sure how to save them as a file in the FileField. attachment.get_content_type() returns image/jpeg. But how do I go from here to making it somehting that can be saved in the file field?

Thanks for all help.

Body:
To save a email attachment to the directory and save the record in the model, you need to do the following,

#firstly change your model design
#an email can have 0 - n attachments

class EmailAttachment(models.Model):
    email = models.ForeignKey(Email)
    document = models.FileField(upload_to='files/%Y/%m/%d')

#if you want to save an attachment
# assume message is multipart
# 'msg' is email.message instance
for part in msg.get_payload():
    if 'attachment' in part.get('Content-Disposition',''):
        attachment = EmailAttachment()
        #saving it in a <uuid>.msg file name
        #use django ContentFile to manage files and BytesIO for stream
        attachment.document.save(uuid.uuid4().hex + ".msg",
            ContentFile(
                BytesIO(
                    msg.get_payload(decode=True)
                ).getvalue()
            )
        )


问:
How can I pass a double array to a form and use it in multiple subs?
I already searched a lot but could not find a solution. I have a Form and in that Form I call another Form (let's say Form2). In Form 2 I can enter values in some textboxes and then I am passing these values as a double array back to Form 1:

```<code>Public Class Form1
  Dim a As Double
  Dim userDefined(3) As Double
  Dim Form_2 As Form2
  Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

    Form_2= New Form2
    Form_2.ShowDialog()
    a = userDefined(0)

  End Sub

  Public WriteOnly Property setUserValues As Array
    Set(value As Array)

        userDefined = value

    End Set
  End Property
End Class

Public Class Form2
  Dim userDefined(0 To 3) As Double

Private Sub Btn_transmitValues_Click(sender As System.Object, e As System.EventArgs) Handles Btn_transmitValues.Click

    userDefined(0) = Txt_1.Text
    userDefined(1) = Txt_2.Text
    userDefined(2) = Txt_3.Text
    userDefined(3) = Txt_4.Text

    Form1.setUserValues = userDefined

    Me.Dispose()

End Sub

End Class
</code>```

Now I want to use the values from the passed double array of Form2 in Form1 in the Button1_Click Sub. But when I define my array in Form1 as

```<code>Dim userDefined(3) As Double
</code>```

then a (also in Form1) is always 0. When I define my array in Form 1 as

```<code>Dim userDefined() As Double
</code>```

then I get the error "Object reference not set to an instance of an object" but when I hover over a the right value is passed. What can I do to get the right value for a? Thanks in advance.

答:
So I got it working but I dont know if this is a good style. Maybe anyone can tell if this is good or bad coding. I basically just changed the way the variables are being passed. First I had Form2 write the new variables into the array of Form1, now I have Form1 reading the values out of Form2.

The thing I don't link myself is, that the variables are being calculated in Form2, then Form2 is being disposed and after that the variables are getting read. Maybe this could problematic because I call variables of a closed Form?

```<code>Public Class Form1
  Dim a As Double
  Dim userDefined(3) As Double
  Dim Form_2 As Form2

  Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

    Form_2= New Form2
    Form_2.ShowDialog()
    userDefined = Form_2.getUserDefined

    a = userDefined(0)

  End Sub

End Class
</code>```

And Form 2:

```<code>Public Class Form2
  Dim _userDefined(0 To 3) As Double

Private Sub Btn_transmitValues_Click(sender As System.Object, e As System.EventArgs) Handles Btn_transmitValues.Click

    _userDefined(0) = Txt_1.Text
    _userDefined(1) = Txt_2.Text
    _userDefined(2) = Txt_3.Text
    _userDefined(3) = Txt_4.Text

    Me.Dispose()

End Sub

Public ReadOnly Property getUserDefined As Double()
    Get
        Return _userDefined
    End Get
End Property

End Class
</code>```

Body:
I already searched a lot but could not find a solution. I have a Form and in that Form I call another Form (let's say Form2). In Form 2 I can enter values in some textboxes and then I am passing these values as a double array back to Form 1:

Public Class Form1
  Dim a As Double
  Dim userDefined(3) As Double
  Dim Form_2 As Form2
  Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

    Form_2= New Form2
    Form_2.ShowDialog()
    a = userDefined(0)

  End Sub

  Public WriteOnly Property setUserValues As Array
    Set(value As Array)

        userDefined = value

    End Set
  End Property
End Class

Public Class Form2
  Dim userDefined(0 To 3) As Double

Private Sub Btn_transmitValues_Click(sender As System.Object, e As System.EventArgs) Handles Btn_transmitValues.Click

    userDefined(0) = Txt_1.Text
    userDefined(1) = Txt_2.Text
    userDefined(2) = Txt_3.Text
    userDefined(3) = Txt_4.Text

    Form1.setUserValues = userDefined

    Me.Dispose()

End Sub

End Class

Now I want to use the values from the passed double array of Form2 in Form1 in the Button1_Click Sub. But when I define my array in Form1 as

Dim userDefined(3) As Double

then a (also in Form1) is always 0. When I define my array in Form 1 as

Dim userDefined() As Double

then I get the error "Object reference not set to an instance of an object" but when I hover over a the right value is passed. What can I do to get the right value for a? Thanks in advance.

Body:
So I got it working but I dont know if this is a good style. Maybe anyone can tell if this is good or bad coding. I basically just changed the way the variables are being passed. First I had Form2 write the new variables into the array of Form1, now I have Form1 reading the values out of Form2.

The thing I don't link myself is, that the variables are being calculated in Form2, then Form2 is being disposed and after that the variables are getting read. Maybe this could problematic because I call variables of a closed Form?

Public Class Form1
  Dim a As Double
  Dim userDefined(3) As Double
  Dim Form_2 As Form2

  Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

    Form_2= New Form2
    Form_2.ShowDialog()
    userDefined = Form_2.getUserDefined

    a = userDefined(0)

  End Sub

End Class

And Form 2:

Public Class Form2
  Dim _userDefined(0 To 3) As Double

Private Sub Btn_transmitValues_Click(sender As System.Object, e As System.EventArgs) Handles Btn_transmitValues.Click

    _userDefined(0) = Txt_1.Text
    _userDefined(1) = Txt_2.Text
    _userDefined(2) = Txt_3.Text
    _userDefined(3) = Txt_4.Text

    Me.Dispose()

End Sub

Public ReadOnly Property getUserDefined As Double()
    Get
        Return _userDefined
    End Get
End Property

End Class


问:
Webpack 3, Babel and Tree shaking not working
I'm trying to find a way to tree-shake my modules and use Babel with Webpack.

If I take the example code from the webpack documentation (https://webpack.js.org/guides/tree-shaking/) and run it, the modules/functions/other exports that are not used are marked as unused harmony exports, which is the expected outcome. After running webpack with the -p argument (production), webpack uses UglifyJS to remove the dead and unused code (to tree-shake).

Now, if I add babel-loader to my webpack config file, my ES2015 modules are transpiled but now are not marked as unused exports anymore.

So for example:

math.js

```<code>export function square(x) {
  return x * x;
}

export function cube(x) {
  return x * x * x;
}
</code>```

app.js (my entry file)

```<code>import {square} from './math.js'
</code>```

Running this through webpack WITHOUT babel-loader, the cube function will get marked as unused and removed after compiling for production (-p).

Running this through webpack WITH babel-loader, the cube function will not be marked as unused and will stay in the compiled bundle.

What am I missing?

Edit

Here's a demo repo that can reproduce the situation

https://github.com/Milanzor/babel-and-treeshaking-question

Update

If I add a .babelrc:

```<code>{
  "presets": [
    ["@babel/preset-env", {
      "useBuiltIns": "entry",
      "debug": true,
      "targets": {
        "browsers": ["last 2 versions"]
      }
    }]
  ]
}
</code>```

I get the same result, but if I add modules: false to the preset-env options, Babel doesn't compile the modules to ES5 and Webpack marks the modules as unused again.

Conclusion

I need to find a way to tell Webpack that my modules are transpiled with Babel, or I need to find a way to tell Babel to scan for unused codes itself.

答:
Webpack's built-in tree shaking works on ES6 module syntax only. If you're using Babel's defaults settings, Babel will compile ES6 modules to CommonJS modules, leaving nothing for Webpack to work with.

Generally people using Webpack will want to pass modules: false to the preset that they are using for ES6 (probably preset-env?), thus doing

```<code>{
  presets: [
    ['env', { modules: false }],
  ],
}
</code>```

alternatively you could consider using a plugin like https://github.com/indutny/webpack-common-shake to enable tree-shaking for CommonJS modules.

Update

If you're using Babel 7 (and thus @babel/preset-env), the modules option is now automatically false when used in Webpack, so this explicit configuration should no longer be needed.

Body:
I'm trying to find a way to tree-shake my modules and use Babel with Webpack.

If I take the example code from the webpack documentation (https://webpack.js.org/guides/tree-shaking/) and run it, the modules/functions/other exports that are not used are marked as unused harmony exports, which is the expected outcome. After running webpack with the -p argument (production), webpack uses UglifyJS to remove the dead and unused code (to tree-shake).

Now, if I add babel-loader to my webpack config file, my ES2015 modules are transpiled but now are not marked as unused exports anymore.

So for example:

math.js

export function square(x) {
  return x * x;
}

export function cube(x) {
  return x * x * x;
}

app.js (my entry file)

import {square} from './math.js'

Running this through webpack WITHOUT babel-loader, the cube function will get marked as unused and removed after compiling for production (-p).

Running this through webpack WITH babel-loader, the cube function will not be marked as unused and will stay in the compiled bundle.

What am I missing?

Edit

Here's a demo repo that can reproduce the situation

https://github.com/Milanzor/babel-and-treeshaking-question

Update

If I add a .babelrc:

{
  "presets": [
    ["@babel/preset-env", {
      "useBuiltIns": "entry",
      "debug": true,
      "targets": {
        "browsers": ["last 2 versions"]
      }
    }]
  ]
}

I get the same result, but if I add modules: false to the preset-env options, Babel doesn't compile the modules to ES5 and Webpack marks the modules as unused again.

Conclusion

I need to find a way to tell Webpack that my modules are transpiled with Babel, or I need to find a way to tell Babel to scan for unused codes itself.

Body:
Webpack's built-in tree shaking works on ES6 module syntax only. If you're using Babel's defaults settings, Babel will compile ES6 modules to CommonJS modules, leaving nothing for Webpack to work with.

Generally people using Webpack will want to pass modules: false to the preset that they are using for ES6 (probably preset-env?), thus doing

{
  presets: [
    ['env', { modules: false }],
  ],
}

alternatively you could consider using a plugin like https://github.com/indutny/webpack-common-shake to enable tree-shaking for CommonJS modules.

Update

If you're using Babel 7 (and thus @babel/preset-env), the modules option is now automatically false when used in Webpack, so this explicit configuration should no longer be needed.

ContentLicense: CC BY-SA 4.0


问:
Algorithm finding path in an undirected tree
Suppose I am given a undirected tree and I need to find a path(the only path) between two nodes.

What is the best algorithm to do it.I probably could use a Dijkstra's algorithm but there a probably something better for trees.

C++ example would be helpful but not necessary

Thank you

答:
Supposing you have

```<code>struct Node
{
    std::vector<Node *> children;
};
</code>```

then what could be done is traversing the whole tree starting at root keeping the whole chain during the traversal. If you find e.g. node1 then you save the current chain, if you find node2 then you check for the intersection... in code (UNTESTED):

```<code>bool findPath(std::vector<Node *>& current_path, // back() is node being visited
              Node *n1, Node *n2,                // interesting nodes
              std::vector<Node *>& match,        // if not empty back() is n1/n2
              std::vector<Node *>& result)       // where to store the result
{
    if (current_path.back() == n1 || current_path.back() == n2)
    {
        // This is an interesting node...
        if (match.size())
        {
            // Now is easy: current_path/match are paths from root to n1/n2
            ...
            return true;
        }
        else
        {
            // This is the first interesting node found
            match = current_path;
        }
    }
    for (std::vector<Node *>::iterator i=current_path.back().children.begin(),
                                       e=current_path.back().children.end();
         i != e; ++i)
    {
        current_path.push_back(*i);
        if (findPath(current_path, n1, n2, match, result))
          return true;
        current_path.pop_back(); // *i
    }
    return false;
}
</code>```

Body:
Supposing you have

struct Node
{
    std::vector<Node *> children;
};

then what could be done is traversing the whole tree starting at root keeping the whole chain during the traversal. If you find e.g. node1 then you save the current chain, if you find node2 then you check for the intersection... in code (UNTESTED):

bool findPath(std::vector<Node *>& current_path, // back() is node being visited
              Node *n1, Node *n2,                // interesting nodes
              std::vector<Node *>& match,        // if not empty back() is n1/n2
              std::vector<Node *>& result)       // where to store the result
{
    if (current_path.back() == n1 || current_path.back() == n2)
    {
        // This is an interesting node...
        if (match.size())
        {
            // Now is easy: current_path/match are paths from root to n1/n2
            ...
            return true;
        }
        else
        {
            // This is the first interesting node found
            match = current_path;
        }
    }
    for (std::vector<Node *>::iterator i=current_path.back().children.begin(),
                                       e=current_path.back().children.end();
         i != e; ++i)
    {
        current_path.push_back(*i);
        if (findPath(current_path, n1, n2, match, result))
          return true;
        current_path.pop_back(); // *i
    }
    return false;
}


问:
how to read data from spreadsheet with .xlsm format in perl?
I want read data  from spreadsheet ,which is .xlsm format.I am unable to access it.its showing blank while access the data .so i want how to access .xlsm format in perl.

Here is what I have tried:

```<code>#!/usr/bin/perl
use strict;
use warnings;

use Spreadsheet::Read;
use Spreadsheet::read qw(ReadData);

my $book = ReadData ('C:\Perl64\bin\sample.xlsm');
   foreach my $line(1..1000) {
           my @rows =Spreadsheet::Read::cellrow($book->[0],"$line");
           print "@rows";
}
</code>```

答:
seems the module you used doesn't work on xlsm files

consider using Spreadsheet::Reader::ExcelXML instead ;)

http://search.cpan.org/~jandrew/Spreadsheet-Reader-ExcelXML/lib/Spreadsheet/Reader/ExcelXML.pm

also beware, you should use push instead of @rows = ..., this way, you won't overwrite @rows at each for iteration

when you try to open a file you should add or die "error message"; at the end of the open, this way you will see if the file opened correctly

my $book = ReadData ('C:\Perl64\bin\sample.xlsm') or die "error while opening the file"; triggers the error with your example code

Body:
I want read data  from spreadsheet ,which is .xlsm format.I am unable to access it.its showing blank while access the data .so i want how to access .xlsm format in perl.

Here is what I have tried:

#!/usr/bin/perl
use strict;
use warnings;

use Spreadsheet::Read;
use Spreadsheet::read qw(ReadData);

my $book = ReadData ('C:\Perl64\bin\sample.xlsm');
   foreach my $line(1..1000) {
           my @rows =Spreadsheet::Read::cellrow($book->[0],"$line");
           print "@rows";
}


问:
How to use Windsor IoC in ASP.net Core 2
How can I use Castle Windsor as an IOC instead of the default .net core IOC container?

I have built a service resolver that depends on WindsorContainer to resolve services.

Something like:

```<code>public class ServiceResolver
{
    private static WindsorContainer container;
    public ServiceResolver()
    {
        container = new WindsorContainer();
        // a method to register components in container
        RegisterComponents(container);
    }

    public IList<T> ResolveAll<T>()
    {
        return container.ResolveAll<T>().ToList();
    }
}
</code>```

Can not figure out how to let my .net core 2 web API use this resolver as a replacement for IServiceCollection.

答:
For .net core, which centers DI around the IServiceProvider, you would need to create you own wrapper

Reference : Introduction to Dependency Injection in ASP.NET Core: Replacing the default services container

```<code>public class ServiceResolver : IServiceProvider {
    private static WindsorContainer container;

    public ServiceResolver(IServiceCollection services) {
        container = new WindsorContainer();
        // a method to register components in container
        RegisterComponents(container, services);
    }

    public object GetService(Type serviceType) {
        return container.Resolve(serviceType);
    }

    //...
}
</code>```

and then configure the container in ConfigureServices and return an IServiceProvider:

When using a third-party DI container, you must change ConfigureServices so that it returns IServiceProvider instead of void.

```<code>public IServiceProvider ConfigureServices(IServiceCollection services) {
    services.AddMvc();
    // Add other framework services

    // Add custom provider
    var container = new ServiceResolver(services);
    return container;
}
</code>```

At runtime, your container will be used to resolve types and inject dependencies.

Body:
How can I use Castle Windsor as an IOC instead of the default .net core IOC container?

I have built a service resolver that depends on WindsorContainer to resolve services.

Something like:

public class ServiceResolver
{
    private static WindsorContainer container;
    public ServiceResolver()
    {
        container = new WindsorContainer();
        // a method to register components in container
        RegisterComponents(container);
    }

    public IList<T> ResolveAll<T>()
    {
        return container.ResolveAll<T>().ToList();
    }
}

Can not figure out how to let my .net core 2 web API use this resolver as a replacement for IServiceCollection.

Body:
For .net core, which centers DI around the IServiceProvider, you would need to create you own wrapper

Reference : Introduction to Dependency Injection in ASP.NET Core: Replacing the default services container

public class ServiceResolver : IServiceProvider {
    private static WindsorContainer container;

    public ServiceResolver(IServiceCollection services) {
        container = new WindsorContainer();
        // a method to register components in container
        RegisterComponents(container, services);
    }

    public object GetService(Type serviceType) {
        return container.Resolve(serviceType);
    }

    //...
}

and then configure the container in ConfigureServices and return an IServiceProvider:

When using a third-party DI container, you must change ConfigureServices so that it returns IServiceProvider instead of void.

public IServiceProvider ConfigureServices(IServiceCollection services) {
    services.AddMvc();
    // Add other framework services

    // Add custom provider
    var container = new ServiceResolver(services);
    return container;
}

At runtime, your container will be used to resolve types and inject dependencies.


问:
how to implement a user authentication system and create accounts for social network login?
I am a newbie of user authentication, currently I am playing around with Azure AD B2C, it seems good but I want to create native pages in my app for user sign up and login instead of using the azure policy, so I want to implement this function in my app:

A user can sign up in to my app by filling his email and password, and then, a set of optional profile attributes. He also can login in to my app by using Facebook or Google, etc; and in the first time login, my app will ask the user to fill in the user profile and create an account for him in my app. So the user will eventually have an account for my app. I think this is very common in mobile apps, but I just don't know what is its structure and how it works, here is an example:

Adobe XD sign up or login page

The other question is how the server should verify a request sent by a user? Does it need to verify the Facebook access token, Google access token or my app access token embedded in the request separately? Or is there a way to safely verify the user identity in the same way?

I don't know how to put all the things together to make an app, please tell me how to implement it, or which services (like azure ad b2c) can satisfy my need, or please recommend some open source ios app projects which implement this function.

Thanks a lot, I've been thinking this problem for a couple of days :/

答:
You should decide what solution would you like to use: your own solution or external, free or commercial. I can suggest you to take a look to https://auth0.com. They have manual for iOS: https://auth0.com/docs/quickstart/native/ios-swift/getting-started. Also you can find a lot of examples how to use auth0 in Internet.

Please be careful if you will use Facebook and Google APIs. Someday we had an error in our application because of gender field. Facebook API return MALE/FEMALE, but Google also have OTHER and this caused an error - on our side we had only MALE/FEMALE gender in our Enumeration and no OTHER type (gender validation failed because of this).


问:
Django and Middleware which uses request.user is always Anonymous
I'm trying to make middleware which alters some fields for the user based on subdomain, etc...

The only problem is the request.user always comes in as AnonymousUser within the middleware, but is then the correct user within the views.  I've left the default authentication and session middleware django uses within the settings.

There is a similar question here: Django, request.user is always Anonymous User
But doesn't overly answer the total question because I'm not using different authentication methods, and djangos authentication is running before I invoke my own middleware.

Is there a way, while using DRF, to get the request.user within the middleware?  I'll show some sample code here:

```<code>class SampleMiddleware(object):

  def process_view(self, request, view_func, view_args, view_kwargs):
    #This will be AnonymousUser.  I need it to be the actual user making the request.
    print (request.user)

  def process_response(self, request, response):
    return response
</code>```

with process_request:

```<code>class SampleMiddleware(object):

  def process_request(self, request):
    #This will be AnonymousUser.  I need it to be the actual user making the request.
    print (request.user)

  def process_response(self, request, response):
    return response
</code>```

答:
Based on Daniel Dubovski's very elegant solution above, here's an example of middleware for Django 1.11:</p>

```<code>from django.utils.functional import SimpleLazyObject
from organization.models import OrganizationMember
from django.core.exceptions import ObjectDoesNotExist

def get_active_member(request):
    try:
        active_member = OrganizationMember.objects.get(user=request.user)
    except (ObjectDoesNotExist, TypeError):
        active_member = None
    return active_member

class OrganizationMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        request.active_member = SimpleLazyObject(lambda: get_active_member(request))

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.
        return response
</code>```

Body:
I'm trying to make middleware which alters some fields for the user based on subdomain, etc...

The only problem is the request.user always comes in as AnonymousUser within the middleware, but is then the correct user within the views.  I've left the default authentication and session middleware django uses within the settings.

There is a similar question here: Django, request.user is always Anonymous User
But doesn't overly answer the total question because I'm not using different authentication methods, and djangos authentication is running before I invoke my own middleware.

Is there a way, while using DRF, to get the request.user within the middleware?  I'll show some sample code here:

class SampleMiddleware(object):

  def process_view(self, request, view_func, view_args, view_kwargs):
    #This will be AnonymousUser.  I need it to be the actual user making the request.
    print (request.user)

  def process_response(self, request, response):
    return response

with process_request:

class SampleMiddleware(object):

  def process_request(self, request):
    #This will be AnonymousUser.  I need it to be the actual user making the request.
    print (request.user)

  def process_response(self, request, response):
    return response

Body:
Based on Daniel Dubovski's very elegant solution above, here's an example of middleware for Django 1.11:

from django.utils.functional import SimpleLazyObject
from organization.models import OrganizationMember
from django.core.exceptions import ObjectDoesNotExist

def get_active_member(request):
    try:
        active_member = OrganizationMember.objects.get(user=request.user)
    except (ObjectDoesNotExist, TypeError):
        active_member = None
    return active_member

class OrganizationMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        request.active_member = SimpleLazyObject(lambda: get_active_member(request))

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.
        return response