答:
Given the following example data,

```<code>+----+---+---+
| Id | A | B |
+----+---+---+
| 1  | 2 | 3 |
+----+---+---+
| 2  | 3 | 4 |
+----+---+---+
| 3  | 4 | 5 |
+----+---+---+
| 4  | 5 | 6 |
+----+---+---+
| 5  | 6 | 7 |
+----+---+---+
</code>```

the following short SQL statement produces the desired output:

```<code>select A - B + lag(A - B, 1, 0) over (order by id)
from test

+----+
| -1 |
+----+
| -2 |
+----+
| -2 |
+----+
| -2 |
+----+
| -2 |
+----+
</code>```

Note that the Lag function takes three arguments: the first is the expression you would like evaluated for the "lagged" record, the second is the amount of the lag (defaults to 1), and the third is the value to return if the expression cannot be computed (e.g. if it is the first record).

Title: SQL Server sum field from previous calculation

Body:
In SQL Server, I have table with 4 column

 artid    num     A           B
   46     1     417636000     0
   47     1     15024000      0
  102     1     3418105650    0
  226     1     1160601286    0
  60     668    260000        0
  69     668    5500000       0

I want in result set create new column for some calculation

This column should have value like this:

artid       num         a                      b                      newColumnValue
----------- ----------- ---------------------- ---------------------- ----------------------
46          1           417636000              0                      a-b+previous newColumnValue

I write this query, but I can't get previous newColumnValue:

select *, (a- b+ lag(a- b, 1, a- b) over (order by num,artid)) as newColumnValue
 FROM MainTbl
  ORDER BY  num,artid

i get this result

artid       num         a                      b                      newColumnValue
----------- ----------- ---------------------- ---------------------- ----------------------
46          1           417636000              0                      417636000
47          1           15024000               0                      432660000
102         1           3418105650             0                      3433129650
226         1           1160601286             0                      4578706936
60          668         260000                 0                      1160861286
69          668         5500000                0                      5760000

i want get this result

artid       num         a                      b                      newColumnValue
----------- ----------- ---------------------- ---------------------- ----------------------
46          1           417636000              0                      417636000
47          1           15024000               0                      432660000
102         1           3418105650             0                      3850765650
226         1           1160601286             0                      5011366936
60          668         260000                 0                      5011626936
69          668         5500000                0                      5017126936

Body:
Given the following example data,

+----+---+---+
| Id | A | B |
+----+---+---+
| 1  | 2 | 3 |
+----+---+---+
| 2  | 3 | 4 |
+----+---+---+
| 3  | 4 | 5 |
+----+---+---+
| 4  | 5 | 6 |
+----+---+---+
| 5  | 6 | 7 |
+----+---+---+

the following short SQL statement produces the desired output:

select A - B + lag(A - B, 1, 0) over (order by id)
from test

+----+
| -1 |
+----+
| -2 |
+----+
| -2 |
+----+
| -2 |
+----+
| -2 |
+----+

Note that the Lag function takes three arguments: the first is the expression you would like evaluated for the "lagged" record, the second is the amount of the lag (defaults to 1), and the third is the value to return if the expression cannot be computed (e.g. if it is the first record).


来源: stackexchange

问:
Why the interface IOrderedEnumerable<T> isn't covariant in T?
I was Looking at the declaration of IOrderedEnumerable an I was suprised that it isn't covariant in it's TElement type parameter .

```<code>public interface IOrderedEnumerable<TElement> : IEnumerable<TElement>, IEnumerable
{
    IOrderedEnumerable<TElement> CreateOrderedEnumerable<TKey>(Func<TElement, TKey> keySelector, IComparer<TKey> comparer, bool descending);
}
</code>```

What's the reason for which it was not made covariant  ?

答:
It's an oversight and that was fixed in .NET Core. Here is (closed) issue about that and here is pull request which fixes it.

It's not getting fixed in full .NET version I think because that's a breaking change. For example (idea is taken from this answer which is about another breaking change, but applies here too):

```<code>public class Base
{
    public void DoSomething(IOrderedEnumerable<string> strings)
    {
        Console.WriteLine("Base");
    }
}

public class Derived : Base
{
    public void DoSomething(IOrderedEnumerable<object> objects)
    {
        Console.WriteLine("Derived");
    }
}
</code>```

Then you call

```<code>Derived d = new Derived();
d.DoSomething(new List<string>().OrderBy(c => c));
</code>```

If IOrderedEnumerable is not covariant - Base method would be called. Now suppose we change that to covariant. When we next time compile this code, suddenly Derived method is called.

ContentLicense: CC BY-SA 3.0

Body:
I was Looking at the declaration of IOrderedEnumerable an I was suprised that it isn't covariant in it's TElement type parameter .

public interface IOrderedEnumerable<TElement> : IEnumerable<TElement>, IEnumerable
{
    IOrderedEnumerable<TElement> CreateOrderedEnumerable<TKey>(Func<TElement, TKey> keySelector, IComparer<TKey> comparer, bool descending);
}

What's the reason for which it was not made covariant  ?

Body:
It's an oversight and that was fixed in .NET Core. Here is (closed) issue about that and here is pull request which fixes it.

It's not getting fixed in full .NET version I think because that's a breaking change. For example (idea is taken from this answer which is about another breaking change, but applies here too):

public class Base
{
    public void DoSomething(IOrderedEnumerable<string> strings)
    {
        Console.WriteLine("Base");
    }
}

public class Derived : Base
{
    public void DoSomething(IOrderedEnumerable<object> objects)
    {
        Console.WriteLine("Derived");
    }
}

Then you call

Derived d = new Derived();
d.DoSomething(new List<string>().OrderBy(c => c));

If IOrderedEnumerable is not covariant - Base method would be called. Now suppose we change that to covariant. When we next time compile this code, suddenly Derived method is called.


问:
Request Location permission at runtime not working
I have wrote my code from this documentation. The askForPermission() method is called when a button is clicked. But every time I click on the button it displays the else part, I mean Permission denied. What I am doing wrong here. How to open the pop up for requesting permission. And after granting permission how can I display the latitude and longitude in a TOAST message. ?? I am new in android and I will be very thankful if anyone can solve it.

I have tried enabling LOCATION permission from the mobile's setting page for my application. But still when I click on the button it displays PERMISSION DENIED

events.java

```<code>package com.example.borntoflirt.design1;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;

import java.util.Calendar;
import java.text.SimpleDateFormat;

public class events extends AppCompatActivity {

    private Button getLocationBtn;
    public static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;

    private FusedLocationProviderClient mFusedLocationClient;

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

        getLocationBtn = (Button) findViewById(R.id.getLocation);

        getLocationBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //First of All check for permission .
                askForPermission();
            }
        });

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    }

    private void askForPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.
                Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_SHORT).show();

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show();
            }
            return;

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

}
</code>```

答:
This is the answer for your question in comment. So to access location and latitude and longitude you need to implement couple interfaces in your activity class:
implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener

Then override necessary methods. In onConnected method make request to location either using deprecated FusedLocationApi which still works or new  FusedLocationProviderClient. Also you will get onLocationChanged method with parameter Location there you can access the latitude and longitude using location.getLatitude(); and location.getLongitude();

You will also have to make connection to GoogleApiClient for example:

protected synchronized void buildGoogleApiClient() {
        googleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        googleApiClient.connect();
    }

Handle removing location updates in onPause and making request again in onResume

Body:
I have wrote my code from this documentation. The askForPermission() method is called when a button is clicked. But every time I click on the button it displays the else part, I mean Permission denied. What I am doing wrong here. How to open the pop up for requesting permission. And after granting permission how can I display the latitude and longitude in a TOAST message. ?? I am new in android and I will be very thankful if anyone can solve it.

I have tried enabling LOCATION permission from the mobile's setting page for my application. But still when I click on the button it displays PERMISSION DENIED

events.java

package com.example.borntoflirt.design1;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;

import java.util.Calendar;
import java.text.SimpleDateFormat;

public class events extends AppCompatActivity {

    private Button getLocationBtn;
    public static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;

    private FusedLocationProviderClient mFusedLocationClient;

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

        getLocationBtn = (Button) findViewById(R.id.getLocation);

        getLocationBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //First of All check for permission .
                askForPermission();
            }
        });

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    }

    private void askForPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.
                Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_SHORT).show();

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show();
            }
            return;

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

}


问:
Remove rows from Pandas Dataframe which contain no numbers and no literal
i have a column called 'str' in a Panda Dataframe.
As i intend to delete all rows from it which contain no numerical values [0-9]
or literal [a-z], the following statement did not work:

```<code>data[data['str'].str.contains(r"[a-zA-z0-9]") == True]
</code>```

After the execution I analysed the column values. There are still values in it like:

("[[", "^")

and it deletes values (which is in this case not desired):

("1", "2016", "20160715")

Is there are anyone who could help me?

Best Regards

答:
```<code>import pandas as pd
data = pd.DataFrame([[']','//','.'],['a2','b2','c2'],['a3','b',']']],columns=['A','B','C'])
test = data['A']str.match('^[\w\d_-]*$')
data = data[test]
</code>```

Output:

```<code>  A   B   C
1  a2  b2  c2
2  a3   b   ]
</code>```

If you are OK with non-letter-non-number characters, I think the best way would be a dictionary of those characters followed by data.replace.

```<code>import pandas as pd
import numpy as np
df = pd.DataFrame([[']','//','.'],['a!','b2','c2'],['a3','b!',']']],columns=['A','B','C'])
df
Output:
 A   B   C
0   ]  //   .
1  a!  b2  c2
2  a3  b!   ]

remove = {'.':np.nan, '/':np.nan, ']':np.nan}  # The format is {'thing to be replaced':'new thing'}

df['A'] = df['A'].replace(remove) # Checks one column
df
Output:
    A    B   C
0  NaN  //   .
1   a!  b2  c2
2   a3  b!   ]

df.dropna()
df
Output:
  A   B   C
1  a!  b2  c2
2  a3  b!   ]
</code>```

Make sure to replace for your specfic column. dropna() will delete any column with any NaN value.

As a cautionary, don't use Python methods such as "str" as your placeholders. Probably won't burn you here, however.

Body:
i have a column called 'str' in a Panda Dataframe.
As i intend to delete all rows from it which contain no numerical values [0-9]
or literal [a-z], the following statement did not work:

