问:
App crashes on resuming by clicking the app icon from menu
App launches normally. When I try to minimize it and reopen through the recent apps history, again it works fine. But when I minimize and try to re open it with the app icon, it crashes.

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity implements ResetPasswordDialog.Listener {

public static final String TAG = MainActivity.class.getSimpleName();

private LoginFragment mLoginFragment;
private ResetPasswordDialog mResetPasswordDialog;

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

    if (savedInstanceState == null) {

        loadFragment();
    }
}

private void loadFragment(){

    if (mLoginFragment == null) {

        mLoginFragment = new LoginFragment();
    }
    getFragmentManager().beginTransaction().replace(R.id.fragmentFrame,mLoginFragment,LoginFragment.TAG).commit();
}

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

    String data = intent.getData().getLastPathSegment();
    Log.d(TAG, "onNewIntent: "+data);

    mResetPasswordDialog = (ResetPasswordDialog) getFragmentManager().findFragmentByTag(ResetPasswordDialog.TAG);

    if (mResetPasswordDialog != null)
        mResetPasswordDialog.setToken(data);
}

@Override
public void onPasswordReset(String message) {

    showSnackBarMessage(message);
}

private void showSnackBarMessage(String message) {

    Snackbar.make(findViewById(R.id.activity_main),message, Snackbar.LENGTH_SHORT).show();

}
</code>```

}

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<uses-feature
    android:name="android.hardware.camera"
    android:required="true" />
<uses-feature
    android:name="android.hardware.camera.front"
    android:required="false" />
<uses-feature
    android:name="android.hardware.camera.autofocus"
    android:required="false" />

<!--singleTask => flag of launchMode -->
<application
    android:name="io.github.froger.xinger.InstaMaterialApplication"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">

    <activity
        android:name="io.github.froger.xinger.ui.activity.MainActivity"
        android:launchMode="singleTop"
        android:theme="@style/AppTheme.LoginRegister"
        android:screenOrientation="portrait">

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />

        </intent-filter>

        <intent-filter>
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:host="learn2crack"
                android:scheme="http" />
        </intent-filter>
    </activity>

    <activity
        android:name="io.github.froger.xinger.ui.activity.DashboardActivity"
        android:screenOrientation="portrait">
    </activity>
    <activity
        android:name="io.github.froger.xinger.ui.activity.CommentsActivity"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.TransparentActivity" />
    <activity
        android:name="io.github.froger.xinger.ui.activity.UserProfileActivity"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.TransparentActivity"
        android:launchMode="singleInstance" />
    <activity
        android:name="io.github.froger.xinger.ui.activity.TakePhotoActivity"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.TransparentActivity" />
    <activity
        android:name="io.github.froger.xinger.ui.activity.PublishActivity"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme"
        android:windowSoftInputMode="stateHidden">

    </activity>
</application>
</code>```

Error

```<code>04-01 00:51:26.015 25525-25525/io.github.froger.instamaterial D/AndroidRuntime: Shutting down VM
04-01 00:51:26.016 25525-25525/io.github.froger.instamaterial E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            Process: io.github.froger.instamaterial, PID: 25525
                                                                            java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
                                                                                at io.github.froger.xinger.ui.activity.MainActivity.onNewIntent(MainActivity.java:44)
                                                                                at android.app.Instrumentation.callActivityOnNewIntent(Instrumentation.java:1245)
                                                                                at android.app.Instrumentation.callActivityOnNewIntent(Instrumentation.java:1257)
                                                                                at android.app.ActivityThread.deliverNewIntents(ActivityThread.java:2804)
                                                                                at android.app.ActivityThread.performNewIntents(ActivityThread.java:2816)
                                                                                at android.app.ActivityThread.handleNewIntent(ActivityThread.java:2825)
                                                                                at android.app.ActivityThread.-wrap15(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1552)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
</code>```

答:
You could store string data in a static variable, and then check to see if it's null. If it's null use the static data. I know static variables are frowned upon and you should address the root problem, but this will fix your immediate problem.</p>

```<code>static String yourStaticString;

...
String data;
if (intent.getData()==NULL)
{
      data = yourStaticString;
}
else
{
     if (intent.getData().getLastPathSegment()!=NULL)
     {
             data = intent.getData().getLastPathSegment();
             yourStaticString = data;
     } else return;
}
</code>```

Body:
App launches normally. When I try to minimize it and reopen through the recent apps history, again it works fine. But when I minimize and try to re open it with the app icon, it crashes.

MainActivity.java

public class MainActivity extends AppCompatActivity implements ResetPasswordDialog.Listener {

public static final String TAG = MainActivity.class.getSimpleName();

private LoginFragment mLoginFragment;
private ResetPasswordDialog mResetPasswordDialog;

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

    if (savedInstanceState == null) {

        loadFragment();
    }
}

private void loadFragment(){

    if (mLoginFragment == null) {

        mLoginFragment = new LoginFragment();
    }
    getFragmentManager().beginTransaction().replace(R.id.fragmentFrame,mLoginFragment,LoginFragment.TAG).commit();
}

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

    String data = intent.getData().getLastPathSegment();
    Log.d(TAG, "onNewIntent: "+data);

    mResetPasswordDialog = (ResetPasswordDialog) getFragmentManager().findFragmentByTag(ResetPasswordDialog.TAG);

    if (mResetPasswordDialog != null)
        mResetPasswordDialog.setToken(data);
}

@Override
public void onPasswordReset(String message) {

    showSnackBarMessage(message);
}

private void showSnackBarMessage(String message) {

    Snackbar.make(findViewById(R.id.activity_main),message, Snackbar.LENGTH_SHORT).show();

}

}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<uses-feature
    android:name="android.hardware.camera"
    android:required="true" />
<uses-feature
    android:name="android.hardware.camera.front"
    android:required="false" />
<uses-feature
    android:name="android.hardware.camera.autofocus"
    android:required="false" />

<application
    android:name="io.github.froger.xinger.InstaMaterialApplication"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">

    <activity
        android:name="io.github.froger.xinger.ui.activity.MainActivity"
        android:launchMode="singleTop"
        android:theme="@style/AppTheme.LoginRegister"
        android:screenOrientation="portrait">

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />

        </intent-filter>

        <intent-filter>
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:host="learn2crack"
                android:scheme="http" />
        </intent-filter>
    </activity>

    <activity
        android:name="io.github.froger.xinger.ui.activity.DashboardActivity"
        android:screenOrientation="portrait">
    </activity>
    <activity
        android:name="io.github.froger.xinger.ui.activity.CommentsActivity"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.TransparentActivity" />
    <activity
        android:name="io.github.froger.xinger.ui.activity.UserProfileActivity"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.TransparentActivity"
        android:launchMode="singleInstance" />
    <activity
        android:name="io.github.froger.xinger.ui.activity.TakePhotoActivity"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.TransparentActivity" />
    <activity
        android:name="io.github.froger.xinger.ui.activity.PublishActivity"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme"
        android:windowSoftInputMode="stateHidden">

    </activity>
</application>

Error

04-01 00:51:26.015 25525-25525/io.github.froger.instamaterial D/AndroidRuntime: Shutting down VM
04-01 00:51:26.016 25525-25525/io.github.froger.instamaterial E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            Process: io.github.froger.instamaterial, PID: 25525
                                                                            java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
                                                                                at io.github.froger.xinger.ui.activity.MainActivity.onNewIntent(MainActivity.java:44)
                                                                                at android.app.Instrumentation.callActivityOnNewIntent(Instrumentation.java:1245)
                                                                                at android.app.Instrumentation.callActivityOnNewIntent(Instrumentation.java:1257)
                                                                                at android.app.ActivityThread.deliverNewIntents(ActivityThread.java:2804)
                                                                                at android.app.ActivityThread.performNewIntents(ActivityThread.java:2816)
                                                                                at android.app.ActivityThread.handleNewIntent(ActivityThread.java:2825)
                                                                                at android.app.ActivityThread.-wrap15(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1552)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)

Body:
You could store string data in a static variable, and then check to see if it's null. If it's null use the static data. I know static variables are frowned upon and you should address the root problem, but this will fix your immediate problem.

static String yourStaticString;

...
String data;
if (intent.getData()==NULL)
{
      data = yourStaticString;
}
else
{
     if (intent.getData().getLastPathSegment()!=NULL)
     {
             data = intent.getData().getLastPathSegment();
             yourStaticString = data;
     } else return;
}


来源: stackexchange

问:
connect to SQL hosted on a local machine from my laptop (using an IP)
I set up an SQL server on my Windows 7 PC.

I have a laptop, from which I want to connect to the SQL server (using visual studio 2010).
I need to fill in a "server name" when creating a database connection.

I tried "My.IP.Address/SQLEXPRESS,custom-port", but that doesn't work. All examples talk about using server names which are formatted like so "TOM-PC/SQLEXPRESS", but I have an important requirement:

I want to be able to connect from anywhere (not only when in the same local network), therefore I'm trying to use the IP address (the port isn't simply 1433 since my ISP blocks it).

The custom port is open, and reachable in tests.

I've been Googling this all day long, but can't find a solution. Please help!

Thank you,

Tom

答:
If you are saying that you have a PC at location A that has SQL and you want to be able to access it from anywhere, well, then you're going to need a static IP from your ISP, a firewall with the proper NAT rules. And even then, it'll be a different IP when you're local (within the same network) than it is when you are at the local coffee shop.

My suggestion would be to use the local server reference and install SQL on your laptop. If you publish your work to your PC at home, then it'll use the local SQL server there too. This is what I do. I use RedGate tools to sync up my DBs.