data[data['str'].str.contains(r"[a-zA-z0-9]") == True]

After the execution I analysed the column values. There are still values in it like:

("[[", "^")

and it deletes values (which is in this case not desired):

("1", "2016", "20160715")

Is there are anyone who could help me?

Best Regards

Body:
import pandas as pd
data = pd.DataFrame([[']','//','.'],['a2','b2','c2'],['a3','b',']']],columns=['A','B','C'])
test = data['A']str.match('^[\w\d_-]*$')
data = data[test]

Output:

  A   B   C
1  a2  b2  c2
2  a3   b   ]

If you are OK with non-letter-non-number characters, I think the best way would be a dictionary of those characters followed by data.replace.

import pandas as pd
import numpy as np
df = pd.DataFrame([[']','//','.'],['a!','b2','c2'],['a3','b!',']']],columns=['A','B','C'])
df
Output:
 A   B   C
0   ]  //   .
1  a!  b2  c2
2  a3  b!   ]

remove = {'.':np.nan, '/':np.nan, ']':np.nan}  # The format is {'thing to be replaced':'new thing'}

df['A'] = df['A'].replace(remove) # Checks one column
df
Output:
    A    B   C
0  NaN  //   .
1   a!  b2  c2
2   a3  b!   ]

df.dropna()
df
Output:
  A   B   C
1  a!  b2  c2
2  a3  b!   ]

Make sure to replace for your specfic column. dropna() will delete any column with any NaN value.

As a cautionary, don't use Python methods such as "str" as your placeholders. Probably won't burn you here, however.


问:
How to cut a hierarchy cluster tree by a given maximum within cluster distance?
I am working on a one-dimensional gene positions data which is like

[705118, 705118, 832132, 860402, 865710, 867206, 925364, 925364,925364]

(around 2000 items in one array) and I wanna divide the array into clusters with a maximum within cluster distance less or equal to 2000.

So I used the

```<code>chrd=scipy.spatial.distance.pdist(chrn,metric='euclidean')
</code>```

to get the distance matrix and then

```<code>scipy.cluster.hierarchy.linkage(chrd,method='average',metric='euclidean')
</code>```

to get the linkage matrix.

But there is no such function in scipy.cluster.hiearchy.fcluster can cut the hierarchy tree based the the maximum within cluster distance.

Does anyone have any idea about how to handle this?
I try to rewrite a hierarchy algorithm which can include such threshold but it seems to be really hard to do >.<

Thanks in advance

答:
Use complete linkage if you need a maximum distance of objects, not average.

Then cut the tree at the desired height.

Alternatively, you can also implement Leader clustering. It's stupid, but he maximum distance is twice the distance of the cluster radius there.

Body:
I am working on a one-dimensional gene positions data which is like

[705118, 705118, 832132, 860402, 865710, 867206, 925364, 925364,925364]

(around 2000 items in one array) and I wanna divide the array into clusters with a maximum within cluster distance less or equal to 2000.

So I used the

chrd=scipy.spatial.distance.pdist(chrn,metric='euclidean')

to get the distance matrix and then

scipy.cluster.hierarchy.linkage(chrd,method='average',metric='euclidean')

to get the linkage matrix.

But there is no such function in scipy.cluster.hiearchy.fcluster can cut the hierarchy tree based the the maximum within cluster distance.

Does anyone have any idea about how to handle this?
I try to rewrite a hierarchy algorithm which can include such threshold but it seems to be really hard to do >.<

Thanks in advance


问:
How to find out the embedded JDK version of Android Studio?
I'm trying to find out what JDK's version does my Android Studio use.
I'm confused, because i have many versions in my /Program Files/Java catalog

Unfortunately the project structure doesn't have any JDK's version number.

答:
The embedded JDK is included in the Android Studio install. If you open the folder where you installed Android Studio, you'll see a jre folder in it:

Inside the folder there is a file called THIRD_PARTY_README in which the second sentence says:

```<code>%% This notice is provided with respect to ASM Bytecode Manipulation
Framework v5.0.3, which may be included with JRE 8, and JDK 8, and
OpenJDK 8.
</code>```

I'm using Android Studio 3.0, in which the embedded JDK version is 8. To find the version in any later version though, go to [SDK_INSTALL_ROOT]/jre/ and find THIRD_PARTY_README

THIRD_PARTY_README is in my system defined as a file and not a txt file. You can open it in Notepad, Notepad++ or any other text editor. The content is plain text. You can also look for a file called release, which contains similar information about versions.

ContentLicense: CC BY-SA 4.0

Body:
The embedded JDK is included in the Android Studio install. If you open the folder where you installed Android Studio, you'll see a jre folder in it:

Inside the folder there is a file called THIRD_PARTY_README in which the second sentence says:

%% This notice is provided with respect to ASM Bytecode Manipulation
Framework v5.0.3, which may be included with JRE 8, and JDK 8, and
OpenJDK 8.

I'm using Android Studio 3.0, in which the embedded JDK version is 8. To find the version in any later version though, go to [SDK_INSTALL_ROOT]/jre/ and find THIRD_PARTY_README

THIRD_PARTY_README is in my system defined as a file and not a txt file. You can open it in Notepad, Notepad++ or any other text editor. The content is plain text. You can also look for a file called release, which contains similar information about versions.


问:
Location Manager's requestLocationUpdates called only once
I am calling the method and expect location updates multiple times:

```<code>locationManager.requestLocationUpdates("gps",0 ,0, loc_listener);
</code>```

My loc_listener is defined as:

```<code>LocationListener loc_listener = new LocationListener() {
    private final String TAG = "xoxoxo.LocationListener";

    public void onLocationChanged(Location l) {
        Intent locationAlert = new Intent("xoxoxo.LOCATION_CHANGED")
                .putExtra("target_location", l);
        sendBroadcast(locationAlert);
        // locationManager.requestLocationUpdates("gps", 0 ,0, this);
    }

    public void onProviderEnabled(String p) {
        Log.i(TAG, "Provider enabled");
    }

    public void onProviderDisabled(String p) {
        Log.i(TAG, "Provider disabled");
    }

    public void onStatusChanged(String p, int status, Bundle extras) {
        Log.i(TAG, "Status changed");
    }
};
</code>```

Defined as is, I will only get an update once, both on HTC Evo 2.2 and 2.2 + Google API emulator.
The hack to get multiple updates is to uncomment the line which registers for updates on each update:

```<code>locationManager.requestLocationUpdates("gps", 0 ,0, this);
</code>```

Have you guys seen anything like this?

答:
I have never seen the issue. The following is my code to test LocationManager and LocationListener. It works as expected when LocationListener is implemented as an anonymous class.</p>

```<code>package com.test.locationmanager;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.widget.TextView;

public class LocationManagerStatus extends Activity {

    private LocationManager locationManager;
    private TextView textView;
    private final LocationListener gpsLocationListener =new LocationListener(){

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            final String tvTxt = textView.getText().toString();
            switch (status) {
            case LocationProvider.AVAILABLE:
                textView.setText(tvTxt + "GPS available again\n");
                break;
            case LocationProvider.OUT_OF_SERVICE:
                textView.setText(tvTxt + "GPS out of service\n");
                break;
            case LocationProvider.TEMPORARILY_UNAVAILABLE:
                textView.setText(tvTxt + "GPS temporarily unavailable\n");
                break;
            }
        }

        @Override
        public void onProviderEnabled(String provider) {
            textView.setText(textView.getText().toString()
                    + "GPS Provider Enabled\n");
        }

        @Override
        public void onProviderDisabled(String provider) {
            textView.setText(textView.getText().toString()
                    + "GPS Provider Disabled\n");
        }

        @Override
        public void onLocationChanged(Location location) {
            locationManager.removeUpdates(networkLocationListener);
            textView.setText(textView.getText().toString()
                    + "New GPS location: "
                    + String.format("%9.6f", location.getLatitude()) + ", "
                    + String.format("%9.6f", location.getLongitude()) + "\n");
        }
    };
    private final LocationListener networkLocationListener =
                                                        new LocationListener(){

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras){
            final String tvTxt = textView.getText().toString();
            switch (status) {
            case LocationProvider.AVAILABLE:
                textView.setText(tvTxt + "Network location available again\n");
                break;
            case LocationProvider.OUT_OF_SERVICE:
                textView.setText(tvTxt + "Network location out of service\n");
                break;
            case LocationProvider.TEMPORARILY_UNAVAILABLE:
                textView.setText(tvTxt
                        + "Network location temporarily unavailable\n");
                break;
            }
        }

        @Override
        public void onProviderEnabled(String provider) {
            textView.setText(textView.getText().toString()
                    + "Network Provider Enabled\n");
        }

        @Override
        public void onProviderDisabled(String provider) {
            textView.setText(textView.getText().toString()
                    + "Network Provider Disabled\n");
        }

        @Override
        public void onLocationChanged(Location location) {
            textView.setText(textView.getText().toString()
                    + "New network location: "
                    + String.format("%9.6f", location.getLatitude()) + ", "
                    + String.format("%9.6f", location.getLongitude()) + "\n");
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textView = (TextView) findViewById(R.id.textview);
        locationManager = (LocationManager)
                getSystemService(Context.LOCATION_SERVICE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        locationManager.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER, 5000, 0,
                networkLocationListener);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                3000, 0, gpsLocationListener);
    }

    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(networkLocationListener);
        locationManager.removeUpdates(gpsLocationListener);
    }
}
</code>```

Body:
I am calling the method and expect location updates multiple times:

locationManager.requestLocationUpdates("gps",0 ,0, loc_listener);

My loc_listener is defined as:

LocationListener loc_listener = new LocationListener() {
    private final String TAG = "xoxoxo.LocationListener";

    public void onLocationChanged(Location l) {
        Intent locationAlert = new Intent("xoxoxo.LOCATION_CHANGED")
                .putExtra("target_location", l);
        sendBroadcast(locationAlert);
        // locationManager.requestLocationUpdates("gps", 0 ,0, this);
    }

    public void onProviderEnabled(String p) {
        Log.i(TAG, "Provider enabled");
    }

    public void onProviderDisabled(String p) {
        Log.i(TAG, "Provider disabled");
    }

    public void onStatusChanged(String p, int status, Bundle extras) {
        Log.i(TAG, "Status changed");
    }
};

Defined as is, I will only get an update once, both on HTC Evo 2.2 and 2.2 + Google API emulator.
The hack to get multiple updates is to uncomment the line which registers for updates on each update:

locationManager.requestLocationUpdates("gps", 0 ,0, this);

Have you guys seen anything like this?

Body:
I have never seen the issue. The following is my code to test LocationManager and LocationListener. It works as expected when LocationListener is implemented as an anonymous class.

package com.test.locationmanager;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.widget.TextView;

public class LocationManagerStatus extends Activity {

    private LocationManager locationManager;
    private TextView textView;
    private final LocationListener gpsLocationListener =new LocationListener(){

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            final String tvTxt = textView.getText().toString();
            switch (status) {
            case LocationProvider.AVAILABLE:
                textView.setText(tvTxt + "GPS available again\n");
                break;
            case LocationProvider.OUT_OF_SERVICE:
                textView.setText(tvTxt + "GPS out of service\n");
                break;
            case LocationProvider.TEMPORARILY_UNAVAILABLE:
                textView.setText(tvTxt + "GPS temporarily unavailable\n");
                break;
            }
        }

        @Override
        public void onProviderEnabled(String provider) {
            textView.setText(textView.getText().toString()
                    + "GPS Provider Enabled\n");
        }

        @Override
        public void onProviderDisabled(String provider) {
            textView.setText(textView.getText().toString()
                    + "GPS Provider Disabled\n");
        }

        @Override
        public void onLocationChanged(Location location) {
            locationManager.removeUpdates(networkLocationListener);
            textView.setText(textView.getText().toString()
                    + "New GPS location: "
                    + String.format("%9.6f", location.getLatitude()) + ", "
                    + String.format("%9.6f", location.getLongitude()) + "\n");
        }
    };
    private final LocationListener networkLocationListener =
                                                        new LocationListener(){

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras){
            final String tvTxt = textView.getText().toString();
            switch (status) {
            case LocationProvider.AVAILABLE:
                textView.setText(tvTxt + "Network location available again\n");
                break;
            case LocationProvider.OUT_OF_SERVICE:
                textView.setText(tvTxt + "Network location out of service\n");
                break;
            case LocationProvider.TEMPORARILY_UNAVAILABLE:
                textView.setText(tvTxt
                        + "Network location temporarily unavailable\n");
                break;
            }
        }

        @Override
        public void onProviderEnabled(String provider) {
            textView.setText(textView.getText().toString()
                    + "Network Provider Enabled\n");
        }

        @Override
        public void onProviderDisabled(String provider) {
            textView.setText(textView.getText().toString()
                    + "Network Provider Disabled\n");
        }

        @Override
        public void onLocationChanged(Location location) {
            textView.setText(textView.getText().toString()
                    + "New network location: "
                    + String.format("%9.6f", location.getLatitude()) + ", "
                    + String.format("%9.6f", location.getLongitude()) + "\n");
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textView = (TextView) findViewById(R.id.textview);
        locationManager = (LocationManager)
                getSystemService(Context.LOCATION_SERVICE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        locationManager.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER, 5000, 0,
                networkLocationListener);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                3000, 0, gpsLocationListener);
    }

    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(networkLocationListener);
        locationManager.removeUpdates(gpsLocationListener);
    }
}


问:
Combine and Append data from multiple Excel workbooks into one worksheet
Below I found a VBA Script online that takes all worksheets from workbooks in a directory, and combines them all in one workbook as separate sheets. However, I don't want them to be separate sheets. I want all data in the sheets to be in a single worksheet.

```<code>Sub GetSheets()
    Path = "Desktop\RandoDir"
    Filename = Dir(Path & "\*.csv*")
    Do While Filename <> ""
        Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
        For Each Sheet In ActiveWorkbook.Sheets
            'MsgBox Filename      ---Debugging
            Sheet.Copy After:=ThisWorkbook.Sheets(1)
        Next Sheet
        Workbooks(Filename).Close
        Filename = Dir()
   Loop
End Sub
</code>```

If I had data structured like this in two files:

```<code>   **File1**                **File2**
Header1|Header2    |     Header1|Header2
Tim    |Smith      |     Mike   |Jones
</code>```

I want the merged worksheet to display

```<code>   **File3**
Header1|Header2
Tim    |Smith
Mike   |Jones
</code>```

答:
This will do what you want.

```<code>Sub Basic_Example_1()
    Dim MyPath As String, FilesInPath As String
    Dim MyFiles() As String
    Dim SourceRcount As Long, Fnum As Long
    Dim mybook As Workbook, BaseWks As Worksheet
    Dim sourceRange As Range, destrange As Range
    Dim rnum As Long, CalcMode As Long

    'Fill in the path\folder where the files are
    MyPath = "C:\Users\Ron\test"

    'Add a slash at the end if the user forget it
    If Right(MyPath, 1) <> "\" Then
        MyPath = MyPath & "\"
    End If

    'If there are no Excel files in the folder exit the sub
    FilesInPath = Dir(MyPath & "*.xl*")
    If FilesInPath = "" Then
        MsgBox "No files found"
        Exit Sub
    End If

    'Fill the array(myFiles)with the list of Excel files in the folder
    Fnum = 0
    Do While FilesInPath <> ""
        Fnum = Fnum + 1
        ReDim Preserve MyFiles(1 To Fnum)
        MyFiles(Fnum) = FilesInPath
        FilesInPath = Dir()
    Loop

    'Change ScreenUpdating, Calculation and EnableEvents
    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    'Add a new workbook with one sheet
    Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
    rnum = 1

    'Loop through all files in the array(myFiles)
    If Fnum > 0 Then
        For Fnum = LBound(MyFiles) To UBound(MyFiles)
            Set mybook = Nothing
            On Error Resume Next
            Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum))
            On Error GoTo 0

            If Not mybook Is Nothing Then

                On Error Resume Next

                With mybook.Worksheets(1)
                    Set sourceRange = .Range("A1:C1")
                End With

                If Err.Number > 0 Then
                    Err.Clear
                    Set sourceRange = Nothing
                Else
                    'if SourceRange use all columns then skip this file
                    If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
                        Set sourceRange = Nothing
                    End If
                End If
                On Error GoTo 0

                If Not sourceRange Is Nothing Then

                    SourceRcount = sourceRange.Rows.Count

                    If rnum + SourceRcount >= BaseWks.Rows.Count Then
                        MsgBox "Sorry there are not enough rows in the sheet"
                        BaseWks.Columns.AutoFit
                        mybook.Close savechanges:=False
                        GoTo ExitTheSub
                    Else

                        'Copy the file name in column A
                        With sourceRange
                            BaseWks.cells(rnum, "A"). _
                                    Resize(.Rows.Count).Value = MyFiles(Fnum)
                        End With

                        'Set the destrange
                        Set destrange = BaseWks.Range("B" & rnum)

                        'we copy the values from the sourceRange to the destrange
                        With sourceRange
                            Set destrange = destrange. _
                                            Resize(.Rows.Count, .Columns.Count)
                        End With
                        destrange.Value = sourceRange.Value

                        rnum = rnum + SourceRcount
                    End If
                End If
                mybook.Close savechanges:=False
            End If

        Next Fnum
        BaseWks.Columns.AutoFit
    End If

ExitTheSub:
    'Restore ScreenUpdating, Calculation and EnableEvents
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With
End Sub
</code>```

You can find more info here.

https://www.rondebruin.nl/win/s3/win008.htm

Body:
Below I found a VBA Script online that takes all worksheets from workbooks in a directory, and combines them all in one workbook as separate sheets. However, I don't want them to be separate sheets. I want all data in the sheets to be in a single worksheet.

Sub GetSheets()
    Path = "Desktop\RandoDir"
    Filename = Dir(Path & "\*.csv*")
    Do While Filename <> ""
        Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
        For Each Sheet In ActiveWorkbook.Sheets
            'MsgBox Filename      ---Debugging
            Sheet.Copy After:=ThisWorkbook.Sheets(1)
        Next Sheet
        Workbooks(Filename).Close
        Filename = Dir()
   Loop
End Sub

If I had data structured like this in two files:

   **File1**                **File2**
Header1|Header2    |     Header1|Header2
Tim    |Smith      |     Mike   |Jones

I want the merged worksheet to display

   **File3**
Header1|Header2
Tim    |Smith
Mike   |Jones

Body:
This will do what you want.

Sub Basic_Example_1()
    Dim MyPath As String, FilesInPath As String
    Dim MyFiles() As String
    Dim SourceRcount As Long, Fnum As Long
    Dim mybook As Workbook, BaseWks As Worksheet
    Dim sourceRange As Range, destrange As Range
    Dim rnum As Long, CalcMode As Long

    'Fill in the path\folder where the files are
    MyPath = "C:\Users\Ron\test"

    'Add a slash at the end if the user forget it
    If Right(MyPath, 1) <> "\" Then
        MyPath = MyPath & "\"
    End If

    'If there are no Excel files in the folder exit the sub
    FilesInPath = Dir(MyPath & "*.xl*")
    If FilesInPath = "" Then
        MsgBox "No files found"
        Exit Sub
    End If

    'Fill the array(myFiles)with the list of Excel files in the folder
    Fnum = 0
    Do While FilesInPath <> ""
        Fnum = Fnum + 1
        ReDim Preserve MyFiles(1 To Fnum)
        MyFiles(Fnum) = FilesInPath
        FilesInPath = Dir()
    Loop

    'Change ScreenUpdating, Calculation and EnableEvents
    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    'Add a new workbook with one sheet
    Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
    rnum = 1

    'Loop through all files in the array(myFiles)
    If Fnum > 0 Then
        For Fnum = LBound(MyFiles) To UBound(MyFiles)
            Set mybook = Nothing
            On Error Resume Next
            Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum))
            On Error GoTo 0

            If Not mybook Is Nothing Then

                On Error Resume Next

                With mybook.Worksheets(1)
                    Set sourceRange = .Range("A1:C1")
                End With

                If Err.Number > 0 Then
                    Err.Clear
                    Set sourceRange = Nothing
                Else
                    'if SourceRange use all columns then skip this file
                    If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
                        Set sourceRange = Nothing
                    End If
                End If
                On Error GoTo 0

                If Not sourceRange Is Nothing Then

                    SourceRcount = sourceRange.Rows.Count

                    If rnum + SourceRcount >= BaseWks.Rows.Count Then
                        MsgBox "Sorry there are not enough rows in the sheet"
                        BaseWks.Columns.AutoFit
                        mybook.Close savechanges:=False
                        GoTo ExitTheSub
                    Else

                        'Copy the file name in column A
                        With sourceRange
                            BaseWks.cells(rnum, "A"). _
                                    Resize(.Rows.Count).Value = MyFiles(Fnum)
                        End With

                        'Set the destrange
                        Set destrange = BaseWks.Range("B" & rnum)

                        'we copy the values from the sourceRange to the destrange
                        With sourceRange
                            Set destrange = destrange. _
                                            Resize(.Rows.Count, .Columns.Count)
                        End With
                        destrange.Value = sourceRange.Value

                        rnum = rnum + SourceRcount
                    End If
                End If
                mybook.Close savechanges:=False
            End If

        Next Fnum
        BaseWks.Columns.AutoFit
    End If