If you have SQL and VS on the same machine (your laptop) and are trying to connect to the SQL server from VS (e.g. in debugger), then try the following: (I'm working like this all the time)

You can use (local) or . as the server in a SQL connection to refer to the local machine.

In your case:

```<code>(local)\SQLEXPRESS
</code>```

or

```<code>.\SQLEXPRESS
</code>```

ContentLicense: CC BY-SA 2.5

Body:
If you are saying that you have a PC at location A that has SQL and you want to be able to access it from anywhere, well, then you're going to need a static IP from your ISP, a firewall with the proper NAT rules. And even then, it'll be a different IP when you're local (within the same network) than it is when you are at the local coffee shop.

My suggestion would be to use the local server reference and install SQL on your laptop. If you publish your work to your PC at home, then it'll use the local SQL server there too. This is what I do. I use RedGate tools to sync up my DBs.

If you have SQL and VS on the same machine (your laptop) and are trying to connect to the SQL server from VS (e.g. in debugger), then try the following: (I'm working like this all the time)

You can use (local) or . as the server in a SQL connection to refer to the local machine.

In your case:

(local)\SQLEXPRESS

or

.\SQLEXPRESS


问:
Get filename and extension from filepath programmatically cocoa?
I know you can use NSBundle:

```<code> NSString *filePath = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"rtf"];
</code>```

to get the filepath of a file, but how would I get the filename and extension (separately) from the filepath programmatically using NSBundle.

For example, I may have: /Users/theuser/Documents/yourdocument.txt

It is obvious that the file is 'yourdocument', and the extension 'txt'

But I need to get the filename and extension from the filepath to use as an NSString.

Your help is greatly appreciated!

答:
Try this, it works for me.</p>

```<code>NSString *fileName = @"yourFileName.pdf";
NSString *ext = [fileName pathExtension];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I know you can use NSBundle:

 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"rtf"];

to get the filepath of a file, but how would I get the filename and extension (separately) from the filepath programmatically using NSBundle.

For example, I may have: /Users/theuser/Documents/yourdocument.txt

It is obvious that the file is 'yourdocument', and the extension 'txt'

But I need to get the filename and extension from the filepath to use as an NSString.

Your help is greatly appreciated!

Body:
Try this, it works for me.

NSString *fileName = @"yourFileName.pdf";
NSString *ext = [fileName pathExtension];


问:
How to reboot CentOS 7 with Ansible?
I'm trying to reboot server running CentOS 7 on VirtualBox. I use this task:

```<code>- name: Restart server
  command: /sbin/reboot
  async: 0
  poll: 0
  ignore_errors: true
</code>```

Server is rebooted, but I get this error:

```<code>TASK: [common | Restart server] ***********************************************
fatal: [rolcabox] => SSH Error: Shared connection to 127.0.0.1 closed.
It is sometimes useful to re-run the command using -vvvv, which prints SSH debug output to help diagnose the issue.

FATAL: all hosts have already failed -- aborting
</code>```

What am I doing wrong? How can I fix this?

答:
None of the above solutions worked reliably for me.

Issuing a /sbin/reboot crashes the play (the SSH connection is closed before ansible finished the task, it crashes even with ignore_errors: true) and /usr/bin/systemd-run --on-active=2 /usr/bin/systemctl reboot will not reboot after 2 seconds, but after a random amount of time between 20 seconds and one minute, so the delay is sometime not sufficient and this is not predictable.

Also I don't want to wait for minutes while a cloud server can reboot in few seconds.

So here is my solution:

```<code>- name: Reboot the server for kernel update
  shell: ( sleep 3 && /sbin/reboot & )
  async: 0
  poll: 0

- name: Wait for the server to reboot
  local_action: wait_for host="{{ansible_host}}" delay=15 state=started port="{{ansible_port}}" connect_timeout=10 timeout=180
</code>```

That's the shell: ( sleep 3 && /sbin/reboot & ) line that does the trick.

Using ( command & ) in shell script runs a program in the background and detaches it: the command succeed immediately but persists after the shell is destroyed.

Ansible get its response immediately and the server reboots 3 seconds later.

Title: How to reboot CentOS 7 with Ansible?

Body:
I'm trying to reboot server running CentOS 7 on VirtualBox. I use this task:

- name: Restart server
  command: /sbin/reboot
  async: 0
  poll: 0
  ignore_errors: true

Server is rebooted, but I get this error:

TASK: [common | Restart server] ***********************************************
fatal: [rolcabox] => SSH Error: Shared connection to 127.0.0.1 closed.
It is sometimes useful to re-run the command using -vvvv, which prints SSH debug output to help diagnose the issue.

FATAL: all hosts have already failed -- aborting

What am I doing wrong? How can I fix this?

Body:
None of the above solutions worked reliably for me.

Issuing a /sbin/reboot crashes the play (the SSH connection is closed before ansible finished the task, it crashes even with ignore_errors: true) and /usr/bin/systemd-run --on-active=2 /usr/bin/systemctl reboot will not reboot after 2 seconds, but after a random amount of time between 20 seconds and one minute, so the delay is sometime not sufficient and this is not predictable.

Also I don't want to wait for minutes while a cloud server can reboot in few seconds.

So here is my solution:

- name: Reboot the server for kernel update
  shell: ( sleep 3 && /sbin/reboot & )
  async: 0
  poll: 0

- name: Wait for the server to reboot
  local_action: wait_for host="{{ansible_host}}" delay=15 state=started port="{{ansible_port}}" connect_timeout=10 timeout=180

That's the shell: ( sleep 3 && /sbin/reboot & ) line that does the trick.

Using ( command & ) in shell script runs a program in the background and detaches it: the command succeed immediately but persists after the shell is destroyed.

Ansible get its response immediately and the server reboots 3 seconds later.


问:
Converting seconds in mm:ss in running JavaScript Timer
I'm just trying to update a friend's timer, which we did for an event a while ago. The timer works perfectly and already does everything it should (see and run Snippet). However, now I would like to display the format mm:ss instead of only seconds (eg. 180 -> 3:00). This must of course be able to count down further. Different approaches I googled have failed. Has anyone an idea how to solve my problem elegantly?

Edit: You can start and stop the timer by pressing 'Space'

<!DOCTYPE html>

  <title></title>

    <svg width="160" height="160" xmlns="http://www.w3.org/2000/svg">
      <g>
        <title>Layer 1</title>
        <circle id="circle" r="65.85699" cy="81" cx="81" stroke-width="15" stroke="#ffffff" fill="none"/>
        <circle id="circle" class="circle_animation" r="65.85699" cy="81" cx="81" stroke-width="16" stroke="#333" fill="none"/>
      </g>
    </svg>

180

```

答:
Use modulus math:

```<code>function sec2human(seconds) {
    sec = seconds % 60;
    min = parseInt(seconds / 60);
    if(sec.toString().length == 1) { // padding
        sec = "0" + sec;
    }
    return min + ":" + sec;
}
</code>```

Full working example:

<!DOCTYPE html>

  <title></title>

    <svg width="160" height="160" xmlns="http://www.w3.org/2000/svg">
      <g>
        <title>Layer 1</title>
        <circle id="circle" r="65.85699" cy="81" cx="81" stroke-width="15" stroke="#ffffff" fill="none"/>
        <circle id="circle" class="circle_animation" r="65.85699" cy="81" cx="81" stroke-width="16" stroke="#333" fill="none"/>
      </g>
    </svg>

180

```

Body:
Use modulus math:

function sec2human(seconds) {
    sec = seconds % 60;
    min = parseInt(seconds / 60);
    if(sec.toString().length == 1) { // padding
        sec = "0" + sec;
    }
    return min + ":" + sec;
}

Full working example:

<!DOCTYPE html>
<html>

<head>
  <title></title>

  <style type="text/css">
    body {
      background-color: #333;
      font-family: sans-serif;
    }

    .item {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translateX(-50%) translateY(-50%) scale(3.0);
    }

    .item h1 {
      text-align: center;
      position: absolute;
      width: 100%;
      top: 50%;
      left: 50%;
      transform: translateX(-50%) translateY(-110%);
      color: #ffffff;
      font-size: 3em;
    }

    .item h2 {
      text-align: center;
      position: absolute;
      width: 50%;
      top: 50%;
      left: 50%;
      transform: translateX(-50%) translateY(-110%);
      color: #ffffff;
      font-size: 1.5em;
      line-height: 0.9;
    }

    svg {
      -webkit-transform: rotate(-90deg);
      transform: rotate(-90deg);
    }

    .circle_animation {
      stroke-dasharray: 440;
      /* this value is the pixel circumference of the circle */
      stroke-dashoffset: 440;
      transition: all 1s linear;
    }
  </style>

  <script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>

  <script type="text/javascript">
    var running = false;

    var time = 180;
    var initialOffset = '440';
    var runtime = 0;

    $(document).keydown(function(e) {

      switch (e.which) {
        case 32:
          setTimeout(function() {
            if (running === false) {
              running = true;
            } else {
              running = false;
            };
          }, 1);
          break;
      }
    });

    $(document).ready(function() {

      console.log("ready!");
      $('#start').click(function() {
        running = true;
      });

      $('h1').text(sec2human(time)); // added for initial display

      var interval = setInterval(function() {
        $('.circle_animation').css('stroke-dashoffset', initialOffset - (runtime * (initialOffset / (time + 10.5))));
        $('h1').text(sec2human(time - runtime)); // added function call
        if (runtime == 420) {
          audioElement1.play();
        }
        if (runtime == time) {
          clearInterval(interval);
          $('.circle_animation').css('stroke-dashoffset', 880);
          $('h1').text('');
          $('h2').text('Time is up!');
        }
        if (running) {
          runtime++;
        };
      }, 1000);

    });

    function sec2human(seconds) {
        sec = seconds % 60;
        min = parseInt(seconds / 60);
        if(sec.toString().length == 1) { // padding
            sec = "0" + sec;
        }
        return min + ":" + sec;
    }
  </script>

</head>

<body>

  <div class="item html">
    <svg width="160" height="160" xmlns="http://www.w3.org/2000/svg">
      <g>
        <title>Layer 1</title>
        <circle id="circle" r="65.85699" cy="81" cx="81" stroke-width="15" stroke="#ffffff" fill="none"/>
        <circle id="circle" class="circle_animation" r="65.85699" cy="81" cx="81" stroke-width="16" stroke="#333" fill="none"/>
      </g>
    </svg>
    <h1>180</h1>
    <h2></h2>
  </div>

</body>

</html>


问:
Unable to configure textvaraible for Entry widget
I was making a program and part of it was:

```<code>ent = Entry(root)
</code>```

and then later:

```<code>ent.config(textvarible=a)
</code>```

(a is a number)
When I load the program the entry is not changed. What's wrong and how can I fix it?

答:
Entry widgets don't work that way (Labels do). To set the value in an entry wdiget you need to delete the current contents and insert the new contents:

```<code>ent.delete(0, 'end')
ent.insert(0, a)
</code>```

There is a second way of doing this. You could bind the value of the Entry to a StringVar, and then the Entry will display whatever the StringVar is set to.

```<code>var = StringVar(root)
ent = Entry(root, textvariable=var)

# to update:
var.set(a)
</code>```

Also, with this method the StringVar reflects all changes the user makes to the Entry, so you need to deal with var only.

Body:
I was making a program and part of it was:

ent = Entry(root)

and then later:

ent.config(textvarible=a)

(a is a number)
When I load the program the entry is not changed. What's wrong and how can I fix it?

Body:
Entry widgets don't work that way (Labels do). To set the value in an entry wdiget you need to delete the current contents and insert the new contents:

ent.delete(0, 'end')
ent.insert(0, a)

There is a second way of doing this. You could bind the value of the Entry to a StringVar, and then the Entry will display whatever the StringVar is set to.

var = StringVar(root)
ent = Entry(root, textvariable=var)

# to update:
var.set(a)

Also, with this method the StringVar reflects all changes the user makes to the Entry, so you need to deal with var only.


问:
removing grid lines in C# Chart & making thicker graph lines
I'm using the built in chart class of .net 4 and I just cant find a way to remove the grid lines on the chart. Is there a way of doing it?
And another question, how do I make the graph lines thicker?

Thanks :)

答: with the chart selected go to its settings menu and click into chartarea(collection).go to Axes(collection) clicking on this will open a new menu. you will find the grid settings under gridtickmarks-majorgrid. with this you can change/delete the grid with no code required.</p>


问:
UICollectionViewCell is overlapped when scrolling
Following code is a very simple program which is used to display numbers from 1-10000 in the UICollectionView. It is displaying correctly without scrolling, but the cells are overlapped if you scroll down and scroll back the collection view.

```<code>-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 10000;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(100,30);
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSString *identifier = @"cell_id";
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    [label setText:[NSString stringWithFormat:@"%d", indexPath.item, nil]];
    [cell.contentView addSubview:label];

    return cell;
}
</code>```

答:
This worked for me in Swift 3:
Almost same solution as approved solution, note that I used

```<code>cell.subViews
</code>```

instead of

```<code>cell.contentView.subViews
</code>```

What's worked for me is:

```<code>for view in cell.subviews {
  view.removeFromSuperview()
}
</code>```

Body:
Following code is a very simple program which is used to display numbers from 1-10000 in the UICollectionView. It is displaying correctly without scrolling, but the cells are overlapped if you scroll down and scroll back the collection view.

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 10000;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(100,30);
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSString *identifier = @"cell_id";
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    [label setText:[NSString stringWithFormat:@"%d", indexPath.item, nil]];
    [cell.contentView addSubview:label];

    return cell;
}

Body:
This worked for me in Swift 3:
Almost same solution as approved solution, note that I used

cell.subViews

instead of

cell.contentView.subViews

What's worked for me is:

for view in cell.subviews {
  view.removeFromSuperview()
}


问:
Android Share sliding image on whatsapp using intent from viewPager using glide
I am working on online gallery app, in a fragment Dialog images from specific displaying as a viewPager.
But the main problem i am unable to share a particular image on whatsapp because I am finding difficulty to get imageViewPreview.

Here is the code for loading image in viewPager

```<code>public class MyViewPagerAdapter extends PagerAdapter {

    private LayoutInflater layoutInflater;

    public MyViewPagerAdapter() {
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.image_fullscreen_preview, container, false);

        final ImageView imageViewPreview = (ImageView) view.findViewById(R.id.image_preview);

        Image image = images.get(position);

        Glide.with(getActivity()).load(image.getLarge())
                .thumbnail(0.5f)
                .crossFade()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(imageViewPreview);

        container.addView(view);
</code>```

return view;
        }

Now i am trying to get image from imageViewPreview from

```<code>whatsappShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                 Log.e(TAG, "Click working");
                //shareImage();
               // ImageView imageWhatsapp = (ImageView) view.findViewById(R.id.image_preview);
                Uri bmpUri = getLocalBitmapUri(imageViewPreview);
                if (bmpUri != null) {
                    // Construct a ShareIntent with link to image
                    Intent shareIntent = new Intent();
                    shareIntent.setAction(Intent.ACTION_SEND);
                    shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
                    shareIntent.setType("image/*");
                    shareIntent.setPackage("com.whatsapp");
                    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

                    // Launch sharing dialog for image
                    startActivity(Intent.createChooser(shareIntent, "Share Image"));
                } else {
                    // ...sharing failed, handle error
                    Log.e(TAG, "ERROR" + bmpUri);
                }
            }

        });