ExitTheSub:
    'Restore ScreenUpdating, Calculation and EnableEvents
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With
End Sub

You can find more info here.

https://www.rondebruin.nl/win/s3/win008.htm


问:
Superclass printing unexpected value when Subclass is created
Could you please help in understanding the output of below java code where this(0) of Superclass is called when object is created for Subclass.

In this code though there is no mention in the code to explicitly print 20, why the first value is printed as 20?

```<code>class Superclass {
    Superclass() {
        this(0);
        System.out.println("1");
    }

    Superclass(int x) {
        System.out.println("2" + x);
    }
}

class Subclass extends Superclass {
    Subclass(int x) {
        System.out.println("3" + x);
    }

    Subclass(int x, int y) {
        System.out.println("4" + x + y);
    }
}

public class practiceTest {
    public static void main(String[] args) {
        Subclass s = new Subclass(10, 20);
    }
}
</code>```

答:
String addition

In this code though there is no mention in the code to explicitly print "20"

Actually there is, take a look at your Superclass

```<code>Superclass() {
    this(0);
    System.out.println("1");
}

Superclass(int x) {
    System.out.println("2" + x);
}
</code>```

Addition of Strings is interpreted as concatenation, not as ordinary addition (of values). So calling the default constructor of Superclass triggers this(0) which yields

```<code>    System.out.println("2" + x);
=>  System.out.println("2" + 0);
=>  System.out.println("20");
</code>```

thus printing 20.

Integer addition

If you want to add the values as integer you need to use int values and not String values, for example like

```<code>Superclass(int x) {
    System.out.println(2 + x);
}
</code>```

then you will also get

```<code>    System.out.println(2 + x);
=>  System.out.println(2 + 0);
=>  System.out.println(2);
</code>```

Constructor-chain

Okay, so what happens exactly if you call

```<code>Subclass s = new Subclass(10, 20);
</code>```

Well, first, of course, you trigger this constructor

```<code>Subclass(int x, int y) {
    System.out.println("4" + x + y);
}
</code>```