</code>```

My getLocalBitmapUri() methos is as follow:

```<code>public Uri getLocalBitmapUri(ImageView imageViewPreview) {
    // Extract Bitmap from ImageView drawable
    Drawable drawable = imageViewPreview.getDrawable();
    Bitmap bmp = null;
    if (drawable instanceof BitmapDrawable) {
        bmp = ((BitmapDrawable) imageViewPreview.getDrawable()).getBitmap();
    } else {
        return null;
    }
    // Store image to default external storage directory
    Uri bmpUri = null;
    try {
        File file = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
        file.getParentFile().mkdirs();
        FileOutputStream out = new FileOutputStream(file);

        Log.e(TAG, "popopo: " + file);
        bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
        out.close();
        bmpUri = Uri.fromFile(file);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bmpUri;
}

But the problem is I am getting **NULL** from getLocalBitmapUri() method.
please guide me the get imageViewPreview.
</code>```

答:
i had faced sacreate this method, few time ago i used it and work, i forgot who given this snippet.

```<code>public Bitmap drawableToBitmap (Drawable drawable) {
    Bitmap bitmap = null;

    if (drawable instanceof BitmapDrawable) {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
        if(bitmapDrawable.getBitmap() != null) {
            return bitmapDrawable.getBitmap();
        }
    }

    if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
        bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
    } else {
        bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    }

    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);
    return bitmap;
}
</code>```

at your getLocalBitmapUri()

```<code>public Uri getLocalBitmapUri(ImageView imageViewPreview) {
   // Extract Bitmap from ImageView drawable
   Drawable drawable = imageViewPreview.getDrawable();
   Bitmap bmp = drawableToBitmap(imageViewPreview);
   //...................
   try {
    File file = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
    file.getParentFile().mkdirs();
    if(!file.exist()) file.createNewFile();
    //..............
</code>```

Body:
I am working on online gallery app, in a fragment Dialog images from specific displaying as a viewPager.
But the main problem i am unable to share a particular image on whatsapp because I am finding difficulty to get imageViewPreview.

Here is the code for loading image in viewPager

public class MyViewPagerAdapter extends PagerAdapter {

    private LayoutInflater layoutInflater;

    public MyViewPagerAdapter() {
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.image_fullscreen_preview, container, false);

        final ImageView imageViewPreview = (ImageView) view.findViewById(R.id.image_preview);

        Image image = images.get(position);

        Glide.with(getActivity()).load(image.getLarge())
                .thumbnail(0.5f)
                .crossFade()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(imageViewPreview);

        container.addView(view);

return view;
        }

Now i am trying to get image from imageViewPreview from

whatsappShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                 Log.e(TAG, "Click working");
                //shareImage();
               // ImageView imageWhatsapp = (ImageView) view.findViewById(R.id.image_preview);
                Uri bmpUri = getLocalBitmapUri(imageViewPreview);
                if (bmpUri != null) {
                    // Construct a ShareIntent with link to image
                    Intent shareIntent = new Intent();
                    shareIntent.setAction(Intent.ACTION_SEND);
                    shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
                    shareIntent.setType("image/*");
                    shareIntent.setPackage("com.whatsapp");
                    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

                    // Launch sharing dialog for image
                    startActivity(Intent.createChooser(shareIntent, "Share Image"));
                } else {
                    // ...sharing failed, handle error
                    Log.e(TAG, "ERROR" + bmpUri);
                }
            }

        });

My getLocalBitmapUri() methos is as follow:

public Uri getLocalBitmapUri(ImageView imageViewPreview) {
    // Extract Bitmap from ImageView drawable
    Drawable drawable = imageViewPreview.getDrawable();
    Bitmap bmp = null;
    if (drawable instanceof BitmapDrawable) {
        bmp = ((BitmapDrawable) imageViewPreview.getDrawable()).getBitmap();
    } else {
        return null;
    }
    // Store image to default external storage directory
    Uri bmpUri = null;
    try {
        File file = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
        file.getParentFile().mkdirs();
        FileOutputStream out = new FileOutputStream(file);

        Log.e(TAG, "popopo: " + file);
        bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
        out.close();
        bmpUri = Uri.fromFile(file);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bmpUri;
}

But the problem is I am getting **NULL** from getLocalBitmapUri() method.
please guide me the get imageViewPreview.

Body:
i had faced sacreate this method, few time ago i used it and work, i forgot who given this snippet.

public Bitmap drawableToBitmap (Drawable drawable) {
    Bitmap bitmap = null;

    if (drawable instanceof BitmapDrawable) {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
        if(bitmapDrawable.getBitmap() != null) {
            return bitmapDrawable.getBitmap();
        }
    }

    if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
        bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
    } else {
        bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    }

    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);
    return bitmap;
}

at your getLocalBitmapUri()

public Uri getLocalBitmapUri(ImageView imageViewPreview) {
   // Extract Bitmap from ImageView drawable
   Drawable drawable = imageViewPreview.getDrawable();
   Bitmap bmp = drawableToBitmap(imageViewPreview);
   //...................
   try {
    File file = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
    file.getParentFile().mkdirs();
    if(!file.exist()) file.createNewFile();
    //..............


问:
can not extract response body to set environment variable
I have response body from POST method like below

```<code>{
    "status": {
        "error": false,
        "code": 200,
        "message": "Login success"
    },
    "result": {
        "data": {
            "name": "vv",
            "email": "gg@gmail.com",
            "session_key": "xxx"
        }
    }
}
</code>```

Then I want to extract that session key to add in the environment variable
I used this code

```<code>var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("session", jsonData.sesssion_key);
</code>```

But on the environment variable still return with "undefined" value
Please help, Thanks

答:
```<code>var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("session", jsonData.result.data.session_key);
</code>```

you need to provide the exact path to get the value of session_key.

I didnt test it , but it should work.

Body:
I have response body from POST method like below

{
    "status": {
        "error": false,
        "code": 200,
        "message": "Login success"
    },
    "result": {
        "data": {
            "name": "vv",
            "email": "gg@gmail.com",
            "session_key": "xxx"
        }
    }
}

Then I want to extract that session key to add in the environment variable
I used this code

var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("session", jsonData.sesssion_key);

But on the environment variable still return with "undefined" value
Please help, Thanks

Body:
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("session", jsonData.result.data.session_key);

you need to provide the exact path to get the value of session_key.

I didnt test it , but it should work.


问:
Integer Arguments Error
I'm attempting to write a program that takes two integer arguments. After some research, I've learned that I need to use the int() funtion when defining the arguments. However, I get an error when I try this code:

```<code>import sys

a, b = int(sys.argv[1]), int(sys.argv[2])
</code>```

I get this error:

```<code>ValueError                                Traceback (most recent call last)
<ipython-input-11-7a4a02a9d164> in <module>()
----> 1 a, b = int(sys.argv[1]), int(sys.argv[2])

ValueError: invalid literal for int() with base 10: '-f'
</code>```

I've been unable to resolve this despite researching. Is this an issue related to my python version perhaps?

Thanks in advance.

EDIT: I'm running this code in a Jupyter Notebook. Running the same code in Terminal throws this error:

```<code>>>> import sys
>>> a = int(sys.argv[1])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
</code>```

答:
You haven't assigned argv to anything. Argv contains the command line arguements for a python script run from the shell. Learn about argv here: Run in the terminal, argv will be an empty list with zero elements. So argv[0] and argv1 can't be accessed (they don't exist).

When you run your script in a Jupityer notebook, the notebook itself has command-line arguments 'higher up'. Your first argument isn't what you want (whatever integer you entered), so you can't convert it's type.

You have three options for writing a program:
 - Work directly from a script
 - Command Line Arguments
 - input during runtime

You might not even need to use command line arguments.

```<code>def add_from_user_input():
    a = input('first number')
    b = input('second number')
    return a+b
</code>```

Title: Integer Arguments Error

Body:
I'm attempting to write a program that takes two integer arguments. After some research, I've learned that I need to use the int() funtion when defining the arguments. However, I get an error when I try this code:

import sys

a, b = int(sys.argv[1]), int(sys.argv[2])

I get this error:

ValueError                                Traceback (most recent call last)
<ipython-input-11-7a4a02a9d164> in <module>()
----> 1 a, b = int(sys.argv[1]), int(sys.argv[2])

ValueError: invalid literal for int() with base 10: '-f'

I've been unable to resolve this despite researching. Is this an issue related to my python version perhaps?

Thanks in advance.

EDIT: I'm running this code in a Jupyter Notebook. Running the same code in Terminal throws this error:

>>> import sys
>>> a = int(sys.argv[1])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

Body:
You haven't assigned argv to anything. Argv contains the command line arguements for a python script run from the shell. Learn about argv here: Run in the terminal, argv will be an empty list with zero elements. So argv[0] and argv1 can't be accessed (they don't exist).

When you run your script in a Jupityer notebook, the notebook itself has command-line arguments 'higher up'. Your first argument isn't what you want (whatever integer you entered), so you can't convert it's type.

You have three options for writing a program:
 - Work directly from a script
 - Command Line Arguments
 - input during runtime

You might not even need to use command line arguments.

def add_from_user_input():
    a = input('first number')
    b = input('second number')
    return a+b


问:
Search only children of a protractor webElementFinder using CSS
I have a protractor webElementFinder testElement. I want to match only its  div children (NOT grandchildren or any other further descendants) and thus testElement.find('div') will not work as it will find all descendant divs.

If protractor worked like jQuery (which would make sense since Angular is smart enough to use jQuery if its present and protractor is built with Angular in mind), I would just do testElement.find(' > div') which would work despite the find argument not being a valid CSS selector by itself; however because protractor just uses built in Element functions, that CSS selector is not valid by itself, and protractor throws an error.

I could go this route Angular JS, Protractor locator, get direct children of element since xpath natively lets you look at children, but I'd much rather use CSS than xpath.

答:
There is no direct and easy way to have a direct parent-child locator from the current element. A common way to solve it is to use the ./ XPath expression, but there is also this "hack" that uses locator():

```<code>testElement.$(testElement.locator().value + ' > div');
</code>```

Body:
There is no direct and easy way to have a direct parent-child locator from the current element. A common way to solve it is to use the ./ XPath expression, but there is also this "hack" that uses locator():

testElement.$(testElement.locator().value + ' > div');


问:
Is it possible to have a stateless server with token based authentication that is not vulnerable to replay attacks?
Currently I have a server that makes use of JSON Web Tokens in order to manage user authentication.

When a user submits a valid authentication request, they receive a JWT which contains information such as their user ID that allows the server to process authentication sensitive requests.

The plain text body of the JWT will take a form similar to:

```<code>{
    "UserID":"100",
    "Expires":"(expiryDate)",
    "IssuedBy":"ServerOne"
}
</code>```

However, as you could quite correctly point out, this does not afford us any way to validate that the agent presenting the access token is in fact the user who it was originally issued to.

As such, if someone were able to obtain the JWT, then assuming it has not expired they would be able to assume the user's identity and gain unauthorised access.

A stateless server is a must for the current project, so I would struggle to use a solution which involves the server keeping track of logged in users.

Is it possible to achieve security using Tokens in this manner?

I've done a bit of reading on the topic, and I remember someone suggesting to use something like the "X-Forwarded-For" header and placing the user's IP in the token then comparing the two, but that has it's own drawbacks.

答:
There are a couple of specs in the OAuth 2.0 / JWT space right now, which try to address this problem. Take a look at RFC 7800 and this draft.

There are several commercial Authorization Servers / Identity Providers out there which already support RFC 7800 and a couple of open source implementations as well.

Body:
Currently I have a server that makes use of JSON Web Tokens in order to manage user authentication.

When a user submits a valid authentication request, they receive a JWT which contains information such as their user ID that allows the server to process authentication sensitive requests.

The plain text body of the JWT will take a form similar to:

{
    "UserID":"100",
    "Expires":"(expiryDate)",
    "IssuedBy":"ServerOne"
}

However, as you could quite correctly point out, this does not afford us any way to validate that the agent presenting the access token is in fact the user who it was originally issued to.

As such, if someone were able to obtain the JWT, then assuming it has not expired they would be able to assume the user's identity and gain unauthorised access.

A stateless server is a must for the current project, so I would struggle to use a solution which involves the server keeping track of logged in users.

Is it possible to achieve security using Tokens in this manner?

I've done a bit of reading on the topic, and I remember someone suggesting to use something like the "X-Forwarded-For" header and placing the user's IP in the token then comparing the two, but that has it's own drawbacks.


问:
Sort numbers then strings C#
I want to this list

```<code>A
B
C
111
11
123
1
42
5
</code>```

To be sorted

```<code>1
5
11
42
111
123
A
B
C
</code>```

By default, it sorts numbers like strings (So, it goes 1,11,111,123,42,5),
But I want to sort numbers like numbers, and than strings that are not numbers.

Is there clean solution to sort it like above?

It is a list of objects, and object has several properties, one of which is a this string.

答:
This will work for most use cases, but may have odd results if the string starts with control characters, string like "\tabc" will come before the integers:

```<code>list.OrderBy(x=>int.TryParse(x, out var dummy) ? dummy.ToString("D10") : x);
</code>```

or for versions of C# prior to 7:

```<code>list.OrderBy(x=> { int dummy; return int.TryParse(x, out dummy) ? dummy.ToString("D10") : x;} );
</code>```

Title: Sort numbers then strings C#

Body:
I want to this list

A
B
C
111
11
123
1
42
5

To be sorted

1
5
11
42
111
123
A
B
C

By default, it sorts numbers like strings (So, it goes 1,11,111,123,42,5),
But I want to sort numbers like numbers, and than strings that are not numbers.

Is there clean solution to sort it like above?

It is a list of objects, and object has several properties, one of which is a this string.

Body:
This will work for most use cases, but may have odd results if the string starts with control characters, string like "\tabc" will come before the integers:

list.OrderBy(x=>int.TryParse(x, out var dummy) ? dummy.ToString("D10") : x);

or for versions of C# prior to 7:

list.OrderBy(x=> { int dummy; return int.TryParse(x, out dummy) ? dummy.ToString("D10") : x;} );


问:
Subclasses with generics of subclasses
I have some issues with generics. I have a BaseObject with multiple sub-classes as well as a BaseContainer<T extends BaseObject> with sub-classes that correspond with BaseObject sub-classes.

```<code>public class TestClass extends BaseClass<BaseContainer<BaseObject>> {

    // method signature tied to BaseClass generic
    @Override
    private BaseContainer<BaseObject> createContainer() {
        BaseContainer<BaseObject> container;

        // example logic here to determine which container to use
        if (Math.random() < 0.5) {
            container = new Parent1Container(); // incompatible types
        } else {
            container = new Parent2Container(); // incompatible types
        }

        return container;
    }

    abstract static class BaseObject {}
    static class Parent1Object extends BaseObject {}
    static class Parent2Object extends BaseObject {}

    abstract static class BaseContainer<T extends BaseObject> {
        public abstract void foo(T object);
    }
    static class Parent1Container extends BaseContainer<Parent1Object> {
        public void foo(Parent1Object object) {}
    }
    static class Parent2Container extends BaseContainer<Parent2Object> {
        public void foo(Parent2Object object) {}
    }

}
</code>```

```<code>public class BaseClass<T extends BaseContainer> {
    public abstract T createContainer();
}
</code>```

I have a method that returns BaseContainer<BaseObject>. Unfortunately, instantiating sub-classes of BaseContainer results in incompatible types error.

I have tried adding casts to the container instantiation, but it leaves ugly unchecked warnings that make me feel like I'm just missing something. I'd like to avoid those and suppress warnings.

If possible, how can I re-write the any of the classes to make the createContainer() method work?

答:
As written here,

Neither List<Number> nor List<Integer> is a subtype of the other, even though Integer is a subtype of Number. So, any method that takes List<Number> as a parameter does not accept an argument of List<Integer>. If it did, it would be possible to insert a Number that is not an Integer into it, which violates type safety.

Since BaseClass is in a library and you cannot modify it, this case cannot be handled cleanly, i.e. as you expected.

Title: Subclasses with generics of subclasses

Body:
I have some issues with generics. I have a BaseObject with multiple sub-classes as well as a BaseContainer<T extends BaseObject> with sub-classes that correspond with BaseObject sub-classes.

public class TestClass extends BaseClass<BaseContainer<BaseObject>> {

    // method signature tied to BaseClass generic
    @Override
    private BaseContainer<BaseObject> createContainer() {
        BaseContainer<BaseObject> container;

        // example logic here to determine which container to use
        if (Math.random() < 0.5) {
            container = new Parent1Container(); // incompatible types
        } else {
            container = new Parent2Container(); // incompatible types
        }

        return container;
    }

    abstract static class BaseObject {}
    static class Parent1Object extends BaseObject {}
    static class Parent2Object extends BaseObject {}

    abstract static class BaseContainer<T extends BaseObject> {
        public abstract void foo(T object);
    }
    static class Parent1Container extends BaseContainer<Parent1Object> {
        public void foo(Parent1Object object) {}
    }
    static class Parent2Container extends BaseContainer<Parent2Object> {
        public void foo(Parent2Object object) {}
    }

}

public class BaseClass<T extends BaseContainer> {
    public abstract T createContainer();
}

I have a method that returns BaseContainer<BaseObject>. Unfortunately, instantiating sub-classes of BaseContainer results in incompatible types error.

I have tried adding casts to the container instantiation, but it leaves ugly unchecked warnings that make me feel like I'm just missing something. I'd like to avoid those and suppress warnings.

If possible, how can I re-write the any of the classes to make the createContainer() method work?


问:
NHibernate One-To-Many re-retrieve object problem
I have come across a weird problem concerning composite keys and one-to-many relationship.

I have the following Invoice class:

```<code>public class Invoice: AccountingBase<InvoiceItem>
{
    public virtual IList<InvoiceItem> InvoiceItems {.....}
}
</code>```

the class it inherits is (AccountingBase) is as follows:

```<code>public abstract class AccountingBase<TItemType>  : AccountingBase where TItemType : AccountingItemBase
{
    public virtual ObservableCollection<TItemType> Items { get; set; }

    public abstract void AddItem(TItemType item);
}
</code>```

And the bottom class is:

```<code>public abstract class AccountingBase
{
    public virtual Subsidiary Subsidiary {....}
    public virtual int ID{ ....}
}
</code>```

The Mapping for Invoice class is as follows:

```<code> <class name="Invoice" table="Invoice">
     <composite-id>
       <key-many-to-one class="Subsidiary" name="Subsidiary"/>
       <key-property name="ID" column="InvoiceID" />
     </composite-id>
     <bag name="InvoiceItems" table="InvoiceItem" inverse="true" lazy="false">
       <key>
         <column name="Subsidiary" />
         <column name="InvoiceID" />
       </key>
       <one-to-many class="InvoiceItem" />
     </bag>
 </class>
</code>```

Now when i retrieve a list of Invoices it works fine, including lazily loading each Items object. The problem i get is, when i select an invoice to edit. I open a new session, and i try retrieve the same invoice using the new session, but when it loads the invoice, it doesnt load the items, it retrieves them as blank, although when i run the generated SQL manually it runs perfectly fine. What could be the reason?

The code i am running to retrieve to get the new Invoice object in the new session using the old object is:

```<code>Invoice = Session.Get<Invoice>(invoice);
</code>```

When i debug, invoice is of Type Invoice, and also, invoice has 1 InvoiceItem in InvoiceItems collection, but the new instance in Invoice, all the fields are populated but the InvoiceItems is null. Is there anything i should know about Nhibernate that might cause this kind of error?

I have tried lazy="false".

答: Found the fix, i had to correctly implement Equality methods, in both Invoice class and Subsidiary class.</p>

Body:
I have come across a weird problem concerning composite keys and one-to-many relationship.

I have the following Invoice class:

public class Invoice: AccountingBase<InvoiceItem>
{
    public virtual IList<InvoiceItem> InvoiceItems {.....}
}

the class it inherits is (AccountingBase) is as follows:

public abstract class AccountingBase<TItemType>  : AccountingBase where TItemType : AccountingItemBase
{
    public virtual ObservableCollection<TItemType> Items { get; set; }

    public abstract void AddItem(TItemType item);
}

And the bottom class is:

public abstract class AccountingBase
{
    public virtual Subsidiary Subsidiary {....}
    public virtual int ID{ ....}
}

The Mapping for Invoice class is as follows:

 <class name="Invoice" table="Invoice">
     <composite-id>
       <key-many-to-one class="Subsidiary" name="Subsidiary"/>
       <key-property name="ID" column="InvoiceID" />
     </composite-id>
     <bag name="InvoiceItems" table="InvoiceItem" inverse="true" lazy="false">
       <key>
         <column name="Subsidiary" />
         <column name="InvoiceID" />
       </key>
       <one-to-many class="InvoiceItem" />
     </bag>
 </class>

Now when i retrieve a list of Invoices it works fine, including lazily loading each Items object. The problem i get is, when i select an invoice to edit. I open a new session, and i try retrieve the same invoice using the new session, but when it loads the invoice, it doesnt load the items, it retrieves them as blank, although when i run the generated SQL manually it runs perfectly fine. What could be the reason?

The code i am running to retrieve to get the new Invoice object in the new session using the old object is:

Invoice = Session.Get<Invoice>(invoice);

When i debug, invoice is of Type Invoice, and also, invoice has 1 InvoiceItem in InvoiceItems collection, but the new instance in Invoice, all the fields are populated but the InvoiceItems is null. Is there anything i should know about Nhibernate that might cause this kind of error?

I have tried lazy="false".


问:
What does the switch statement in this RxJS example do?
I don't understand what the following documentation means in this RxJS example. Can someone answer?

The outcome is that switched is essentially a timer that restarts
  on every click. The interval Observables from older clicks do not
  merge with the current interval Observable.

Here is the code:

```<code>var clicks = Rx.Observable.fromEvent(document, 'click');
// Each click event is mapped to an Observable that ticks every second
var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000));
var switched = higherOrder.switch();
// The outcome is that `switched` is essentially a timer that restarts
// on every click. The interval Observables from older clicks do not merge
// with the current interval Observable.
switched.subscribe(x => console.log(x));
</code>```

答:
The easiest model to understand for switch is autocomplete.

In the typical autocomplete scenario you will take input from a user, and call a service that returns a promise.   You then attach to the promise through .then() to update your UI.

```<code>function onChange(text: string) {
    this.request(url).then((data) => this.updateListBox(data))
}
</code>```

If the user enters text multiple times you'll call onChange each time.  The order of responses at that point is not guarnteed. The endpoint you're calling could very well return you responses out of order.  1, 3, 2.  So the user will see the second request they made, instead of the last request they made.

Now what switch does, is given an input observable, it only actively listens to the last observable emitted to it. For example...

```<code>this.onChange
   .map(text => Observable.fromPromise(this.request(text))
   .switch()
   .subscribe((data) => this.updateListBox(data));
</code>```

Each time a value comes in through onChange we will still make the request as per normal.  Once a second value emits from onChange we unsubscribe from the first observable (request 1).  And subscribe to the second observable (request 2).

So that once you update the UI, you only ever update with the latest set of data that you care about.

Body:
I don't understand what the following documentation means in this RxJS example. Can someone answer?

The outcome is that switched is essentially a timer that restarts
  on every click. The interval Observables from older clicks do not
  merge with the current interval Observable.

Here is the code:

var clicks = Rx.Observable.fromEvent(document, 'click');
// Each click event is mapped to an Observable that ticks every second
var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000));
var switched = higherOrder.switch();
// The outcome is that `switched` is essentially a timer that restarts
// on every click. The interval Observables from older clicks do not merge
// with the current interval Observable.
switched.subscribe(x => console.log(x));

Body:
The easiest model to understand for switch is autocomplete.

In the typical autocomplete scenario you will take input from a user, and call a service that returns a promise.   You then attach to the promise through .then() to update your UI.

function onChange(text: string) {
    this.request(url).then((data) => this.updateListBox(data))
}

If the user enters text multiple times you'll call onChange each time.  The order of responses at that point is not guarnteed. The endpoint you're calling could very well return you responses out of order.  1, 3, 2.  So the user will see the second request they made, instead of the last request they made.

Now what switch does, is given an input observable, it only actively listens to the last observable emitted to it. For example...

this.onChange
   .map(text => Observable.fromPromise(this.request(text))
   .switch()
   .subscribe((data) => this.updateListBox(data));

Each time a value comes in through onChange we will still make the request as per normal.  Once a second value emits from onChange we unsubscribe from the first observable (request 1).  And subscribe to the second observable (request 2).

So that once you update the UI, you only ever update with the latest set of data that you care about.


问:
Choosing the closest authority match for a multi-tenant app
We have a multi-tenant app which has been passing in "login.windows.net/common" when creating a new AuthenticationContext.  We missed the memo a while back that this had been deprecated in favor of "login.microsoftonline.com/common".  The impetus for switching now is that we have customers for whom that also won't work (e.g. because they're behind "login.microsoftonline.de").

We understand the correct approach is to first query "login.microsoftonline.com/tenant-domain-name/.well-known/openid-configuration", and use the endpoints we get back, instead of hardcoding login.microsoftonline.com.  What we're wondering is which of the fields we get back should be used.

I haven’t been able to find an authoritative (no pun intended) source for what the authority string should be.  Some places I’ve checked:

The documentation for AuthenticationContext says authority is, “Address of the authority to issue token.”

The developer’s guide for integrating AAD with Windows Store apps references creating AuthenticationContext with an authority, doesn’t say what authority should be.

The sample code for a Windows Store app uses "login.microsoftonline.com/tenant".

The AAD docs say for multi-tenant apps, use "login.microsoftonline.com/common".

Other answers here on StackOverflow have ranged covered those, specific paths (like "/oauth2/token"), etc.

So, after we query the discovery service, what do we then use for authority?

authorization_endpoint?

token_endpoint?

map tenant_region_scope to the right login.microsoftonline.com variation, and append "/common"? or "/tenant"?

Thank you.

答:
The https://login.microsoftonline.com/{common-or-tenant}/.well-known/openid-configuration metadata document can be used to determine the authority URLs to log a user in (it's part of the OpenID Connect standard).  Typically developers will use an OpenID Connect library or package to consume this metadata document and construct requests for them.  But if you're intent on consuming it yourself, I recommend reading the OpenID Connect Discovery spec.  It will instruct you that the authorization_endpoint is the URL to use to log users in.

Re: common vs. tenant.  The common endpoint can be used when you don't know which company/tenant/directory the user belongs to.  This is the most generic case.  If you somehow know which tenant the user belongs to out of band (they work for your company, they told you in some form, etc) you can instead use the tenanted endpoint. This will direct the user directly to their company's login page, instead of performing a discovery step which locates which tenant the user belongs to.


问:
Application of 2D ArrayList in Java
I want to create a list of usernames, and then each username would correlate to a password. The purpose is when a username is submitted, I would iterate through the username list to look for a match. If matched, I would then ask for the password of that username. I thought of using a 2D ArrayList of String, but do not think it's possible to ask for a username and then check for the password that way. Would the only possible (and not too advanced) way to do this be to create 2 separate ArrayList? If so, how do I make sure that for each name from username list, there is only one correct password in the password list?

Note: I am just recently introduced to Java.

答:
A map from java.util would do what you're looking for much better, you'd be able to do stuff like this:

```<code>Map<String, String> namesToPasswords = new HashMap<>();
namesToPasswords.put("user1", "password");
</code>```

Then namesToPasswords.get("user1") would return "password" which you can do what you please with.

Not only is this a lot easier to think about than cross-referencing arrays, it's a lot faster too. Iterating over an array of length n to find a match is O(n), while looking up an entry in a HashMap is O(1).

Documentation

Title: Application of 2D ArrayList in Java

Body:
A map from java.util would do what you're looking for much better, you'd be able to do stuff like this:

Map<String, String> namesToPasswords = new HashMap<>();
namesToPasswords.put("user1", "password");

Then namesToPasswords.get("user1") would return "password" which you can do what you please with.

Not only is this a lot easier to think about than cross-referencing arrays, it's a lot faster too. Iterating over an array of length n to find a match is O(n), while looking up an entry in a HashMap is O(1).

Documentation


问:
502 error when calling an external web service from azure web service
I have a web service hosted on Azure from which I need to make a request to an external web service.  When I try it on localhost it gets an expected response but from Azure I get 502 - Web server received an invalid response while acting as a gateway or proxy server. -- There is a problem with the page you are looking for, and it cannot be displayed. When the Web server (while acting as a gateway or proxy) contacted the upstream content server, it received an invalid response from the content server.
Is this a configuration problem on Azure to allow receipt of incoming responses or is it a problem with the way I am sending requests and receiving responses?

答: I think the answer to this problem is here: Azure application gateway throws 502 when application sends 401  Looks like any error returned >399 causes Azure to shut down the response and send the 502.  </p>


问:
Connecting an Already Opened Project to Perforce
Is there a way to tell P4VS that the currently opened solution corresponds to a given checkout?

My problem stems from the fact that I'm using a 3rd party tool to open Visual Studio and attach it to a process. But once it's open I want to be able to use the P4VS plugin.

Is that doable, or do i just have to work without P4VS :(

答:
Yeah you can do this, you'll just need to use the "P4 Connection" Toolbar:

You can enable this by right clicking on vacant toolbar area or a toolbar handle in Visual Studio, and checking it.

Once you have the toolbar just log in and supply your current checkout.

If you're going to be doing this a lot it may also be helpful to you to select: "Connect to the server using my most recent" in the "Perforce - Connections" Options so you don't have to keep logging in:


问:
Install Python Package From Private Bitbucket Repo
I created a Python 3.5 package for work, which is in a private Bitbucket repo and I can easily pull the code and do a "python .\setup.py install" to have it install, but I want to try to eliminate the step of having to pull the code and have multiple copies on my machine and at the same time make it easier for my coworkers to install/update the package. Is it possible to use git bash or cmd (we are all on Windows) to install the package and ask for credentials in the process?</p>

答:
You can use the https option listed in pip_install.
https://pip.pypa.io/en/stable/reference/pip_install/#git

Sample Code:

```<code>pip install git+https://USER_NAME@GIT_URL/PATH_TO_YOUR_REPO.git
</code>```

You can use the url Bitbucket gives you when you request the clone url. Just remember to add the git+ to it.

Body:
You can use the https option listed in pip_install.
https://pip.pypa.io/en/stable/reference/pip_install/#git

Sample Code:

pip install git+https://USER_NAME@GIT_URL/PATH_TO_YOUR_REPO.git

You can use the url Bitbucket gives you when you request the clone url. Just remember to add the git+ to it.


问:
How to sort .xml file and merge sections based on ID entry
I have an .xml file containing two sets of information that I want to match up to each other based on their ID value (1.2). For example, this snippet.

```<code><rule id="1.2">
      <checker id="checker.id">
         <description locale="en">description</description>
      </checker>
</rule>

<rule id="1.2">
        <checker>
            <category locale="en">Advisory</category>
            <decidable locale="en">Yes</decidable>
        </checker>
</rule>
</code>```

I have a .xsl for each rule, add the values to a table entry

```<code><row>
    <entry>
        <xsl:value-of select="@id"/>
    </entry>
    <entry>
        <xsl:for-each select="checker">
        <xsl:value-of select="category[@locale=$locale]"/>
        </xsl:for-each>
    </entry>
    <entry>
        <xsl:for-each select="checker">
        <xsl:value-of select="decidable[@locale=$locale]"/>
        </xsl:for-each>
    </entry>
    <entry>
        <xsl:for-each select="checker">
        <p>
        <codeph>
        <xsl:value-of select="@id"/></codeph><xsl:text> </xsl:text>
        <xsl:value-of select="description[@locale=$locale]"/>
        </p>
        </xsl:for-each>
    </entry>
</row>
</code>```

The current result gives me this, but it has created two separate rows even though the ID is the same. What can I do to have the information with the same ID be in the same row?

```<code><row>
    <entry>1.2</entry>
    <entry>Advisory</entry>
    <entry>Yes</entry>
    <entry>
    <p>
    <codeph/></p>
    </entry>
</row>
<row>
    <entry>1.2</entry>
    <entry/>
    <entry/>
    <entry>
    <p>
    <codeph>checker.id</codeph>description</p>
    </entry>
</row>
</code>```

Desired outcome:

```<code><row>
    <entry>1.2</entry>
    <entry>Advisory</entry>
    <entry>Yes</entry>
    <entry>
    <p><codeph>checker.id</codeph>description</p>
    </entry>
</row>
</code>```

答:
This is a variant of the so-called Muenchian grouping.

The following XSLT chooses the first match of the sorted <xsl:key> of all <rule>s and then compiles the desired outcome by matching all <rule>s with the same @id by applying the // operator with a predicate.

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:key name="kSorted" match="rule" use="@id" />
  <xsl:variable name="locale" select="'en'" />

    <xsl:template match="/root">
      <xsl:apply-templates select="rule[generate-id() = generate-id(key('kSorted',@id)[1])]">
        <xsl:sort select="@id" />
      </xsl:apply-templates>
    </xsl:template>

    <xsl:template match="rule">
      <xsl:variable name="thisID" select="@id" />
      <row>
        <entry><xsl:value-of select="@id"/></entry>
        <entry><xsl:value-of select="//rule[@id = $thisID]//category[@locale=$locale]"/></entry>
        <entry><xsl:value-of select="//rule[@id = $thisID]//decidable[@locale=$locale]"/></entry>
        <entry>
          <p>
            <codeph><xsl:value-of select="checker/@id"/></codeph><xsl:text> </xsl:text>
            <xsl:value-of select="checker/*[@locale=$locale][1]"/>
          </p>
        </entry>
      </row>
    </xsl:template>

</xsl:stylesheet>
</code>```

Body:
I have an .xml file containing two sets of information that I want to match up to each other based on their ID value (1.2). For example, this snippet.

<rule id="1.2">
      <checker id="checker.id">
         <description locale="en">description</description>
      </checker>
</rule>

<rule id="1.2">
        <checker>
            <category locale="en">Advisory</category>
            <decidable locale="en">Yes</decidable>
        </checker>
</rule>

I have a .xsl for each rule, add the values to a table entry

<row>
    <entry>
        <xsl:value-of select="@id"/>
    </entry>
    <entry>
        <xsl:for-each select="checker">
        <xsl:value-of select="category[@locale=$locale]"/>
        </xsl:for-each>
    </entry>
    <entry>
        <xsl:for-each select="checker">
        <xsl:value-of select="decidable[@locale=$locale]"/>
        </xsl:for-each>
    </entry>
    <entry>
        <xsl:for-each select="checker">

        <codeph>
        <xsl:value-of select="@id"/></codeph><xsl:text> </xsl:text>
        <xsl:value-of select="description[@locale=$locale]"/>

        </xsl:for-each>
    </entry>
</row>

The current result gives me this, but it has created two separate rows even though the ID is the same. What can I do to have the information with the same ID be in the same row?

<row>
    <entry>1.2</entry>
    <entry>Advisory</entry>
    <entry>Yes</entry>
    <entry>

    <codeph/>

    </entry>
</row>
<row>
    <entry>1.2</entry>
    <entry/>
    <entry/>
    <entry>

    <codeph>checker.id</codeph>description

    </entry>
</row>

Desired outcome:

<row>
    <entry>1.2</entry>
    <entry>Advisory</entry>
    <entry>Yes</entry>
    <entry>

<codeph>checker.id</codeph>description

    </entry>
</row>

Body:
This is a variant of the so-called Muenchian grouping.

The following XSLT chooses the first match of the sorted <xsl:key> of all <rule>s and then compiles the desired outcome by matching all <rule>s with the same @id by applying the // operator with a predicate.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:key name="kSorted" match="rule" use="@id" />
  <xsl:variable name="locale" select="'en'" />

    <xsl:template match="/root">
      <xsl:apply-templates select="rule[generate-id() = generate-id(key('kSorted',@id)[1])]">
        <xsl:sort select="@id" />
      </xsl:apply-templates>
    </xsl:template>

    <xsl:template match="rule">
      <xsl:variable name="thisID" select="@id" />
      <row>
        <entry><xsl:value-of select="@id"/></entry>
        <entry><xsl:value-of select="//rule[@id = $thisID]//category[@locale=$locale]"/></entry>
        <entry><xsl:value-of select="//rule[@id = $thisID]//decidable[@locale=$locale]"/></entry>
        <entry>
          <p>
            <codeph><xsl:value-of select="checker/@id"/></codeph><xsl:text>&#160;</xsl:text>
            <xsl:value-of select="checker/*[@locale=$locale][1]"/>
          </p>
        </entry>
      </row>
    </xsl:template>

</xsl:stylesheet>


问:
Formatting date in odoo email template
In odoo 9 i need to format the date_invoice in %d/%m/%Y inside email template:

```<code>Invoice date: ${object.date_invoice}
</code>```

The code above return 2017-03-31 but it is in wrong locale.

How i can format to get 31/03/2017 ?

答:
Qweb has a format_tz() function here is an example

${format_tz(object.write_date, tz='UTC', format='%d/%m/%Y')}

Now I think this function may only work on a datetime but you could probably add a new field to the model which is calculated from the date field you have and call it a day.

You can find a usage here event/data/email_template_data.xml

Title: Formatting date in odoo email template

Body:
In odoo 9 i need to format the date_invoice in %d/%m/%Y inside email template:

Invoice date: ${object.date_invoice}

The code above return 2017-03-31 but it is in wrong locale.

How i can format to get 31/03/2017 ?


答:
I wrote this IComparer implementation a few months back to handle something like this.  I think it will do what you want by default, though it is built to handle more complex cases where number/letter groups are separated by delimiters that also need to be sorted atomically.  You should be able to adjust it to your needs.

```<code>public class SemanticComparer : IComparer<string>
{
    private static Regex _splitter = new Regex("\\W+");

    public int Compare(string x, string y)
    {
        string[] partsX = _splitter.Split(x);
        string[] partsY = _splitter.Split(y);

        int shortest = Math.Min(partsX.Length, partsY.Length);

        for (int index = 0; index < shortest; index++)
        {
            int intX, intY;
            int result;

            if (int.TryParse(partsX[index], out intX) && int.TryParse(partsY[index], out intY))
            {
                result = intX.CompareTo(intY);
            }
            else
            {
                result = string.Compare(partsX[index], partsY[index], StringComparison.Ordinal);
            }

            if (result != 0)
            {
                return result;
            }
        }

        return 0;
    }
}
</code>```

You can sort your list with it like this:

```<code>MyList.Sort(new SemanticComparer());
</code>```

Title: Sort numbers then strings C#

Body:
I wrote this IComparer implementation a few months back to handle something like this.  I think it will do what you want by default, though it is built to handle more complex cases where number/letter groups are separated by delimiters that also need to be sorted atomically.  You should be able to adjust it to your needs.

public class SemanticComparer : IComparer<string>
{
    private static Regex _splitter = new Regex("\\W+");

    public int Compare(string x, string y)
    {
        string[] partsX = _splitter.Split(x);
        string[] partsY = _splitter.Split(y);

        int shortest = Math.Min(partsX.Length, partsY.Length);

        for (int index = 0; index < shortest; index++)
        {
            int intX, intY;
            int result;

            if (int.TryParse(partsX[index], out intX) && int.TryParse(partsY[index], out intY))
            {
                result = intX.CompareTo(intY);
            }
            else
            {
                result = string.Compare(partsX[index], partsY[index], StringComparison.Ordinal);
            }

            if (result != 0)
            {
                return result;
            }
        }

        return 0;
    }
}

You can sort your list with it like this:

MyList.Sort(new SemanticComparer());


问:
MAMP OS X Conflict with Built in Apache with Virtualhostx
I am a newbie and I set up Mamp and virtualhostx on my IMAC and it works fine except when I restart the server in virtualhostx it tells me multiple servers are running and it could cause conflicts. I can go into settings and turn off Apache but it starts again when I restart with virtualhostx.

I used the setup suggested in http://seansperte.com/entry/Setting_Up_a_Killer_Local_Web_Development_Environment_on_a_Mac_with_MAMP_an/

and set my Apache and Mysql ports to to 80 and 3306 respectively

How can I keep the built in Apache turned off?

答: You can disable it in System Preferences > Sharing. Remove the check next to "Web Sharing".</p>


问:
AtomicInteger and Math.max
I was trying to get the maximum value of a calculatedValue in a cycle and I wanted it to be thread safe. So I decided to use AtomicInteger and Math.max, but I can't find a solution so that the operation can be considered atomic.

```<code>AtomicInteger value = new AtomicInteger(0);

// Having some cycle here... {
    Integer anotherCalculatedValue = ...;
    value.set(Math.max(value.get(), anotherCalculatedValue));
}

return value.get()
</code>```

The problem with that is that I make two operations, therefore is not threadsafe. How can I solve this? The only way is to use synchronized?

答:
If Java 8 is available you can use:

```<code>AtomicInteger value = new AtomicInteger(0);
Integer anotherCalculatedValue = ...;
value.getAndAccumulate(anotherCalculatedValue, Math::max);
</code>```

Which from the specification will:

Atomically updates the current value with the results of
    applying the given function to the current and given values,
    returning the previous value.

Title: AtomicInteger and Math.max

Body:
I was trying to get the maximum value of a calculatedValue in a cycle and I wanted it to be thread safe. So I decided to use AtomicInteger and Math.max, but I can't find a solution so that the operation can be considered atomic.

AtomicInteger value = new AtomicInteger(0);

// Having some cycle here... {
    Integer anotherCalculatedValue = ...;
    value.set(Math.max(value.get(), anotherCalculatedValue));
}

return value.get()

The problem with that is that I make two operations, therefore is not threadsafe. How can I solve this? The only way is to use synchronized?

Body:
If Java 8 is available you can use:

AtomicInteger value = new AtomicInteger(0);
Integer anotherCalculatedValue = ...;
value.getAndAccumulate(anotherCalculatedValue, Math::max);

Which from the specification will:

Atomically updates the current value with the results of
    applying the given function to the current and given values,
    returning the previous value.


问:
Out of Memory at 26 MB in C#
I have a draw function which draws lines that are gradient from one end to the other. I'm only drawing about forty or so lines each time. Each time, I generate a new set of Linear gradient brushes. The old set is a local variable with no ties to any object. My program only uses about 26 MB of memory. It'll work fine for several minutes before randomly throwing an out of memory exception when allocating a new linear gradient brush. As you can see, memory was at 25.7 MB when the exception occurred.

Minimal Example Code (will throw the memory exception):

Note: The following code only triggers the exception if it is used in a redraw for the graphics context, that context is resized, and even then, only after several minutes.

```<code>class DrawImpl
{
    private static Pen routePen = new Pen(Color.Black);
    public static void Draw(Graphics g, Point[] ps)
    {
        g.SmoothingMode = SmoothingMode.HighQuality;
        if (ps != null && ps.Length > 0)
        {
            for (int i = 0; i < ps.Length; ++i)
            {
                int prevI = (((i - 1) % ps.Length) + ps.Length) % ps.Length;
                using (LinearGradientBrush routeBrush = new LinearGradientBrush(ps[prevI], ps[i], Color.Red, Color.Blue))
                {
                    routePen.Brush = routeBrush;
                    g.DrawLine(routePen, ps[prevI], ps[i]);
                }
            }
            GC.Collect();
        }
    }
}
</code>```