Now in Java, when creating sub-classes you will always need to call one of the constructors of the super-class (it's per definition of the language).

And if you don't explicitly specify such a call then it tries to call the default constructor of your super-class. If there is no, it won't compile. However you have such a default constructor, the code will thus be equivalent to

```<code>Subclass(int x, int y) {
    // Implicit call of default super-constructor
    super();
    System.out.println("4" + x + y);
}
</code>```

So you call the following constructor

```<code>Superclass() {
    this(0);
    System.out.println("1");
}
</code>```

which, as shown above, triggers the other constructor

```<code>Superclass(int x) {
    System.out.println("2" + x);
}
</code>```

So what you will get, if resolving this chain, are the following outputs

```<code>// from Superclass(int x)
System.out.println("2" + 0);
// from Superclass()
System.out.println("1");
// from Subclass(int x, int y)
System.out.println("4" + 10 + 20);
</code>```

which yields

```<code>20
1
41020
</code>```

Body:
Could you please help in understanding the output of below java code where this(0) of Superclass is called when object is created for Subclass.

In this code though there is no mention in the code to explicitly print 20, why the first value is printed as 20?

class Superclass {
    Superclass() {
        this(0);
        System.out.println("1");
    }

    Superclass(int x) {
        System.out.println("2" + x);
    }
}

class Subclass extends Superclass {
    Subclass(int x) {
        System.out.println("3" + x);
    }

    Subclass(int x, int y) {
        System.out.println("4" + x + y);
    }
}

public class practiceTest {
    public static void main(String[] args) {
        Subclass s = new Subclass(10, 20);
    }
}

Body:
String addition

In this code though there is no mention in the code to explicitly print "20"

Actually there is, take a look at your Superclass

Superclass() {
    this(0);
    System.out.println("1");
}

Superclass(int x) {
    System.out.println("2" + x);
}

Addition of Strings is interpreted as concatenation, not as ordinary addition (of values). So calling the default constructor of Superclass triggers this(0) which yields

    System.out.println("2" + x);
=>  System.out.println("2" + 0);
=>  System.out.println("20");

thus printing 20.

Integer addition

If you want to add the values as integer you need to use int values and not String values, for example like

Superclass(int x) {
    System.out.println(2 + x);
}

then you will also get

    System.out.println(2 + x);
=>  System.out.println(2 + 0);
=>  System.out.println(2);

Constructor-chain

Okay, so what happens exactly if you call

Subclass s = new Subclass(10, 20);

Well, first, of course, you trigger this constructor

Subclass(int x, int y) {
    System.out.println("4" + x + y);
}

Now in Java, when creating sub-classes you will always need to call one of the constructors of the super-class (it's per definition of the language).

And if you don't explicitly specify such a call then it tries to call the default constructor of your super-class. If there is no, it won't compile. However you have such a default constructor, the code will thus be equivalent to

Subclass(int x, int y) {
    // Implicit call of default super-constructor
    super();
    System.out.println("4" + x + y);
}

So you call the following constructor

Superclass() {
    this(0);
    System.out.println("1");
}

which, as shown above, triggers the other constructor

Superclass(int x) {
    System.out.println("2" + x);
}

So what you will get, if resolving this chain, are the following outputs

// from Superclass(int x)
System.out.println("2" + 0);
// from Superclass()
System.out.println("1");
// from Subclass(int x, int y)
System.out.println("4" + 10 + 20);

which yields

20
1
41020


问:
Why does wrapping a ReactiveSwift MutableProperty in a Property cause a leak?
Here's a Swift class that uses ReactiveSwift, wrapping a MutableProperty in a Property, and adding a subscription to that Property in a ScopedDisposable:

```<code>class Leaker {
    let mutableProperty = MutableProperty<Int>(0)

    var wrapperProperty: Property<Int> {
        return Property(self.mutableProperty)
    }

    private var disposable: ScopedDisposable<AnyDisposable>?

    init() {
        let disposable = CompositeDisposable()

        disposable += self.wrapperProperty.producer
            .startWithValues { value in
                print("\(value)")
            }

        self.disposable = ScopedDisposable(disposable)
    }
}
</code>```

If I give another class a property of type Leaker?, and then set it using self.leaker = Leaker(), this creates a leak. By "creates a leak," I mean it sets off the Leaks instrument, showing a leaked object labeled Malloc 32 Bytes, with a stack trace that includes Leaker.init() calling Leaker.wrapperProperty.getter.

Why does this leak? I'm finding it hard to understand exactly what is causing the memory allocated here to never be released.

Some other facts that might be useful:

This doesn't leak if I subscribe to mutableProperty directly

This doesn't leak if I wrap mutableProperty in a lazy property instead of a computed property

This doesn't leak if I create a temporary Leaker, e.g. let _ = Leaker()

答:
I tried, but was not able to reproduce the memory leak. I've used your exact Leaker class with this code:

```<code>final class OtherClass {
  let leaker: Leaker?

  init() {
    self.leaker = Leaker()
  }
}

var otherClass: OtherClass? = OtherClass()

var mutablePropertyCompleted = false
otherClass!.leaker!.mutableProperty.producer.startWithCompleted {
  mutablePropertyCompleted = true
}

var wrappedPropertyCompleted = false
otherClass!.leaker!.wrapperProperty.producer.startWithCompleted {
  wrappedPropertyCompleted = true
}

otherClass = nil

if(!mutablePropertyCompleted) {
  print("LEAK")
}

if(!wrappedPropertyCompleted) {
  print("LEAK")
}
</code>```

One thing to note is that MutableProperty sends completed in its deinit method, so it should be possible to detect a leak the way I did here.

But just to be sure I also profiled this with the memory leaks instrument which detected nothing.

Since you mentioned some specific circumstances in which this does not leak for you it might just be that the way I'm trying to reproduce the issue is wrong, maybe you can post a complete example?

Anyway, I don't see an error in the example you posted, so either this is a bug in ReactiveSwift, or its a false positive by the profiler (which has happened with ReactiveSwift before as jjoelson pointed out in his comment)

Body:
Here's a Swift class that uses ReactiveSwift, wrapping a MutableProperty in a Property, and adding a subscription to that Property in a ScopedDisposable:

class Leaker {
    let mutableProperty = MutableProperty<Int>(0)

    var wrapperProperty: Property<Int> {
        return Property(self.mutableProperty)
    }

    private var disposable: ScopedDisposable<AnyDisposable>?

    init() {
        let disposable = CompositeDisposable()

        disposable += self.wrapperProperty.producer
            .startWithValues { value in
                print("\(value)")
            }

        self.disposable = ScopedDisposable(disposable)
    }
}

If I give another class a property of type Leaker?, and then set it using self.leaker = Leaker(), this creates a leak. By "creates a leak," I mean it sets off the Leaks instrument, showing a leaked object labeled Malloc 32 Bytes, with a stack trace that includes Leaker.init() calling Leaker.wrapperProperty.getter.

Why does this leak? I'm finding it hard to understand exactly what is causing the memory allocated here to never be released.

Some other facts that might be useful:

This doesn't leak if I subscribe to mutableProperty directly

This doesn't leak if I wrap mutableProperty in a lazy property instead of a computed property

This doesn't leak if I create a temporary Leaker, e.g. let _ = Leaker()

Body:
I tried, but was not able to reproduce the memory leak. I've used your exact Leaker class with this code:

final class OtherClass {
  let leaker: Leaker?

  init() {
    self.leaker = Leaker()
  }
}

var otherClass: OtherClass? = OtherClass()

var mutablePropertyCompleted = false
otherClass!.leaker!.mutableProperty.producer.startWithCompleted {
  mutablePropertyCompleted = true
}

var wrappedPropertyCompleted = false
otherClass!.leaker!.wrapperProperty.producer.startWithCompleted {
  wrappedPropertyCompleted = true
}

otherClass = nil

if(!mutablePropertyCompleted) {
  print("LEAK")
}

if(!wrappedPropertyCompleted) {
  print("LEAK")
}

One thing to note is that MutableProperty sends completed in its deinit method, so it should be possible to detect a leak the way I did here.

But just to be sure I also profiled this with the memory leaks instrument which detected nothing.

Since you mentioned some specific circumstances in which this does not leak for you it might just be that the way I'm trying to reproduce the issue is wrong, maybe you can post a complete example?

Anyway, I don't see an error in the example you posted, so either this is a bug in ReactiveSwift, or its a false positive by the profiler (which has happened with ReactiveSwift before as jjoelson pointed out in his comment)


问:
How to insert rows and columns of zeros into Matlab Matrix
I have a 3x3 matrix, k1, that I would like to convert into a 5x5 matrix, k1g.  k1g is created by inserting zeros into certain rows and columns of k1.  In this case I would like to insert zeros into rows 3 and 4 and columns 3 and 4, and keep existing values from k1 matrix.  The code below accomplishes what I am trying to do but seems that it is a long method and I need to do this many times in numerous problems.

```<code>clc
clear all
format long;
k1 = [20,50,-20;
     60,20,-20;
   -20,-20,40]
k1g = zeros(5,5);
k1g(1:2,1:2) = k1(1:2,1:2);
k1g(5:5,1:2) = k1(3:3,1:2);
k1g(1:2,5:5) = k1(1:2,3:3);
k1g(5,5) = k1(3,3)
</code>```

Here is output of above code:

```<code>k1 =

    20    50   -20
    60    20   -20
   -20   -20    40

k1g =

    20    50     0     0   -20
    60    20     0     0   -20
     0     0     0     0     0
     0     0     0     0     0
   -20   -20     0     0    40
</code>```

Is there a better way to accomplish this?

答:
You just need to generalise your approach. e.g. with:

```<code>function k1g = rowcolsof0s(k1,rowsof0s,colsof0s)
k1g = ones(size(k1)+[numel(rowsof0s) numel(colsof0s)]);  %Initialising matrix with ones
k1g(rowsof0s,:) = 0;    %Changing the elements of desired rows to zeros
k1g(:,colsof0s) = 0;    %Changing the elements of desired columns to zeros
k1g(logical(k1g)) = k1; %Transferring the contents of k1 into k1g
end
</code>```

Now call that function with:

```<code>rowsof0s = [3 4];       %rows where you want to insert zeros
colsof0s = [3 4];       %columns where you want to insert zeros

k1g = rowcolsof0s(k1, rowsof0s, colsof0s);
</code>```

Body:
I have a 3x3 matrix, k1, that I would like to convert into a 5x5 matrix, k1g.  k1g is created by inserting zeros into certain rows and columns of k1.  In this case I would like to insert zeros into rows 3 and 4 and columns 3 and 4, and keep existing values from k1 matrix.  The code below accomplishes what I am trying to do but seems that it is a long method and I need to do this many times in numerous problems.

clc
clear all
format long;
k1 = [20,50,-20;
     60,20,-20;
   -20,-20,40]
k1g = zeros(5,5);
k1g(1:2,1:2) = k1(1:2,1:2);
k1g(5:5,1:2) = k1(3:3,1:2);
k1g(1:2,5:5) = k1(1:2,3:3);
k1g(5,5) = k1(3,3)

Here is output of above code:

k1 =

    20    50   -20
    60    20   -20
   -20   -20    40

k1g =

    20    50     0     0   -20
    60    20     0     0   -20
     0     0     0     0     0
     0     0     0     0     0
   -20   -20     0     0    40

Is there a better way to accomplish this?

Body:
You just need to generalise your approach. e.g. with:

function k1g = rowcolsof0s(k1,rowsof0s,colsof0s)
k1g = ones(size(k1)+[numel(rowsof0s) numel(colsof0s)]);  %Initialising matrix with ones
k1g(rowsof0s,:) = 0;    %Changing the elements of desired rows to zeros
k1g(:,colsof0s) = 0;    %Changing the elements of desired columns to zeros
k1g(logical(k1g)) = k1; %Transferring the contents of k1 into k1g
end

Now call that function with:

rowsof0s = [3 4];       %rows where you want to insert zeros
colsof0s = [3 4];       %columns where you want to insert zeros

k1g = rowcolsof0s(k1, rowsof0s, colsof0s);


问:
Processing of kivy canvas texture in memory
I want to pass pixels from the kivy canvas to keras model (neural network). Simple approach would be to export the image to png and then read it using scikit-image or PIL. Question is can this be done in memory without such redundant steps?

This is what I came up with:

```<code>fbo = Fbo()
fbo.add(self.canvas)
fbo.draw()
img = Image.frombytes('RGBA', img_size, fbo.pixels)
</code>```

In order to check if everything works, img was saved as png. Unfortunately it turned out to be complete mess. My question is how can I get it to work properly?

Here is code that reproduces/demonstrates this problem:

```<code>from PIL import Image
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.graphics import Line, Fbo
from kivy.uix.floatlayout import FloatLayout

class Painter(Widget):

    def on_touch_down(self, touch):
        with self.canvas:
            touch.ud['line'] = Line(points=(touch.x, touch.y), width=50)

    def on_touch_move(self, touch):
        touch.ud['line'].points += [touch.x, touch.y]

    def save(self, obj):

        fbo = Fbo()
        fbo.add(self.canvas)
        fbo.draw()
        img = Image.frombytes('RGBA', self.size, fbo.pixels)
        img.save('img.png')

class App(App):

    def build(self):
        layout = FloatLayout()
        painter = Painter()
        btn = Button(text='Save', on_release=painter.save, size_hint=(0.2,0.2))

        layout.add_widget(painter)
        layout.add_widget(btn)
        return layout

App().run()
</code>```

答:
You can read the source to see how Widget.export_to_png works, then use a similar method yourself. Once you have the texture, probably you can get the pixel information you want from the pixels attribute.

You can also replace the widget's canvas with an Fbo, to avoid the need to make a new one each time.

Body:
I want to pass pixels from the kivy canvas to keras model (neural network). Simple approach would be to export the image to png and then read it using scikit-image or PIL. Question is can this be done in memory without such redundant steps?

This is what I came up with:

fbo = Fbo()
fbo.add(self.canvas)
fbo.draw()
img = Image.frombytes('RGBA', img_size, fbo.pixels)

In order to check if everything works, img was saved as png. Unfortunately it turned out to be complete mess. My question is how can I get it to work properly?

Here is code that reproduces/demonstrates this problem:

from PIL import Image
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.graphics import Line, Fbo
from kivy.uix.floatlayout import FloatLayout

class Painter(Widget):

    def on_touch_down(self, touch):
        with self.canvas:
            touch.ud['line'] = Line(points=(touch.x, touch.y), width=50)

    def on_touch_move(self, touch):
        touch.ud['line'].points += [touch.x, touch.y]

    def save(self, obj):

        fbo = Fbo()
        fbo.add(self.canvas)
        fbo.draw()
        img = Image.frombytes('RGBA', self.size, fbo.pixels)
        img.save('img.png')

class App(App):

    def build(self):
        layout = FloatLayout()
        painter = Painter()
        btn = Button(text='Save', on_release=painter.save, size_hint=(0.2,0.2))

        layout.add_widget(painter)
        layout.add_widget(btn)
        return layout

App().run()


问:
How to cancel the keyboard in UISearchbar?
I'm using UISearchBar in my application and it serves as both an edit field as well as a search.  So when I want to disappear the keyboard I have to use cancel button in UISearchBar but I can't have that cancel button on screen, so how could T make keyboard disappear when not used without using cancel button.  Please help me as i'm new to iPhone application development.

Thanks in advance!

答: Are you looking for ways you can dismiss the keyboard or how to actually do that programmatically? If programmatically, then [UISearchBar resignFirstResponder]. If you are looking for a possible way for the user to achieve that you can either make the return button on the keyboard resign its first responder status when pressed, or attach a UIGestureRecognizer to your view and set it up so that when the user clicks outside the keyboard, this keyboard goes away.

ContentLicense: CC BY-SA 2.5


问:
DDD, Status object / Value Objects
I've a class, Proposal, which has a $status of type ProposalStatus.  Now, for the most part the ProposalStatus's identity does not change...  but it does (sort of).  It's $id is fixed, but the $display_name and $definition (just strings) can change over a long period of time as the master data is updated, but it will NOT change within the lifetime of an HTTP Request-Response.

Question #1 - Entity or Value Object?

Is a value object something is never supposed to change or only never supposed to change over the lifetime of a specific execution of the application?  If the display name or definition are changed then really I expect / want it to be changed for everyone.  However, since they can be defined outside of the proposal I'm think that just straight up makes them entities instead of value objects.

At no time does the Proposal change the ProposalStatus's attributes, it only changes which ProposalStatus is has.

Question #2 - How to set the status correctly for a domain-driven design?

My proposal object has the ability to manage it's statuses, but in order to do that I need to have a specific ProposalStatus object.  Only, where is the list of statuses that allows it to returns the right expected to be?

I could get it from a the ProposalRepository...  but everything is accessed via the aggregate root which the Proposal so that doesn't make sense.

I could have constants that match the $id of the ProposalStatus, but that seems wrong.

I could make a ProposalStatusRepository...  but should I be accessing another repository from within the Proposal?

I could make a array of all possible statuses with the $id as the key and add to the proposal, but that isn't much different from a repository...

Example:

```<code>class ProposalStatus {
    protected $id; // E.g., pending_customer_approval
    protected $display_name; // E.g., Pending Customer Approval
    protected $definition; // E.g., The proposal needs to be approved by the customer
}

class Proposal {
    /**
     * The current status of the proposal
     * @var ProposalStatus
     */
    protected $proposal_status;

    public function withdraw() {
        // verify status is not closed or canceled
        // change status to draft
    }

    public function submit() {
        // verify status is draft
        // change status to pending customer approval
    }

    public function approve() {
        // verify status is pending customer approval
        // change status to approved
    }

    public function reject() {
        // verify status is pending customer approval
        // change status to rejected
    }

    public function close() {
        // verify status is not canceled
        // change status to closed
    }

    public function cancel() {
        // verify status is not closed
        // change status to canceled
    }
}
</code>```

答:
In case that your ProposalStatus is a fixed list of values just go for the enumeration approach.

Otherwise you need to treat ProposalStatus as an AggregateRoot that users can create, update and delete (I guess). When assigning a ProposalStatus to a Proposal you just need the ID. If you want to check that the given ID exists you just need to satisfy the invariant with a specialized query. Specification pattern fits well here.

```<code>class ProposalStatusExistsSpecification
{
    public function isSatisfiedBy(string $proposalSatusId): bool
    {
        //database query to see if the given ID exists
    }
}
</code>```

You can find here the Interfaces to implement your specification.

Title: DDD, Status object / Value Objects

Body:
I've a class, Proposal, which has a $status of type ProposalStatus.  Now, for the most part the ProposalStatus's identity does not change...  but it does (sort of).  It's $id is fixed, but the $display_name and $definition (just strings) can change over a long period of time as the master data is updated, but it will NOT change within the lifetime of an HTTP Request-Response.

Question #1 - Entity or Value Object?

Is a value object something is never supposed to change or only never supposed to change over the lifetime of a specific execution of the application?  If the display name or definition are changed then really I expect / want it to be changed for everyone.  However, since they can be defined outside of the proposal I'm think that just straight up makes them entities instead of value objects.

At no time does the Proposal change the ProposalStatus's attributes, it only changes which ProposalStatus is has.

Question #2 - How to set the status correctly for a domain-driven design?

My proposal object has the ability to manage it's statuses, but in order to do that I need to have a specific ProposalStatus object.  Only, where is the list of statuses that allows it to returns the right expected to be?

I could get it from a the ProposalRepository...  but everything is accessed via the aggregate root which the Proposal so that doesn't make sense.

I could have constants that match the $id of the ProposalStatus, but that seems wrong.

I could make a ProposalStatusRepository...  but should I be accessing another repository from within the Proposal?

I could make a array of all possible statuses with the $id as the key and add to the proposal, but that isn't much different from a repository...

Example:

class ProposalStatus {
    protected $id; // E.g., pending_customer_approval
    protected $display_name; // E.g., Pending Customer Approval
    protected $definition; // E.g., The proposal needs to be approved by the customer
}

class Proposal {
    /**
     * The current status of the proposal
     * @var ProposalStatus
     */
    protected $proposal_status;

    public function withdraw() {
        // verify status is not closed or canceled
        // change status to draft
    }

    public function submit() {
        // verify status is draft
        // change status to pending customer approval
    }

    public function approve() {
        // verify status is pending customer approval
        // change status to approved
    }

    public function reject() {
        // verify status is pending customer approval
        // change status to rejected
    }

    public function close() {
        // verify status is not canceled
        // change status to closed
    }

    public function cancel() {
        // verify status is not closed
        // change status to canceled
    }
}

Body:
In case that your ProposalStatus is a fixed list of values just go for the enumeration approach.

Otherwise you need to treat ProposalStatus as an AggregateRoot that users can create, update and delete (I guess). When assigning a ProposalStatus to a Proposal you just need the ID. If you want to check that the given ID exists you just need to satisfy the invariant with a specialized query. Specification pattern fits well here.

class ProposalStatusExistsSpecification
{
    public function isSatisfiedBy(string $proposalSatusId): bool
    {
        //database query to see if the given ID exists
    }
}

You can find here the Interfaces to implement your specification.


问:
MySQL Workbench out of range value for decimal number
I wanted to create an table

```<code>create table Oceny_projekty
(
   OProj_Id             int not null  comment '',
   ID_Projektu          int  comment '',
   ID_Studenta          int  comment '',
   OProj_Ocena          decimal(1,1)  comment '',
   OProj_Data           date  comment '',
   primary key (OProj_Id)
);
</code>```

And fill it with sample data generated by PowerDesigner

```<code>insert into Oceny_projekty (OProj_Id, ID_Projektu, ID_Studenta, OProj_Ocena, OProj_Data)
    values (2, 18, 10, '2.5', '1857-12-25');
</code>```

And I've got this:

insert into Oceny_projekty (OProj_Id, ID_Projektu, ID_Studenta,
  OProj_Ocena, OProj_Data) values (2, 18, 10, '2.5', '1857-12-25')  Error
  Code: 1264. Out of range value for column 'OProj_Ocena' at row 1

How can I modify command that can accept decimal numbers? (with integer numbers there is no problem)
Using MySQL Workbench 6.3, PowerDesigner 16.6

Thanks in advance!

答:
Declaring OProj_Ocena as decimal(1,1) means that it has 0 integer digits (precision - scale = 1 - 1 = 0) and 1 fractional digit. It can only store values 0, 0.1, 0.2 ... 0.9.

The datatype you need is probably decimal(2,1).

Body:
I wanted to create an table

create table Oceny_projekty
(
   OProj_Id             int not null  comment '',
   ID_Projektu          int  comment '',
   ID_Studenta          int  comment '',
   OProj_Ocena          decimal(1,1)  comment '',
   OProj_Data           date  comment '',
   primary key (OProj_Id)
);

And fill it with sample data generated by PowerDesigner

insert into Oceny_projekty (OProj_Id, ID_Projektu, ID_Studenta, OProj_Ocena, OProj_Data)
    values (2, 18, 10, '2.5', '1857-12-25');

And I've got this:

insert into Oceny_projekty (OProj_Id, ID_Projektu, ID_Studenta,
  OProj_Ocena, OProj_Data) values (2, 18, 10, '2.5', '1857-12-25')  Error
  Code: 1264. Out of range value for column 'OProj_Ocena' at row 1

How can I modify command that can accept decimal numbers? (with integer numbers there is no problem)
Using MySQL Workbench 6.3, PowerDesigner 16.6

Thanks in advance!


问:
Sum of each row and column in 2D array (C)
I want to get the sum of each row and column of an array and print them one by one in C. I done half of work but I can't progress any more. There it is my code:

```<code>int n,m;
void sum_row_column(int array[n][m],int r,int c,int i,int j)
{
int sum_of_column1=0;
int sum_of_row1;

for(j=0,i=0;i<r;i++)
{
    sum_of_column1=sum_of_column1+array[i][j];
    if(i==r-1)
    {
        printf("\nSum of %d.column: %d\n",j+1,sum_of_column1);
        j=j+1;
    }
}

for(i=0,j=0;j<r;j++)
{
    sum_of_row1=sum_of_row1+array[i][j];
    if(j=c-1)
    {
        printf("\nSum of %d.row: %d\n",j+1,sum_of_row1);
        i=i+1;
    }
}
</code>```

As you can see it prints just first row's sum and column's sum. I thought if I add

```<code>i=0;
</code>```

after

```<code>printf("\nSum of %d.column: %d\n",j+1,sum_of_column1);
j=j+1
</code>```

line, it can move second column and sum it too. But when I add

```<code>i=0;
</code>```

the program go into infinite loop without any errors.
This code is in the header but don't worry in the rest of the code there aren't any mistake.

答:
I did in main;

```<code>case 8:
        for(i=0;i<n;i++)
        {
            for(j=0;j<m;j++)
            {
                printf("Enter %d.row and %d.column: ",i+1,j+1);
                scanf("%d",&array[i][j]);
            }
        }
        sum_row_column(array,n,m,i,j);
        break;
</code>```

and in function;

```<code>void sum_row_column(int array[n][m],int r,int c,int i,int j)
{
int sumOfColumn=0;
int sumOfRow=0;
printf("\n");
for(i=0;i<r;i++)
{
    sumOfRow=0;
    for(j=0;j<c;j++)
    {
        sumOfRow+=array[i][j];
    }
    printf("Sum of %d.row=%d\n",i+1,sumOfRow);
}
printf("\n");
for(j=0;j<r;j++)
{
    sumOfColumn=0;
    for(i=0;i<c;i++)
    {
        sumOfColumn+=array[i][j];
    }
    printf("Sum of %d.column=%d\n",j+1,sumOfColumn);
}
}
</code>```

and its work! Thank you for your help.

Body:
I want to get the sum of each row and column of an array and print them one by one in C. I done half of work but I can't progress any more. There it is my code:

int n,m;
void sum_row_column(int array[n][m],int r,int c,int i,int j)
{
int sum_of_column1=0;
int sum_of_row1;

for(j=0,i=0;i<r;i++)
{
    sum_of_column1=sum_of_column1+array[i][j];
    if(i==r-1)
    {
        printf("\nSum of %d.column: %d\n",j+1,sum_of_column1);
        j=j+1;
    }
}

for(i=0,j=0;j<r;j++)
{
    sum_of_row1=sum_of_row1+array[i][j];
    if(j=c-1)
    {
        printf("\nSum of %d.row: %d\n",j+1,sum_of_row1);
        i=i+1;
    }
}

As you can see it prints just first row's sum and column's sum. I thought if I add

i=0;

after

printf("\nSum of %d.column: %d\n",j+1,sum_of_column1);
j=j+1

line, it can move second column and sum it too. But when I add

i=0;

the program go into infinite loop without any errors.
This code is in the header but don't worry in the rest of the code there aren't any mistake.

Body:
I did in main;

case 8:
        for(i=0;i<n;i++)
        {
            for(j=0;j<m;j++)
            {
                printf("Enter %d.row and %d.column: ",i+1,j+1);
                scanf("%d",&array[i][j]);
            }
        }
        sum_row_column(array,n,m,i,j);
        break;

and in function;

void sum_row_column(int array[n][m],int r,int c,int i,int j)
{
int sumOfColumn=0;
int sumOfRow=0;
printf("\n");
for(i=0;i<r;i++)
{
    sumOfRow=0;
    for(j=0;j<c;j++)
    {
        sumOfRow+=array[i][j];
    }
    printf("Sum of %d.row=%d\n",i+1,sumOfRow);
}
printf("\n");
for(j=0;j<r;j++)
{
    sumOfColumn=0;
    for(i=0;i<c;i++)
    {
        sumOfColumn+=array[i][j];
    }
    printf("Sum of %d.column=%d\n",j+1,sumOfColumn);
}
}

and its work! Thank you for your help.


问:
Complex circle diagram
I have spent loads of time trying to replicate the attached diagram in SVG/D3.js. The closest I have come is by using the code attached. I have explored using the tree function but  can only create one band of circles.

The issue with the attached code is it will be very hard to get it looking smooth and smart by manually typing which pixel coordinates each circle must sit.

For info, the dataset will do nothing more than colour these circles, so it can be entirely static in terms of shape. The code just needs to generate the shape, and I can then drive the colour based on the dataset.

image of what I am trying to create:

This is my code:

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>D3 Test</title>

```

答:
Prelude

Although this is a year old I would like to add my own two cents providing an entirely different approach as the one proposed by Gerardo. Every now and then I have advocated the use of the mighty SVG transformations available throught the transform attribute. Whatsoever, this mostly passes unnoticed for reasons that elude me. One such example is my answer to "SVG marker - can I set length and angle?". Most developers seem to prefer doing trigonometry on their own although I consider my solution less cumbersome and the resulting code much more clean and elegant as well as much more intuitively accessible.

To fully understand what is going on I encourage anybody not yet familiar with the topic to read and re-read the outstanding 3-part series on SVG coordinate systems and transformations by Sara Soueidan.

The approach I am going to present offloads all trigonometry to the browser whereby allowing for verbatim SVG code. If you did calculate the circles' positions on your own you would be left with coordinates like this:

```<code><circle cx="314.67156727579004" cy="276.78784026555627"></circle>
</code>```

The same circle could be generated with the following lines:

```<code><g transform="rotate(30)">
  <circle transform="translate(70)"></circle>
</g>
</code>```

Note, that some irrelevant attributes (r, fill) have been stripped from both snippets to just focus on the positioning. The latter is much more clear on what the developer wants to achieve:

Rotate the coordinate system by 30 degrees.

Translate the coordinate system by 70 pixels in the direction of the rotated x axis.

Draw the circle at that new origin.

There is not even the need to have cx and cy attributes as these will default to 0 allowing us start off from the origin and later offset the entire graphic by wrapping it in another group translating it to whereever it seems fit. The resulting SVG will be structured like follows:

Have a look at the following snippet for a working demo:

const svg = d3.select("svg>g");

const g = svg.selectAll(null)
  .data(d3.range(30, 361, 30))
  .enter().append("g")
    .attr("transform", d => `rotate(${d})`);

g.selectAll(null)
  .data(d3.range(40, 171, 30))
  .enter().append("circle")
    .attr("transform", d => `translate(${d})`)
    .attr("r", (d, i) => i === 4 ? 15 : 10)
    .attr("fill", "#ccc");
  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.js"></script>
<svg width="600" height="600">
  <g transform="translate(200,200)">
  </g>
</svg></code>```

Title: Complex circle diagram

Body:
Prelude

Although this is a year old I would like to add my own two cents providing an entirely different approach as the one proposed by Gerardo. Every now and then I have advocated the use of the mighty SVG transformations available throught the transform attribute. Whatsoever, this mostly passes unnoticed for reasons that elude me. One such example is my answer to "SVG marker - can I set length and angle?". Most developers seem to prefer doing trigonometry on their own although I consider my solution less cumbersome and the resulting code much more clean and elegant as well as much more intuitively accessible.

To fully understand what is going on I encourage anybody not yet familiar with the topic to read and re-read the outstanding 3-part series on SVG coordinate systems and transformations by Sara Soueidan.

The approach I am going to present offloads all trigonometry to the browser whereby allowing for verbatim SVG code. If you did calculate the circles' positions on your own you would be left with coordinates like this:

<circle cx="314.67156727579004" cy="276.78784026555627"></circle>

The same circle could be generated with the following lines:

<g transform="rotate(30)">
  <circle transform="translate(70)"></circle>
</g>

Note, that some irrelevant attributes (r, fill) have been stripped from both snippets to just focus on the positioning. The latter is much more clear on what the developer wants to achieve:

Rotate the coordinate system by 30 degrees.

Translate the coordinate system by 70 pixels in the direction of the rotated x axis.

Draw the circle at that new origin.

There is not even the need to have cx and cy attributes as these will default to 0 allowing us start off from the origin and later offset the entire graphic by wrapping it in another group translating it to whereever it seems fit. The resulting SVG will be structured like follows:

Have a look at the following snippet for a working demo:

const svg = d3.select("svg>g");

const g = svg.selectAll(null)
  .data(d3.range(30, 361, 30))
  .enter().append("g")
    .attr("transform", d => `rotate(${d})`);

g.selectAll(null)
  .data(d3.range(40, 171, 30))
  .enter().append("circle")
    .attr("transform", d => `translate(${d})`)
    .attr("r", (d, i) => i === 4 ? 15 : 10)
    .attr("fill", "#ccc");

<script src="https://d3js.org/d3.v4.js"></script>
<svg width="600" height="600">
  <g transform="translate(200,200)">
  </g>
</svg>


问:
Refresh blank screen issue in angular js
I am using Angular Pages template, whenever I redirect to any page or refresh I usually get a blank screen saying "Unknown service Provider" is that the problem of lazy load or something else which is causing the issue?</p>

答: Try using resolver as mentioned https://angular.io/api/router/Resolve which waits for page to load till you get your data from the source.</p>


问:
.NET POP3 Library that supports Proxy
I am looking for a pop3 library that will let me use a proxy. I have tried OpenPop.NET but it doesn't support proxy. Thanks in advance.</p>

答:
I am one of the developers of OpenPop.NET.
I have thought about supporting proxies, but have not added it as of yet. However, the Pop3Client  Connect method takes a stream, which it uses to communicate with the server. If you supply a stream, which is a proxied stream, then OpenPop.NET would work fine with it.
I have found a starksoft proxy project that should be able to deliver such streams. I have not tested it though. Also see this for more information on the starksoft proxy.

Hope it helps.

Title: .NET POP3 Library that supports Proxy


问:
How to set global variables from database in Laravel 5.4
I'm facing the same problem very often in various projects - I need to set some global variables from database and be able to receive them in anywhere in laravel - views, controllers, models. Is it possible? Or what is the most easy way to do this?

Why I need this? For language translations. I need them not cached and saved in file. For website options which can be taken from any place of app. For website language to set, because I don't want to make /language/ prefix on url.

Sorry if this question can be a duplicate, but none of the answers in similar questions worked in a way I have explained.

答:
the best way to access a variable everywhere in your project is using sessions. you can store everything in sessions and access it everywhere in your controllers, models and views.

Read the topic: https://laravel.com/docs/5.5/session#using-the-session


问:
factorial with trailing zeros, but without calculating factorial
I'm calculating the trailing zeros of a factorial. My solution is to calculate the factorial then determine how many trailing zeros it has. As you can imagine this isn't very scalable. How can I solve this without calculating the factorial?

I've found these pages on SO:
Trailing zeroes in a Factorial
Calculating the factorial without trailing zeros efficiently?

However, neither are in Javascript. If you downvote this question please let me know why. Thank-you for your time and feedback.

My solution:

```<code>function zeros(n) {
  var result = [];
  var count = 0;

  for (var i = 1; i <= n; i++) {
    result.push(i);
  } //generating range for factorial function

  var factorial = result.reduce(function(acc, el) {
    return acc * el;
  }, 1); //calculating factorial

  factorial = factorial.toString().split('');

  for (var j = factorial.length - 1; j > 0; j--) {
    if (parseInt(factorial[j]) === 0) {
      count += 1;
    } else {
      break;
    }
  } //counting trailing zeros

  return count;
}
</code>```

答:
You don't really need to calculate the factorial product to count the trailing zeroes.

Here a sample to count the number of trailing zeroes in n!

```<code>    temp = 5;
    zeroes = 0;
    //counting the sum of multiples of 5,5^2,5^3....present in n!
    while(n>=temp){
        fives = n/temp;
        zeroes = zeroes + fives;
        temp = temp*5;
    }
    printf("%d",zeroes);
</code>```

Note that each multiple of 5 in the factorial product will contribute 1 to the number of trailing zeros. On top of this, each multiple of 25 will contribute an additional 1 to the number of trailing zeros. Then, each multiple of 125 will contribute another 1 to the number of trailing zeros, and so on.

Here's a great link to understand the concept behind this: https://brilliant.org/wiki/trailing-number-of-zeros/

Body:
I'm calculating the trailing zeros of a factorial. My solution is to calculate the factorial then determine how many trailing zeros it has. As you can imagine this isn't very scalable. How can I solve this without calculating the factorial?

I've found these pages on SO:
Trailing zeroes in a Factorial
Calculating the factorial without trailing zeros efficiently?

However, neither are in Javascript. If you downvote this question please let me know why. Thank-you for your time and feedback.

My solution:

function zeros(n) {
  var result = [];
  var count = 0;

  for (var i = 1; i <= n; i++) {
    result.push(i);
  } //generating range for factorial function

  var factorial = result.reduce(function(acc, el) {
    return acc * el;
  }, 1); //calculating factorial

  factorial = factorial.toString().split('');

  for (var j = factorial.length - 1; j > 0; j--) {
    if (parseInt(factorial[j]) === 0) {
      count += 1;
    } else {
      break;
    }
  } //counting trailing zeros

  return count;
}

Body:
You don't really need to calculate the factorial product to count the trailing zeroes.

Here a sample to count the number of trailing zeroes in n!

    temp = 5;
    zeroes = 0;
    //counting the sum of multiples of 5,5^2,5^3....present in n!
    while(n>=temp){
        fives = n/temp;
        zeroes = zeroes + fives;
        temp = temp*5;
    }
    printf("%d",zeroes);

Note that each multiple of 5 in the factorial product will contribute 1 to the number of trailing zeros. On top of this, each multiple of 25 will contribute an additional 1 to the number of trailing zeros. Then, each multiple of 125 will contribute another 1 to the number of trailing zeros, and so on.

Here's a great link to understand the concept behind this: https://brilliant.org/wiki/trailing-number-of-zeros/


问:
How to see which lock was set in transaction sql?

I want to demo the lost update problem which this example

```<code>Create table tblInventory
(
    Id int,
    Name varchar(50),
    ItemsInStock int
    Constraint PK_PRODUCT
    Primary key (Id)
)
Insert tblInventory
Values (1,'Iphone',10)
</code>```

```<code> -- Transaction 1
 Begin Tran
 Declare @ItemsInStock int

 Select @ItemsInStock = ItemsInStock
 from tblInventory where Id=1

 -- Transaction takes 10 seconds

 Waitfor Delay '00:00:10'
 Set @ItemsInStock = @ItemsInStock - 1

 Update tblInventory
 Set ItemsInStock = @ItemsInStock where Id=1

 Print @ItemsInStock

 Commit Transaction

 -- Transaction 2
 Begin Tran
 Declare @ItemsInStock int

 Select @ItemsInStock = ItemsInStock
 from tblInventory where Id=1

 -- Transaction takes 1 second
 Waitfor Delay '00:00:1'
 Set @ItemsInStock = @ItemsInStock - 2

 Update tblInventory
 Set ItemsInStock = @ItemsInStock where Id=1

 Print @ItemsInStock

 Commit Transaction
</code>```

This example I get from this link: http://csharp-video-tutorials.blogspot.com/2015/08/sql-server-lost-update-problem.html

This example will corrupt lost update and I want to ask that have anyway to show which lock was set in transaction 1 and 2 on SQL Server like this:

Select => Lock type: S (Shared lock) => Isolation level : Read Committed

Update => Lock type: X (Exclusive lock) => Isolation level : Read Committed

As I know that when Select we will get Shared lock and when Update we will get Exclusive lock but I want display this in SQL Server

I have try use sp_who and sp_lock but not display the result I want

I'm using SQL Server 2008 R2

PS:/I have a small question that how to know which transaction can get lost update problem by look the query ?

Any help is appreciated.

Thanks in advance.

答:
Create an Extended Event trace including the lock_acquired and lock_released events. Add a filter to trace only those sessions of interest.

Below is trace example DDL for a session that writes events to a trace file for 2 sessions filtered on session_id. The trace can be started, stopped, and viewed from SSMS (Management-->Extended Events-->Sessions.

```<code>CREATE EVENT SESSION [locks] ON SERVER
ADD EVENT sqlserver.lock_acquired(SET collect_resource_description=(1)
    ACTION(sqlserver.session_id,sqlserver.sql_text)
    WHERE ([sqlserver].[session_id]=(56) OR [sqlserver].[session_id]=(57))),
ADD EVENT sqlserver.lock_released(SET collect_resource_description=(1)
    ACTION(sqlserver.session_id,sqlserver.sql_text)
    WHERE ([sqlserver].[session_id]=(56) OR [sqlserver].[session_id]=(57)))
ADD TARGET package0.event_file(SET filename=N'locks')
WITH (MAX_MEMORY=1048576 KB,EVENT_RETENTION_MODE=ALLOW_SINGLE_EVENT_LOSS,MAX_DISPATCH_LATENCY=30 SECONDS,MAX_EVENT_SIZE=0 KB,MEMORY_PARTITION_MODE=NONE,TRACK_CAUSALITY=OFF,STARTUP_STATE=OFF)
GO
</code>```

Body:
I want to demo the lost update problem which this example

Create table tblInventory
(
    Id int,
    Name varchar(50),
    ItemsInStock int
    Constraint PK_PRODUCT
    Primary key (Id)
)
Insert tblInventory
Values (1,'Iphone',10)

 -- Transaction 1
 Begin Tran
 Declare @ItemsInStock int

 Select @ItemsInStock = ItemsInStock
 from tblInventory where Id=1

 -- Transaction takes 10 seconds

 Waitfor Delay '00:00:10'
 Set @ItemsInStock = @ItemsInStock - 1

 Update tblInventory
 Set ItemsInStock = @ItemsInStock where Id=1

 Print @ItemsInStock

 Commit Transaction

 -- Transaction 2
 Begin Tran
 Declare @ItemsInStock int

 Select @ItemsInStock = ItemsInStock
 from tblInventory where Id=1

 -- Transaction takes 1 second
 Waitfor Delay '00:00:1'
 Set @ItemsInStock = @ItemsInStock - 2

 Update tblInventory
 Set ItemsInStock = @ItemsInStock where Id=1

 Print @ItemsInStock

 Commit Transaction

This example I get from this link: http://csharp-video-tutorials.blogspot.com/2015/08/sql-server-lost-update-problem.html

This example will corrupt lost update and I want to ask that have anyway to show which lock was set in transaction 1 and 2 on SQL Server like this:

Select => Lock type: S (Shared lock) => Isolation level : Read Committed

Update => Lock type: X (Exclusive lock) => Isolation level : Read Committed

As I know that when Select we will get Shared lock and when Update we will get Exclusive lock but I want display this in SQL Server

I have try use sp_who and sp_lock but not display the result I want

I'm using SQL Server 2008 R2

PS:/I have a small question that how to know which transaction can get lost update problem by look the query ?

Any help is appreciated.

Thanks in advance.

Body:
Create an Extended Event trace including the lock_acquired and lock_released events. Add a filter to trace only those sessions of interest.

Below is trace example DDL for a session that writes events to a trace file for 2 sessions filtered on session_id. The trace can be started, stopped, and viewed from SSMS (Management-->Extended Events-->Sessions.

CREATE EVENT SESSION [locks] ON SERVER
ADD EVENT sqlserver.lock_acquired(SET collect_resource_description=(1)
    ACTION(sqlserver.session_id,sqlserver.sql_text)
    WHERE ([sqlserver].[session_id]=(56) OR [sqlserver].[session_id]=(57))),
ADD EVENT sqlserver.lock_released(SET collect_resource_description=(1)
    ACTION(sqlserver.session_id,sqlserver.sql_text)
    WHERE ([sqlserver].[session_id]=(56) OR [sqlserver].[session_id]=(57)))
ADD TARGET package0.event_file(SET filename=N'locks')
WITH (MAX_MEMORY=1048576 KB,EVENT_RETENTION_MODE=ALLOW_SINGLE_EVENT_LOSS,MAX_DISPATCH_LATENCY=30 SECONDS,MAX_EVENT_SIZE=0 KB,MEMORY_PARTITION_MODE=NONE,TRACK_CAUSALITY=OFF,STARTUP_STATE=OFF)
GO


答:
Whenever a constructor is invoked the first statement needs to be a call to any constructor of the superclass. If you don't call it explicitly, the compiler will add a call to the default constructor for you (As explained in this question.).

In your case, the default constructor of your superclass calls the other constructor which in turn calls  System.out.println("2" + x);

This statement will print the string "2" appended to Integer.valueOf(x).toString(), resulting on the String "20" in your case (because x == 0).

Title: Superclass printing unexpected value when Subclass is created

Body:
Could you please help in understanding the output of below java code where this(0) of Superclass is called when object is created for Subclass.

In this code though there is no mention in the code to explicitly print 20, why the first value is printed as 20?

class Superclass {
    Superclass() {
        this(0);
        System.out.println("1");
    }

    Superclass(int x) {
        System.out.println("2" + x);
    }
}

class Subclass extends Superclass {
    Subclass(int x) {
        System.out.println("3" + x);
    }

    Subclass(int x, int y) {
        System.out.println("4" + x + y);
    }
}

public class practiceTest {
    public static void main(String[] args) {
        Subclass s = new Subclass(10, 20);
    }
}


问:
Looking for a good practice for dealing with repository in asp.net mvc
Currently I've got repository class for each data model for data access.

In the homepage, I need to display the top 5 records from each repository. So in the HomeController, I would need to have a lot of repository members, which doesn't feel right. Is there any good solution for this?

Thank you very much for your help. Any advice is welcome!

答:
you could do a generic Repository for basic operations, and inherit it when creating repositories for each entity in part.

but this way you would still need 5 instances or the generic repository.

so there are 2 ways:

1)

create a repository UniRepo

which has Generic Methods like Get<T>(int id), etc.

and use it in your HomeController

2)

don't put any instance of repository in HomeController, instead

create 5 controllers for each entity, and in each you put an instance of a repository, and create an action for that list

and in the home/index view you do

```<code>@Html.Action("list","entity1");
@Html.Action("list","entity2");
@Html.Action("list","entity3");
</code>```

Html.Action is equivalent to RenderAction

Body:
you could do a generic Repository for basic operations, and inherit it when creating repositories for each entity in part.

but this way you would still need 5 instances or the generic repository.

so there are 2 ways:

1)

create a repository UniRepo

which has Generic Methods like Get<T>(int id), etc.

and use it in your HomeController

2)

don't put any instance of repository in HomeController, instead

create 5 controllers for each entity, and in each you put an instance of a repository, and create an action for that list

and in the home/index view you do

@Html.Action("list","entity1");
@Html.Action("list","entity2");
@Html.Action("list","entity3");

Html.Action is equivalent to RenderAction


问:
express js URL cleanup

I create a rout that get user full details from the DATABASE(mongoDB).

Router

```<code>router.get('/user/:userid/:name', getUrl, function(req, res, next) {
  User.findOne({_id: req.params.userid})
  .exec(function(err, user) {
     if (err) { return next(err); }
     if (!user) { return next(404); }
     res.render('........');
 });
});
</code>```

for instance i can access this router with this URL:

```<code>http://127.0.0.1/user/6465667/username
</code>```

but what i realy want is this

```<code>http://127.0.0.1/user/username
</code>```

Is there a way of hiding the user ID in the URL

答:
Simply remove :userid from your route and use the name to lookup your database. Ensure your username is unique otherwise you might receive the wrong user details.

```<code>router.get('/user/:name', getUrl, function(req, res, next) {
  User.findOne({name: req.params.name})
  .exec(function(err, user) {
     if (err) { return next(err); }
     if (!user) { return next(404); }
     res.render('........');
 });
});
</code>```

Title: express js URL cleanup

Body:
I create a rout that get user full details from the DATABASE(mongoDB).

Router

router.get('/user/:userid/:name', getUrl, function(req, res, next) {
  User.findOne({_id: req.params.userid})
  .exec(function(err, user) {
     if (err) { return next(err); }
     if (!user) { return next(404); }
     res.render('........');
 });
});

for instance i can access this router with this URL:

http://127.0.0.1/user/6465667/username

but what i realy want is this

http://127.0.0.1/user/username

Is there a way of hiding the user ID in the URL

Body:
Simply remove :userid from your route and use the name to lookup your database. Ensure your username is unique otherwise you might receive the wrong user details.

router.get('/user/:name', getUrl, function(req, res, next) {
  User.findOne({name: req.params.name})
  .exec(function(err, user) {
     if (err) { return next(err); }
     if (!user) { return next(404); }
     res.render('........');
 });
});