答:
Unfortunately, System.Drawing can throw OutOfMemory exception even when the error has nothing to do with memory.

I have seen people encounter that exception in the following scenarios:
* Using a LinearGradientBrush to fill a rectangle with dimension(s) of 0
* Trying to load a corrupted image file

These exceptions come from GDI+ so I would suggest to look for inner exceptions and logs.

Title: Out of Memory at 26 MB in C#

Body:
I have a draw function which draws lines that are gradient from one end to the other. I'm only drawing about forty or so lines each time. Each time, I generate a new set of Linear gradient brushes. The old set is a local variable with no ties to any object. My program only uses about 26 MB of memory. It'll work fine for several minutes before randomly throwing an out of memory exception when allocating a new linear gradient brush. As you can see, memory was at 25.7 MB when the exception occurred.

Minimal Example Code (will throw the memory exception):

Note: The following code only triggers the exception if it is used in a redraw for the graphics context, that context is resized, and even then, only after several minutes.

class DrawImpl
{
    private static Pen routePen = new Pen(Color.Black);
    public static void Draw(Graphics g, Point[] ps)
    {
        g.SmoothingMode = SmoothingMode.HighQuality;
        if (ps != null && ps.Length > 0)
        {
            for (int i = 0; i < ps.Length; ++i)
            {
                int prevI = (((i - 1) % ps.Length) + ps.Length) % ps.Length;
                using (LinearGradientBrush routeBrush = new LinearGradientBrush(ps[prevI], ps[i], Color.Red, Color.Blue))
                {
                    routePen.Brush = routeBrush;
                    g.DrawLine(routePen, ps[prevI], ps[i]);
                }
            }
            GC.Collect();
        }
    }
}


问:
Pulling Random Image From Directory with PHP
I'm trying to produce a random image on my 404 pages from a directory in my assets.  I found another thread using the code I'm using, but I have had zero luck getting this to work.

```<code><h1>404 Page not Found</h1>
            <?php
                $imageDir = 'https://globalassets.provo.edu/image/404/';
                $images = glob($imageDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
                $randomImage = $images[array_rand($images)];

            ?>
            <img src="<?php echo($randomImage); ?>" alt="" />
</code>```

Any ideas?  If I try to print just $images it appears to give me a empty Array.

答:
AH! Thanks for pointing me in the right direction.

I moved the 404 images folder into the same directory as my theme and everything is working now

the updated code looks like

```<code><h1>404 Page not Found</h1>
            <?php
                $imageDir = '404/';
                $images = glob($imageDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
                $randomImage = $images[array_rand($images)];

            ?>
            <img src="<?php echo($randomImage);  ?>" alt="" />
</code>```

Body:
I'm trying to produce a random image on my 404 pages from a directory in my assets.  I found another thread using the code I'm using, but I have had zero luck getting this to work.

404 Page not Found

            <?php
                $imageDir = 'https://globalassets.provo.edu/image/404/';
                $images = glob($imageDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
                $randomImage = $images[array_rand($images)];

            ?>
            <img src="<?php echo($randomImage); ?>" alt="" />

Any ideas?  If I try to print just $images it appears to give me a empty Array.

Body:
AH! Thanks for pointing me in the right direction.

I moved the 404 images folder into the same directory as my theme and everything is working now

the updated code looks like

<h1>404 Page not Found</h1>
            <?php
                $imageDir = '404/';
                $images = glob($imageDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
                $randomImage = $images[array_rand($images)];

            ?>
            <img src="<?php echo($randomImage);  ?>" alt="" />


问:
Eigen::SparseTriangularView
I am trying to switch some code from Eigen 3.2.10 to 3.3. I am running into compile errors with this method declaration

```<code>/// \brief Returns template expression for the lower triangular part of A.
Eigen::SparseTriangularView < SystemMatrixType, Eigen::Lower >
    getLowerTriangular() const;
</code>```

producing error C2143: syntax error : missing ';' before '<'.

It looks like SparseTriangularView has been renamed or replaced. What should SparseTriangularView or this whole declaration be replaced by?

答: Just use TriangularView < SystemMatrixType, Eigen::Lower >. Triangular and Selfadjoint views of dense and sparse expressions have been unified in 3.3.

Title: Eigen::SparseTriangularView

Body:
I am trying to switch some code from Eigen 3.2.10 to 3.3. I am running into compile errors with this method declaration

/// \brief Returns template expression for the lower triangular part of A.
Eigen::SparseTriangularView < SystemMatrixType, Eigen::Lower >
    getLowerTriangular() const;

producing error C2143: syntax error : missing ';' before '<'.

It looks like SparseTriangularView has been renamed or replaced. What should SparseTriangularView or this whole declaration be replaced by?


问:
ssrs user typing in multiple values in a parameter or leaving it blank
I am creating a report in SSRS and have a parameter for the end users to search for an account number. Within the report the parameter is set to null by default to show all accounts. When the parameter is not null the user should be able to type in a single account or multiple accounts separated by commas. My problem is when I try to type in multiple accounts I get this error:

"An expression of non-boolean type specified in a context where a condition is expected, near ','."

Here is my sql query:

```<code>SELECT * FROM test_db WHERE (AccountNumber IN (@Account)) OR (@Account IS NULL)
</code>```

The code on the parameter for @Account is

```<code>=IIF(IsNothing(Parameters!Account.Value),Parameters!Account.Value,Split(Parameters!Account.Value,","))
</code>```

答:
You don't need to do anything with it. If you make the @Account parameter multi-value, you can simply type each entry followed by [Enter], no commas, just your required value, one on each row of the parameter drop down.

Then your original query will work, SSRS will automatically convert the multi-value list into a comma separated list and inject it into your SQL. If this doesn't make sense, let me know and I'll put a complete answer with some images. You may need to change you query to

```<code>SELECT *
    FROM test_db
    WHERE AccountNumber IN (@Account)
        OR ISNULL(@Account, '' ) = ''
</code>```

This will take care of blanks too. So blanks/Null should return everything

Body:
I am creating a report in SSRS and have a parameter for the end users to search for an account number. Within the report the parameter is set to null by default to show all accounts. When the parameter is not null the user should be able to type in a single account or multiple accounts separated by commas. My problem is when I try to type in multiple accounts I get this error:

"An expression of non-boolean type specified in a context where a condition is expected, near ','."

Here is my sql query:

SELECT * FROM test_db WHERE (AccountNumber IN (@Account)) OR (@Account IS NULL)

The code on the parameter for @Account is

=IIF(IsNothing(Parameters!Account.Value),Parameters!Account.Value,Split(Parameters!Account.Value,","))

Body:
You don't need to do anything with it. If you make the @Account parameter multi-value, you can simply type each entry followed by [Enter], no commas, just your required value, one on each row of the parameter drop down.

Then your original query will work, SSRS will automatically convert the multi-value list into a comma separated list and inject it into your SQL. If this doesn't make sense, let me know and I'll put a complete answer with some images. You may need to change you query to

SELECT *
    FROM test_db
    WHERE AccountNumber IN (@Account)
        OR ISNULL(@Account, '' ) = ''

This will take care of blanks too. So blanks/Null should return everything


问:
Differences between "empty project" and "external build system" in XCode
I am new in the programming world, and use XCode's IDE and compiler (GCC?) to program. But I have a questions, what is the differences between "empty project" and "external build system" in XCode?

It's sounds like a stupid question, but why not ask? :)

答: The External Build System project template already contains a target for, you guessed it!, an external build system; the empty project is empty, i.e. has no targets at all. Not that big a difference, there is a template for an external target, so it's just a few clicks away.</p>