问:
how to make a git alias with arguments in windwos
I have to use this command frequently

git difftool head head~2 -- Myefile.cpp.

It is a large command to type all the time. I would like to make an alias of this command with head~n where n is a variable. I want to type

git myfilediff n

where n is an integer number.

How can I do it in windows 10?

答:
A quick and dirty solution, to define a bash function in ~/.bashrc if you are using Ubuntu or git-bash-for-windows:

```<code>function mfd() {
    git diff HEAD HEAD~${1} -- Myfile.cpp
}
</code>```

source ~/.bashrc and then mfd 2 is equivalent to git diff HEAD HEAD~2 -- Myfile.cpp.

Body:
A quick and dirty solution, to define a bash function in ~/.bashrc if you are using Ubuntu or git-bash-for-windows:

function mfd() {
    git diff HEAD HEAD~${1} -- Myfile.cpp
}

source ~/.bashrc and then mfd 2 is equivalent to git diff HEAD HEAD~2 -- Myfile.cpp.


来源: stackexchange

问:
How to pass a php variable from hidden input value to a php script?
I have this form INSIDE a table :

```<code>while($row=mysqli_fetch_array($result)){
    echo "<tr>";
        echo "<td>".$row['first_name'] . "</td>";
        echo "<td>" . $row['last_name'] . "</td>";
        <td>
            <form action="send_notification.php" method="POST">
                <input type="hidden" name="id" value="<?php echo $row['first_name']; ?>">
                <input type="submit" name="submit" value="request">
            </form>
       </td>
</code>```

Next to each row I have a button called "request" if I click on it I want
to pass the php variable $row['first_name'] to another PHP script .

How can I do that?
I tried to do this in the php file send_notification.php :

```<code><?php
session_start();
require("connect.php");

$id=$_GET['first_name'];

echo $id;
?>
</code>```

But it gave me this error:

Notice: Undefined index: first_name in path/send_notification.php on line 5

UPDATE ONE:

I change $_GET['first_name'] to $_POST['id'] , the output gave no error but it was a blank page. Should't it echo the $id?

答:
Change your hidden input name replace id to first_name.</p>

```<code>while($row=mysqli_fetch_array($result)){
echo "<tr>";

 echo "<td>".$row['first_name'] . "</td>";
 echo "<td>" . $row['last_name'] . "</td>";
     <td>
                    <form action="send_notification.php" method="POST">
                        <input type="hidden" name="first_name" value="<?php echo $row['first_name']; ?>">
                        <input type="submit" name="submit" value="request">
                    </form>
                </td>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this form INSIDE a table :

while($row=mysqli_fetch_array($result)){
    echo "
";
        echo "".$row['first_name'] . "	";
        echo "" . $row['last_name'] . "	";

            <form action="send_notification.php" method="POST">
                <input type="hidden" name="id" value="<?php echo $row['first_name']; ?>">
                <input type="submit" name="submit" value="request">
            </form>

Next to each row I have a button called "request" if I click on it I want
to pass the php variable $row['first_name'] to another PHP script .

How can I do that?
I tried to do this in the php file send_notification.php :

<?php
session_start();
require("connect.php");

$id=$_GET['first_name'];

echo $id;
?>

But it gave me this error:

Notice: Undefined index: first_name in path/send_notification.php on line 5

UPDATE ONE:

I change $_GET['first_name'] to $_POST['id'] , the output gave no error but it was a blank page. Should't it echo the $id?

Body:
Change your hidden input name replace id to first_name.

while($row=mysqli_fetch_array($result)){
echo "<tr>";

 echo "<td>".$row['first_name'] . "</td>";
 echo "<td>" . $row['last_name'] . "</td>";
     <td>
                    <form action="send_notification.php" method="POST">
                        <input type="hidden" name="first_name" value="<?php echo $row['first_name']; ?>">
                        <input type="submit" name="submit" value="request">
                    </form>
                </td>


问:
Is there a library for iPhone to work with HMAC-SHA-1 encoding
For all operation with Amazon services(S3, EC2, SimpleDB) You need to sign all resquest with HMAC-SHA-1 Signature(http://en.wikipedia.org/wiki/HMAC , http://docs.amazonwebservices.com/AWSFWS/latest/DeveloperGuide/index.html?SummaryOfAuthentication.html).

I'm working under asp.net backend and there is no problems. Problem is in the iPhone application. iPhone developer says that there is no way to use HMAC-SHA-1 encoding, and he have no rigths to implement his own algorithm. As programmer I cannot understand why there can be a problem.

So I want too know is iPhone developer right?

I've never coded for iPhone, so I don't even where to search such an information.

答:
Not for iPhone in particular, but the library libs3 provides a C API for accessing Amazon's S3 services.  It, or the FUSE s3fs component, may be good sources for extracting the routines needed to communicate with Amazon's Web Services.  As Objective-C is still C at its core, these routines should work just fine on the iPhone.

I know at least one developer who is using something similar within their iPhone application to communicate with S3 buckets.

OwnerDisplayName: AlfeG

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Brad Larson


问:
PHP - Is dynamic CSS/JS cached by browsers?
I'm including javascript generated by php for each page, like

Will this be cached by browser, so if you would go on another page some js might not work, because the previous page js is used?

If it is, how could I prevent caching?

答:
Will this be cached by browser

It depends on what caching headers your web server is configured to send for PHP scripts, if any. Usually, none are sent and no caching should take place.

You could use a tool like Firebug's "Net" tab to find out. If you want to make totally sure, see e.g. @fire's answer to this question to see how to disable caching completely from within PHP by sending the right headers.


问:
Nginx 301 Redirect not working correctly
I'm trying to redirect all traffic from one subfolder to another.  For example:

```<code>www.website.com/ve/12345.html
</code>```

to

```<code>www.website.com/es/12345.html
</code>```

My nginx command:

```<code>rewrite ^/(ve)/(.*)$ /es/$1 permanent;
</code>```

Does the following:

```<code>www.website.com/ve/12345.html
</code>```

to

```<code>www.website.com/es/ve
</code>```

How can I replace ve with es and keep the rest of the URL intact?

答:
The problem is that you've used $1 in your replacement, but $1 is just the characters 've', not the extra stuff at the end, which is in $2 in your version.

Best would be to remove the extra capture group so that you're not capturing things you're not using. This rule will do the redirect ok:

```<code>rewrite ^/ve/(.+)$ /es/$1 permanent;
</code>```

Body:
I'm trying to redirect all traffic from one subfolder to another.  For example:

www.website.com/ve/12345.html

to

www.website.com/es/12345.html

My nginx command:

rewrite ^/(ve)/(.*)$ /es/$1 permanent;

Does the following:

www.website.com/ve/12345.html

to

www.website.com/es/ve

How can I replace ve with es and keep the rest of the URL intact?

Body:
The problem is that you've used $1 in your replacement, but $1 is just the characters 've', not the extra stuff at the end, which is in $2 in your version.

Best would be to remove the extra capture group so that you're not capturing things you're not using. This rule will do the redirect ok:

rewrite ^/ve/(.+)$ /es/$1 permanent;


问:
Set color of text in status bar it is not working (swift 3 - iOS 10)
My status bar is black and I'm trying to set as white, so I did what I found in some questions here and put this on my AppDelegate...

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    //Status bar color
    UIApplication.shared.statusBarStyle = .lightContent

    return true
}
</code>```

There is no error in my console, nothing about this. The status bar text is still black. What could be causing this? There is another way to do that in swift 3.0?

答:
Here is Apple Guidelines/Instruction about status bar change. Only Dark & light (while & black) are allowed in status bar.

Here is - How to change status bar style:

If you want to set status bar style, application level then set UIViewControllerBasedStatusBarAppearance to NO in your `.plist' file.

if you wan to set status bar style, at view controller level then follow these steps:

Set the UIViewControllerBasedStatusBarAppearance to YES in the .plist file, if you need to set status bar style at UIViewController level only.

In the viewDidLoad add function - setNeedsStatusBarAppearanceUpdate

override preferredStatusBarStyle in your view controller.

-

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    self.setNeedsStatusBarAppearanceUpdate()
}

override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}
</code>```

Body:
My status bar is black and I'm trying to set as white, so I did what I found in some questions here and put this on my AppDelegate...

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    //Status bar color
    UIApplication.shared.statusBarStyle = .lightContent

    return true
}

There is no error in my console, nothing about this. The status bar text is still black. What could be causing this? There is another way to do that in swift 3.0?

Body:
Here is Apple Guidelines/Instruction about status bar change. Only Dark & light (while & black) are allowed in status bar.

Here is - How to change status bar style:

If you want to set status bar style, application level then set UIViewControllerBasedStatusBarAppearance to NO in your `.plist' file.

if you wan to set status bar style, at view controller level then follow these steps:

Set the UIViewControllerBasedStatusBarAppearance to YES in the .plist file, if you need to set status bar style at UIViewController level only.

In the viewDidLoad add function - setNeedsStatusBarAppearanceUpdate

override preferredStatusBarStyle in your view controller.

-

override func viewDidLoad() {
    super.viewDidLoad()
    self.setNeedsStatusBarAppearanceUpdate()
}

override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}


问:
Table with position: fixed doesn't scroll with overflow: scroll
I have two tables: the first is a header, the second contains data. I want to see the header when I scroll down, so its table has position: fixed. The tables can be too large to be shown on the screen at once, so I wrapped them in a div with overflow: scroll;.

My problem can be see here: https://jsfiddle.net/xa86wgw9/3/

When I scroll down, the header doesn't move; that's what I want. But when I scroll to the right, the header stay on the left... is there a way to have the two table stay aligned ? css and javascript can be used.

EDIT: I'm currently working on IE10, so position: sticky isn't an option.

答:
you can use position:stickyto achieve what you want

fiddle


问:
Error with setting data to subkey at Registry
I am trying to write new key i.e Mode and assign a a value to it, my system is 32 bit and code is as follows. I am getting an error with the following code as failed to set data for Mode I have tried with all rectification by setting different parameters to reg.Access but no success. I always have to keep reg.Access to KEY_READ as with KEY_WRITE it will not open subkey at reg.OpenKey method.

```<code>  reg := TRegistry.Create(KEY_READ);
  reg.RootKey := HKEY_LOCAL_MACHINE;

  if (not reg.KeyExists('\Software\MyApp\appname\')) then
  begin
      MessageDlg('Key not found! Created now.', mtInformation, mbOKCancel, 0);
  end;

  reg.Access:= KEY_READ;
  openResult := reg.OpenKey('\Software\MyApp\appname\',True);
      if not openResult = True then
      begin
          MessageDlg('Unable to create key! Exiting.', mtError, mbOKCancel, 0);
          Exit();
      end;

      if not reg.KeyExists('Mode') then
      begin
        reg.WriteString('Mode','trial');
      end;
</code>```

答:
KEY_READ gives you read access. But that's not enough for you. You pass True to the CanCreate argument of OpenKey and so need the KEY_CREATE_SUB_KEY access flag. And then you attempt to write a value, which requires the KEY_WRITE access flag.

Your problem is presumably that your process executes as a user without sufficient rights. You will need to make sure that your program runs with sufficient rights. Usually this means running it as administrator. Use the application manifest to enforce that, or the runas verb, whichever method is most appropriate for your application.

Body:
I am trying to write new key i.e Mode and assign a a value to it, my system is 32 bit and code is as follows. I am getting an error with the following code as failed to set data for Mode I have tried with all rectification by setting different parameters to reg.Access but no success. I always have to keep reg.Access to KEY_READ as with KEY_WRITE it will not open subkey at reg.OpenKey method.

  reg := TRegistry.Create(KEY_READ);
  reg.RootKey := HKEY_LOCAL_MACHINE;

  if (not reg.KeyExists('\Software\MyApp\appname\')) then
  begin
      MessageDlg('Key not found! Created now.', mtInformation, mbOKCancel, 0);
  end;

  reg.Access:= KEY_READ;
  openResult := reg.OpenKey('\Software\MyApp\appname\',True);
      if not openResult = True then
      begin
          MessageDlg('Unable to create key! Exiting.', mtError, mbOKCancel, 0);
          Exit();
      end;

      if not reg.KeyExists('Mode') then
      begin
        reg.WriteString('Mode','trial');
      end;


问:
How to deploy an ActiveX control through JavaScript/jQuery DOM methods?
I have a page that needs to be able to invoke the installation of an ActiveX control through JavaScript. I have tried a few DOM-centric methods, but have not been able to get anywhere. If the ActiveX is already installed, I can get it to load, but I can't seem to get the CAB to install. Using straight HTML, the installation works, yellow bar and all.

This is the code that is able to load the ActiveX. It uses jQuery 1.4.2. host is a reference to a visible div element on the page. result is true if the ActiveX is loaded, false otherwise (I don't know if it works on all ActiveX controls, but it works for the one my company has developed).

```<code>var attributes = {
    id: "ax",
    classid: "clsid:" + drv.clsid,
    codebase: install ? drv.cab : undefined,
    width: 0,
    height: 0
};

try {
    axSelector = $("<object></object>", attributes);
    host.append(axSelector);
} catch (e) {
    return false;
}

ax = axSelector[0];

var result = ax && ax["Enabled"] !== undefined && ax["Enabled"] !== null;

axSelector.remove();
</code>```

答: I got this working by refactoring my code so that I could embed the object tag into the page on the server side during a postback (ASP.NET). Not exactly the solution I was hoping for, but it works.</p>

Body:
I have a page that needs to be able to invoke the installation of an ActiveX control through JavaScript. I have tried a few DOM-centric methods, but have not been able to get anywhere. If the ActiveX is already installed, I can get it to load, but I can't seem to get the CAB to install. Using straight HTML, the installation works, yellow bar and all.

This is the code that is able to load the ActiveX. It uses jQuery 1.4.2. host is a reference to a visible div element on the page. result is true if the ActiveX is loaded, false otherwise (I don't know if it works on all ActiveX controls, but it works for the one my company has developed).

var attributes = {
    id: "ax",
    classid: "clsid:" + drv.clsid,
    codebase: install ? drv.cab : undefined,
    width: 0,
    height: 0
};

try {
    axSelector = $("<object></object>", attributes);
    host.append(axSelector);
} catch (e) {
    return false;
}

ax = axSelector[0];

var result = ax && ax["Enabled"] !== undefined && ax["Enabled"] !== null;

axSelector.remove();


问:
Run code every day at a specific time - AlarmManager
Currently, I am trying to run a piece of code at a specific time. After some research, I think the correct way to go is to make usage of the AlarmManger. The code should be executed every day at 3 am. If the phone is at 3 am shut down, the code should be executed directly after turning the phone on.

I used googled and found a lot of results. But my code isn't working correctly.

Yesterday I got a notification. The notification time was 10 pm. But in the code, the time is set to 3 am. I set up a lot of alarm manager over the time (because of testing). Could it be possible, that the triggered AlarmManager was an old one? Note: Before setting up a new AlarmManager I deleted the complete application from my phone and installed it new. (I think this will delete all set AlarmManager's?)

Okay, here is the code I am using:

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 0);
calendar.add(Calendar.MINUTE, 0);
calendar.add(Calendar.HOUR, 3);

Intent _myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
_myIntent.putExtra("MyMessage","Content of the message");
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 123, _myIntent, PendingIntent.FLAG_UPDATE_CURRENT);

AlarmManager alarmManager = (AlarmManager) MainActivity.this.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000*60*60*24, pendingIntent);```

This code will be executed on every startup of my app (inside MainActivity's onCreate(); method).

答:
Note: as of API 19, all repeating alarms are inexact. If your application needs precise delivery times then it must use one-time exact alarms, rescheduling each time.

Inexact scheduling means the time between any two successive firings of the alarm may vary. Thats what happening in your case i guess.To overcome the exact time issue i think you should use one shot alarm.But in this case you need to reschedule it for next day. and so on.
 You can get a very clear understanding from the Documentation setrepeating , setInexactRepeating.

EDIT:- TO optimizing DOZE mode
In Case you are Using setAndAllowWhileIdle() or setExactAndAllowWhileIdle(),
Then you must read This Document which says :-

Neither setAndAllowWhileIdle() nor setExactAndAllowWhileIdle() can fire alarms more than once per 9 minutes, per app.

Body:
Currently, I am trying to run a piece of code at a specific time. After some research, I think the correct way to go is to make usage of the AlarmManger. The code should be executed every day at 3 am. If the phone is at 3 am shut down, the code should be executed directly after turning the phone on.

I used googled and found a lot of results. But my code isn't working correctly.

Yesterday I got a notification. The notification time was 10 pm. But in the code, the time is set to 3 am. I set up a lot of alarm manager over the time (because of testing). Could it be possible, that the triggered AlarmManager was an old one? Note: Before setting up a new AlarmManager I deleted the complete application from my phone and installed it new. (I think this will delete all set AlarmManager's?)

Okay, here is the code I am using:

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 0);
calendar.add(Calendar.MINUTE, 0);
calendar.add(Calendar.HOUR, 3);

Intent _myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
_myIntent.putExtra("MyMessage","Content of the message");
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 123, _myIntent, PendingIntent.FLAG_UPDATE_CURRENT);

AlarmManager alarmManager = (AlarmManager) MainActivity.this.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000*60*60*24, pendingIntent);

This code will be executed on every startup of my app (inside MainActivity's onCreate(); method).

ContentLicense: CC BY-SA 4.0


问:
Switching classes onClick toggle
I am learning by doing and have hit a road block while developing a website. I have a menu with 4 options, there is an active state and off state in css as well as the first option is active by default. When clicking any option it toggles it to the active state but does not change the previous one to the off state.

Code:

function myFunc(e) {
  if (e.className == 'channel') {
    e.className = 'channel active';
  } else {
    e.className = 'channel';
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><li id="test" class="channel active" data-v-a3c933a2="" onclick="openPlayer('option1'); myFunc(this)">
  <div class="status offline" data-v-a3c933a2="">Offline <span class="viewers" data-v-a3c933a2="">0</span>
  </div>Option1
</li>
<li id="test" class="channel" data-v-a3c933a2="" onclick="openPlayer('option2'); myFunc(this)">
  <div class="status offline" data-v-a3c933a2="">Offline <span class="viewers" data-v-a3c933a2="">0</span>
  </div>Option2
</li>
<li id="test" class="channel" data-v-a3c933a2="" onclick="openPlayer('option3'); myFunc(this)">
  <div class="status offline" data-v-a3c933a2="">Offline <span class="viewers" data-v-a3c933a2="">0</span>
  </div>Option3
</li>
<li id="test" class="channel" data-v-a3c933a2="" onclick="openPlayer('option4'); myFunc(this)">
  <div class="status offline" data-v-a3c933a2="">Offline <span class="viewers" data-v-a3c933a2="">0</span>
  </div>Option4
</li></code>```

How do I go about having all nonactive options actually display in the off state instead of just toggling per-click?

Thank you for your time!

答:
Initially option1 is active.
When you click on option2, option2 becomes active but there is no code to make option1 inactive. So both option1 and option2 are active. Add a logic to ensure at anytime only one option can be set active class.</p>

Title: Switching classes onClick toggle

Body:
I am learning by doing and have hit a road block while developing a website. I have a menu with 4 options, there is an active state and off state in css as well as the first option is active by default. When clicking any option it toggles it to the active state but does not change the previous one to the off state.

Code:

function myFunc(e) {
  if (e.className == 'channel') {
    e.className = 'channel active';
  } else {
    e.className = 'channel';
  }
}

Offline 0

Option1

Offline 0

Option2

Offline 0

Option3

Offline 0

Option4

How do I go about having all nonactive options actually display in the off state instead of just toggling per-click?

Thank you for your time!


问:
plotting in ipython notebook in 2 steps
I have the following script that works in jupyter notebook when run through a single cell, but fails when running through 2 cells as done below:

Is there any way to make this kind of arrangement work in notebook?

cell 1:

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

    def __init__(self, run, hist):
        self.running = run
        self.histogram = hist

    def start_plot(self):
        if self.running:
            self.run_fig, self.run_ax = plt.subplots(1,2)
        if self.histogram:
            self.hist_fig, self.hist_ax = plt.subplots(1,2)

    def create_plots(self, iwindow, run_series, hist_series):
        if self.running:
            self.run_ax[iwindow].plot(run_series)
        if self.histogram:
            self.hist_ax[iwindow].hist(hist_series, histtype='step')

plot = Plotting(run =1, hist =1)
plot.start_plot()
</code>```

cell 2:

```<code>for iwindow in np.arange(2):
   r = np.random.rand(20)
   h = np.random.rand(50)
   plot.create_plots(iwindow, r, h)
</code>```

答:
You would either run this in a single cell,

```<code>%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

class Plotting(object):

    def __init__(self, run, hist):
        self.running = run
        self.histogram = hist

    def start_plot(self):
        if self.running:
            self.run_fig, self.run_ax = plt.subplots(1,2)
        if self.histogram:
            self.hist_fig, self.hist_ax = plt.subplots(1,2)

    def create_plots(self, iwindow, run_series, hist_series):
        if self.running:
            self.run_ax[iwindow].plot(run_series)
        if self.histogram:
            self.hist_ax[iwindow].hist(hist_series, histtype='step')

plot = Plotting(run =1, hist =1)
plot.start_plot()

for iwindow in np.arange(2):
    r = np.random.rand(20)
    h = np.random.rand(50)
    plot.create_plots(iwindow, r, h)
</code>```

Or if you need to run it in two different cells, you need to display the output:

cell 1

```<code>%%capture
%matplotlib inline
from IPython.display import display
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

class Plotting(object):

    def __init__(self, run, hist):
        self.running = run
        self.histogram = hist

    def start_plot(self):
        if self.running:
            self.run_fig, self.run_ax = plt.subplots(1,2)
        if self.histogram:
            self.hist_fig, self.hist_ax = plt.subplots(1,2)

    def create_plots(self, iwindow, run_series, hist_series):
        if self.running:
            self.run_ax[iwindow].plot(run_series)
        if self.histogram:
            self.hist_ax[iwindow].hist(hist_series, histtype='step')

plot = Plotting(run =1, hist =1)
plot.start_plot()
</code>```

cell 2

```<code>for iwindow in np.arange(2):
    r = np.random.rand(20)
    h = np.random.rand(50)
    plot.create_plots(iwindow, r, h)
display(plot.run_fig)
display(plot.hist_fig)
</code>```

Title: plotting in ipython notebook in 2 steps

Body:
I have the following script that works in jupyter notebook when run through a single cell, but fails when running through 2 cells as done below:

Is there any way to make this kind of arrangement work in notebook?

cell 1:

class Plotting(object):

    def __init__(self, run, hist):
        self.running = run
        self.histogram = hist

    def start_plot(self):
        if self.running:
            self.run_fig, self.run_ax = plt.subplots(1,2)
        if self.histogram:
            self.hist_fig, self.hist_ax = plt.subplots(1,2)

    def create_plots(self, iwindow, run_series, hist_series):
        if self.running:
            self.run_ax[iwindow].plot(run_series)
        if self.histogram:
            self.hist_ax[iwindow].hist(hist_series, histtype='step')

plot = Plotting(run =1, hist =1)
plot.start_plot()

cell 2:

for iwindow in np.arange(2):
   r = np.random.rand(20)
   h = np.random.rand(50)
   plot.create_plots(iwindow, r, h)

Body:
You would either run this in a single cell,

%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

class Plotting(object):

    def __init__(self, run, hist):
        self.running = run
        self.histogram = hist

    def start_plot(self):
        if self.running:
            self.run_fig, self.run_ax = plt.subplots(1,2)
        if self.histogram:
            self.hist_fig, self.hist_ax = plt.subplots(1,2)

    def create_plots(self, iwindow, run_series, hist_series):
        if self.running:
            self.run_ax[iwindow].plot(run_series)
        if self.histogram:
            self.hist_ax[iwindow].hist(hist_series, histtype='step')

plot = Plotting(run =1, hist =1)
plot.start_plot()

for iwindow in np.arange(2):
    r = np.random.rand(20)
    h = np.random.rand(50)
    plot.create_plots(iwindow, r, h)

Or if you need to run it in two different cells, you need to display the output:

cell 1

%%capture
%matplotlib inline
from IPython.display import display
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

class Plotting(object):

    def __init__(self, run, hist):
        self.running = run
        self.histogram = hist

    def start_plot(self):
        if self.running:
            self.run_fig, self.run_ax = plt.subplots(1,2)
        if self.histogram:
            self.hist_fig, self.hist_ax = plt.subplots(1,2)

    def create_plots(self, iwindow, run_series, hist_series):
        if self.running:
            self.run_ax[iwindow].plot(run_series)
        if self.histogram:
            self.hist_ax[iwindow].hist(hist_series, histtype='step')

plot = Plotting(run =1, hist =1)
plot.start_plot()

cell 2

for iwindow in np.arange(2):
    r = np.random.rand(20)
    h = np.random.rand(50)
    plot.create_plots(iwindow, r, h)
display(plot.run_fig)
display(plot.hist_fig)


问:
how can i split the longest word in the sentence
```<code>String s = "сотрудник компании ГазТехСтройСнабСервис";
String[] parts = s.split(" ");
System.out.println(Arrays.toString(parts));
</code>```

how can i split the longest word in the sentence for example if it has more than 10 characters and return String?

答:
With java8 -

```<code>int len = 10; //specify your length here

List<String> list = Stream.of(s.split(" ")).filter(str->len > str.length()).collect(Collectors.toList());
</code>```

list will have all the words having length greater than the specified length.

Body:
String s = "сотрудник компании ГазТехСтройСнабСервис";
String[] parts = s.split(" ");
System.out.println(Arrays.toString(parts));

how can i split the longest word in the sentence for example if it has more than 10 characters and return String?

Body:
With java8 -

int len = 10; //specify your length here

List<String> list = Stream.of(s.split(" ")).filter(str->len > str.length()).collect(Collectors.toList());

list will have all the words having length greater than the specified length.


问:
using Mod Rewrite in .htaccess to get "prettify" urls working correctly
I have a website which has several pages which are generated by pulling data from a database, the links to view those pages look like this.

www.mywebsite.com/article.php?id=01&title=title

and i am trying to set up a mod rewrite to get the server to display the the same webpages but using a much nicer looking url.

www.mywebsite.com/article/01/title

the line of code i have used in my .htaccess file is

```<code>RewriteRule ^article/([0-9]+)/([A-Za-z0-9-\+]+)/?$ /article.php?id=$1&title=$2 [NC,L,QSA]
</code>```

now when i go back to my website and type in the following url
www.mywebsite.com/article/01/title

it displays the correct content but there is no styling attached to the page at all?

my full .htaccess is as follows

```<code>## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
## EXPIRES CACHING ##
# Needed before any rewriting
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^/]+/)*(default|index)\.   (html|php|htm)\ HTTP/ [NC]
RewriteRule ^(([^/]+/)*)(default|main|index)\.(html|php|htm)$ http://www.example.com/$1 [R=301]
RewriteRule ^article/([0-9]+)/([A-Za-z0-9-\+]+)/?$ /article.php?id=$1&title=$2 [NC,L,QSA]
</code>```

can someone please tell me what i am doing wrong?
many thanks

答:
That means you have probably attached your css file with a relative path not starting by a "/", change this

```<code><link rel="stylesheet" type="text/css" href="style.css">
<!--- TO -->
<link rel="stylesheet" type="text/css" href="/style.css">
<!-- OR -->
<link rel="stylesheet" type="text/css" href="/path/to/css/style.css">
</code>```

I don't think there is a problem with your rewrite rules, you just have virtual directories in your URL now you have to manage.

Body:
I have a website which has several pages which are generated by pulling data from a database, the links to view those pages look like this.

www.mywebsite.com/article.php?id=01&title=title

and i am trying to set up a mod rewrite to get the server to display the the same webpages but using a much nicer looking url.

www.mywebsite.com/article/01/title

the line of code i have used in my .htaccess file is

RewriteRule ^article/([0-9]+)/([A-Za-z0-9-\+]+)/?$ /article.php?id=$1&title=$2 [NC,L,QSA]

now when i go back to my website and type in the following url
www.mywebsite.com/article/01/title

it displays the correct content but there is no styling attached to the page at all?

my full .htaccess is as follows

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
## EXPIRES CACHING ##
# Needed before any rewriting
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^/]+/)*(default|index)\.   (html|php|htm)\ HTTP/ [NC]
RewriteRule ^(([^/]+/)*)(default|main|index)\.(html|php|htm)$ http://www.example.com/$1 [R=301]
RewriteRule ^article/([0-9]+)/([A-Za-z0-9-\+]+)/?$ /article.php?id=$1&title=$2 [NC,L,QSA]

can someone please tell me what i am doing wrong?
many thanks

Body:
That means you have probably attached your css file with a relative path not starting by a "/", change this

<link rel="stylesheet" type="text/css" href="style.css">
<!--- TO -->
<link rel="stylesheet" type="text/css" href="/style.css">
<!-- OR -->
<link rel="stylesheet" type="text/css" href="/path/to/css/style.css">

I don't think there is a problem with your rewrite rules, you just have virtual directories in your URL now you have to manage.


问:
Auto select input field when toggle is actioned
I have a search bar that only displayed when the toggle button is clicked. The code I am using to do this is:

```<code>$("a.search-toggle").click(function(){
    $(".search-bar").slideToggle(200);
    $(this).toggleClass("open");
});
</code>```

Now I am trying to find a way to auto select the input[type="search"] field when this toggle is actioned. Currently the user has to click the toggle button, then click the search field which isn't very user friendly.

Note

I am not looking for this to occur on page load, only once toggle has been activated.

答:
This should do it

```<code>$('input[type="search"]').focus();
</code>```

See the docs here

Body:
I have a search bar that only displayed when the toggle button is clicked. The code I am using to do this is:

$("a.search-toggle").click(function(){
    $(".search-bar").slideToggle(200);
    $(this).toggleClass("open");
});

Now I am trying to find a way to auto select the input[type="search"] field when this toggle is actioned. Currently the user has to click the toggle button, then click the search field which isn't very user friendly.

Note

I am not looking for this to occur on page load, only once toggle has been activated.

Body:
This should do it

$('input[type="search"]').focus();

See the docs here


问:
Find out "flattened index" from "stacked index" of an Array
I'm trying to come up with an equation to mathematically determine the "flattened index" of an array from the "stacked index."  Observe the following example in Ruby.

```<code>matx = [[[ 1, 2, 3, 4],
         [ 5, 6, 7, 8]],

        [[ 9,10,11,12],
         [13,14,15,16]]]
</code>```

In this example, matx is a three dimensional matrix, and the element 7 is located at matx[0][1][2].  However, in the next example:

```<code>matx.flatten!  # => [1, 2, 3, 4, 5, 6, 7, 8,
               #     9, 10, 11, 12, 13, 14, 15, 16]
</code>```

Now the element 7 is located at matx[6].

So essentially, I'm looking for a way to, given the dimensions of the matrix and the set of indices for the particular element, convert from the stacked matrix to the flattened matrix.  Reverse would be awesome, too, but I figure the way to get that is similar (but essentially reversed) to the method of obtaining this result. I realized that reverse is not actually a function, because there's no way to necessarily tell the difference as to whether 5 maps to [2,3] or [3,2], etc.  So I'm not going to look into that one.

答:
```<code>class Index
  def initialize *dims
    @dims = dims.reverse
  end

  def if_flat *subs
    raise unless @dims && @dims.size == subs.size
    res = 0
    subs.reverse.each_with_index { |s, i| res += s * @dims[0...i].inject(1) { |m, e| m * e }}
    res
  end
end
puts Index.new(2, 2, 4).if_flat 0, 1, 2
</code>```

Body:
I'm trying to come up with an equation to mathematically determine the "flattened index" of an array from the "stacked index."  Observe the following example in Ruby.

matx = [[[ 1, 2, 3, 4],
         [ 5, 6, 7, 8]],

        [[ 9,10,11,12],
         [13,14,15,16]]]

In this example, matx is a three dimensional matrix, and the element 7 is located at matx[0][1][2].  However, in the next example:

matx.flatten!  # => [1, 2, 3, 4, 5, 6, 7, 8,
               #     9, 10, 11, 12, 13, 14, 15, 16]

Now the element 7 is located at matx[6].

So essentially, I'm looking for a way to, given the dimensions of the matrix and the set of indices for the particular element, convert from the stacked matrix to the flattened matrix.  Reverse would be awesome, too, but I figure the way to get that is similar (but essentially reversed) to the method of obtaining this result. I realized that reverse is not actually a function, because there's no way to necessarily tell the difference as to whether 5 maps to [2,3] or [3,2], etc.  So I'm not going to look into that one.


问:
Can you use 'svnadmin hotcopy' with a remote SVN repository
Per the SVN documentation (http://svnbook.red-bean.com/en/1.7/svn.ref.svnadmin.c.hotcopy.html), you can only run svnadmin hotcopy with local repositories.

Is there any way to run this command using a remote SVN repository, using the URL?

I essentially want to make a complete copy of my huge SVN repository (over 6000 versions), including all history, tags, versions etc. and store it on my local machine, completely independent of the remote repository.

答: I tried lots of different methods including svnadmin hotcopy but the best in the end without a doubt was simply svn dump such as this taken from the svn book. svnadmin dump /var/svn/repos > full.dump link here once you have done that pack it up and send it to where you want the repository. I tried pretty much everything else and this was the simplest and the best for me. I seem to remember that it automatically set the UUID which is the unique identification number of your Subversion project. If you want to use it as the original then it needs to be the same UUID, if it is different use the setuuid command such as svnadmin setuuid /var/svn/repos-new 2109a8dd-854f-0410-ad31-d604008985ab http://svnbook.red-bean.com/en/1.6/svn.ref.svnadmin.c.setuuid.html


问:
Remove element n from Java List dependent on n + 1 element
I want to achieve the following but with a List instead of an array (Remove some element based on comparisons between a neighboring element in the array)

```<code>Interval: {
  start,
  end,
  priority;
}

    Interval[] intervals = someIntervalsSortedByStartTime();//[(1,5), (4, 5)]
    for(int i=0; i<intervals.length-1; i++){
    if(intervals[i] == null) continue;
    if((intervals[i].end > intervals[i+1].start) ){
        if(intervals[i].priority < intervals[i+1].priority){
          intervals[i] = null //i.e. have the element removed.
        }else if(intervals[i].priority > intervals[i+1].priority{
          itervals[i+1] = null;
        }else{
         throw new WTFException();
        }
    }
}
</code>```

I know With collection things are a bit different for one we need to use Iterator, ListIterator, Apache collections Iteration, or Google Collections iterator. to remove an item from the List.

ListIterator, Apache, and Google have .previous or .peek methods that can some what allow for the "look ahead" functionality thats shown in the for loop example. However if you use them in addition to .remove() if .previous or .peek was last called before .remove() the previous item will be removed and there isnt a way to specify .remove(index) you would have to call .next().next in some cases and manage getting back to where you want the iterator to be after every iteration.

Steams wont work in this case either as we cant filter based on other elements in the List i.e. we cant get a "next" in steams.

I also wanted to avoid making a temporary copy of the data and deleting the data afterwards.

What would be the best approach of achieving the desired functionality?

答:
You can use a List like an array, you create a loop and use the methods get(int index) and remove(int index) to access/remove Elements from the list. You just have to keep track of the indexes when you delete elements. To avoid this, you can start at the end of the list and work to the beginning:</p>

```<code>for (int i=intervals.length-1; i>=0; i--)
</code>```

Body:
I want to achieve the following but with a List instead of an array (Remove some element based on comparisons between a neighboring element in the array)

Interval: {
  start,
  end,
  priority;
}

    Interval[] intervals = someIntervalsSortedByStartTime();//[(1,5), (4, 5)]
    for(int i=0; i<intervals.length-1; i++){
    if(intervals[i] == null) continue;
    if((intervals[i].end > intervals[i+1].start) ){
        if(intervals[i].priority < intervals[i+1].priority){
          intervals[i] = null //i.e. have the element removed.
        }else if(intervals[i].priority > intervals[i+1].priority{
          itervals[i+1] = null;
        }else{
         throw new WTFException();
        }
    }
}

I know With collection things are a bit different for one we need to use Iterator, ListIterator, Apache collections Iteration, or Google Collections iterator. to remove an item from the List.

ListIterator, Apache, and Google have .previous or .peek methods that can some what allow for the "look ahead" functionality thats shown in the for loop example. However if you use them in addition to .remove() if .previous or .peek was last called before .remove() the previous item will be removed and there isnt a way to specify .remove(index) you would have to call .next().next in some cases and manage getting back to where you want the iterator to be after every iteration.

Steams wont work in this case either as we cant filter based on other elements in the List i.e. we cant get a "next" in steams.

I also wanted to avoid making a temporary copy of the data and deleting the data afterwards.

What would be the best approach of achieving the desired functionality?

Body:
You can use a List like an array, you create a loop and use the methods get(int index) and remove(int index) to access/remove Elements from the list. You just have to keep track of the indexes when you delete elements. To avoid this, you can start at the end of the list and work to the beginning:

for (int i=intervals.length-1; i>=0; i--)


问:
Recursively copy a set of files from one directory to another in PowerShell
I'm trying to copy all *.csproj.user files recursively from C:\Code\Trunk to C:\Code\F2.

For example:

C:\Code\Trunk\SomeProject\Blah\Blah.csproj.user

Would get copied to:

C:\Code\F2\SomeProject\Blah\Blah.csproj.user

My current attempt is:

Copy-Item C:\Code\Trunk -Filter *.csproj.user -Destination
  C:\Code\F2 -Recurse -WhatIf

However I get:

What if: Performing operation "Copy Directory" on Target "Item:
  C:\Code\Trunk Destination: C:\Code\F2\Trunk".

First, it wants to put them all in a new folder called F2\Trunk which is wrong.  Second, it doesn't list any of the files.  There should be about 10 files to be copied over.

What's the correct syntax for the command?  Thanks!

Update:

Okay, it seems to have something to do with the fact that C:\Code\F2 already exists.  If I try copying the files over to a destination that does not exist, it works.

I want to overwrite any existing .csproj.user files in the destination.

答:
While the most voted answer is perfectly valid for single file types, if you need to copy multiple file types there is a more useful functionality called robocopy exactly for this purpose with simpler usage</p>

```<code>robocopy C:\Code\Trunk C:\Code\F2 *.cs *.xaml *.csproj *.appxmanifest /s
</code>```

Body:
While the most voted answer is perfectly valid for single file types, if you need to copy multiple file types there is a more useful functionality called robocopy exactly for this purpose with simpler usage

robocopy C:\Code\Trunk C:\Code\F2 *.cs *.xaml *.csproj *.appxmanifest /s


问:
java 8 Map.merge is thread safe?
```<code>import java.util.HashMap;
import java.util.Map;

public class MainTest
{
    static Map<String, Integer> map = new HashMap();

    public static void incr()
    {
        map.merge("counter", 1, Integer::sum);
    }

    public static void decr()
    {
        map.merge("counter", -1, Integer::sum);
    }

    public static void main(String[] args) throws Exception
    {
        map.put("counter", 0);
        for (int i = 0; i < 10000; i++)
        {
            Thread t1 = new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    incr();
                }
            });
            t1.join();
            t1.start();

            Thread t2 = new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    decr();
                }
            });
            t2.join();
            t2.start();
        }
      System.out.println(map);
    }

}
</code>```

The result is {counter=-2} when main method is run.
Why is it not 0?

答:
It’s a bit strange to ask for the thread safety of a particular single method modifying a data structure like HashMap which is documented not to be thread safe in general.

When you want to modify a map concurrently, you have to look for an implementation which supports concurrent updates, which is usually shown by implementing ConcurrentMap. For these maps, even the default implementation would be sufficient, as it is implemented atop the other interface methods, which are guaranteed to be thread safe. But if you want atomicity guaranteed, you need an implementation overriding the method with an appropriate implementation, e.g. ConcurrentHashMap:

merge

… The entire method invocation is performed atomically. Some attempted update operations on this map by other threads may be blocked while computation is in progress, so the computation should be short and simple, and must not attempt to update any other mappings of this Map.

To fix and simplify your example:

```<code>Map<String, Integer> map = new ConcurrentHashMap<>();
for (int i = 0; i < 10000; i++) {
    Thread t1 = new Thread(() -> map.merge("counter", -1, Integer::sum));
    Thread t2 = new Thread(() -> map.merge("counter",  1, Integer::sum));
    t1.start();
    t2.start();
    t1.join();
    t2.join();
}
System.out.println(map);
</code>```

Note that in your original code, you’re calling join() before start, which has no effect. Since you’re not doing a join() after start(), your code bears the possibility to print the map before all threads have finished, so it could print a nonzero value, even if HashMap was thread safe.

Doing the join() after start() like in the code above will correctly wait for the completion, but allows at most two concurrent update operations.

To raise the concurrency, you should abandon the manual thread creation:

```<code>ExecutorService threadPool
    = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
Map<String, Integer> map = new ConcurrentHashMap<>();
for (int i = 0; i < 10000; i++) {
    threadPool.execute(() -> map.merge("counter", -1, Integer::sum));
    threadPool.execute(() -> map.merge("counter",  1, Integer::sum));
}
threadPool.shutdown();
threadPool.awaitTermination(1, TimeUnit.DAYS);
System.out.println(map);
</code>```

This allows a concurrency higher than two, but since the worker threads might be able to execute this simple task as fast as your loop can schedule new jobs, the resulting concurrency might be still close to two.

Title: java 8 Map.merge is thread safe?

Body:
import java.util.HashMap;
import java.util.Map;

public class MainTest
{
    static Map<String, Integer> map = new HashMap();

    public static void incr()
    {
        map.merge("counter", 1, Integer::sum);
    }

    public static void decr()
    {
        map.merge("counter", -1, Integer::sum);
    }

    public static void main(String[] args) throws Exception
    {
        map.put("counter", 0);
        for (int i = 0; i < 10000; i++)
        {
            Thread t1 = new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    incr();
                }
            });
            t1.join();
            t1.start();

            Thread t2 = new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    decr();
                }
            });
            t2.join();
            t2.start();
        }
      System.out.println(map);
    }

}

The result is {counter=-2} when main method is run.
Why is it not 0?

Body:
It’s a bit strange to ask for the thread safety of a particular single method modifying a data structure like HashMap which is documented not to be thread safe in general.

When you want to modify a map concurrently, you have to look for an implementation which supports concurrent updates, which is usually shown by implementing ConcurrentMap. For these maps, even the default implementation would be sufficient, as it is implemented atop the other interface methods, which are guaranteed to be thread safe. But if you want atomicity guaranteed, you need an implementation overriding the method with an appropriate implementation, e.g. ConcurrentHashMap:

merge

… The entire method invocation is performed atomically. Some attempted update operations on this map by other threads may be blocked while computation is in progress, so the computation should be short and simple, and must not attempt to update any other mappings of this Map.

To fix and simplify your example:

Map<String, Integer> map = new ConcurrentHashMap<>();
for (int i = 0; i < 10000; i++) {
    Thread t1 = new Thread(() -> map.merge("counter", -1, Integer::sum));
    Thread t2 = new Thread(() -> map.merge("counter",  1, Integer::sum));
    t1.start();
    t2.start();
    t1.join();
    t2.join();
}
System.out.println(map);

Note that in your original code, you’re calling join() before start, which has no effect. Since you’re not doing a join() after start(), your code bears the possibility to print the map before all threads have finished, so it could print a nonzero value, even if HashMap was thread safe.

Doing the join() after start() like in the code above will correctly wait for the completion, but allows at most two concurrent update operations.

To raise the concurrency, you should abandon the manual thread creation:

ExecutorService threadPool
    = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
Map<String, Integer> map = new ConcurrentHashMap<>();
for (int i = 0; i < 10000; i++) {
    threadPool.execute(() -> map.merge("counter", -1, Integer::sum));
    threadPool.execute(() -> map.merge("counter",  1, Integer::sum));
}
threadPool.shutdown();
threadPool.awaitTermination(1, TimeUnit.DAYS);
System.out.println(map);

This allows a concurrency higher than two, but since the worker threads might be able to execute this simple task as fast as your loop can schedule new jobs, the resulting concurrency might be still close to two.


问:
Pass $(this) to a function
I am trying to build a media playlist that can advance the credits, play the video and change the title on thumb-hover, end of video and on next/prev click. So I need to write some functions that can then be called together. So like this:

```<code>    function showBox()
    {
        $(this).parents('.container').find('.box').show();
    };

    function hideBox()
    {
        $(this).parents('.container').find('.box').hide();
    };

    $('a').hover(
        function()
        {
            showBox();
        },
        function()
        {
            hideBox();
        }
    );
</code>```

The problem is that $(this) does not carry through to the functions from the .hover. How do I do this?

答:
The this will carry through if you just do:

```<code>$('a').hover(showBox,hideBox);
</code>```

EDIT: To address the question in the comment, this will work for any function you assign as an event handler. Doesn't matter if it is an anonymous function or a named one.

This:

```<code>$('a').click(function() {
    alert( this.tagName );
});
</code>```

...is the same as:

```<code>function alertMe() {
    alert( this.tagName );
}

$('a').click( alertMe );
</code>```

...or this:

```<code>function alertMe() {
    alert( this.tagName );
}

$('a').bind('click', alertMe );
</code>```

Title: Pass $(this) to a function

Body:
I am trying to build a media playlist that can advance the credits, play the video and change the title on thumb-hover, end of video and on next/prev click. So I need to write some functions that can then be called together. So like this:

    function showBox()
    {
        $(this).parents('.container').find('.box').show();
    };

    function hideBox()
    {
        $(this).parents('.container').find('.box').hide();
    };

    $('a').hover(
        function()
        {
            showBox();
        },
        function()
        {
            hideBox();
        }
    );

The problem is that $(this) does not carry through to the functions from the .hover. How do I do this?

Body:
The this will carry through if you just do:

$('a').hover(showBox,hideBox);

EDIT: To address the question in the comment, this will work for any function you assign as an event handler. Doesn't matter if it is an anonymous function or a named one.

This:

$('a').click(function() {
    alert( this.tagName );
});

...is the same as:

function alertMe() {
    alert( this.tagName );
}

$('a').click( alertMe );

...or this:

function alertMe() {
    alert( this.tagName );
}

$('a').bind('click', alertMe );


问:
Rating bar with custom size
I have to display rating bar with my custom size. But in the case that rating bar with my custom size, the stars disappear in my layout. Can I manage the size of padding and margin the rating bar?</p>

```<code> <RatingBar
                    android:focusable="false"
                    android:id="@+id/rating_order"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:numStars="5"
                    android:stepSize="1.0"
                    android:scaleX="0.3"
                    android:scaleY="0.3" />
</code>```

答:
You can try to set the parameters from styles:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
  <style name="CustomRatingBar" parent="@android:style/Widget.RatingBar" >
 <item name="android:numStars">5</item>
 <item name="android:stepSize">1.0</item>
 <item name="android:layout_width">wrap_content</item>
 <item name="android:layout_height">wrap_content</item>
 <item name="android:paddingBottom">44dp</item>
 <item name="android:layout_marginLeft">4dp</item>
 <item name="android:layout_marginTop">4dp</item>
  </style>
<resources />
</code>```

And then in your RatingBar add a style:

```<code>style="@style/CustomRatingBar"
</code>```

Title: Rating bar with custom size

Body:
I have to display rating bar with my custom size. But in the case that rating bar with my custom size, the stars disappear in my layout. Can I manage the size of padding and margin the rating bar?

 <RatingBar
                    android:focusable="false"
                    android:id="@+id/rating_order"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:numStars="5"
                    android:stepSize="1.0"
                    android:scaleX="0.3"
                    android:scaleY="0.3" />

Body:
You can try to set the parameters from styles:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <style name="CustomRatingBar" parent="@android:style/Widget.RatingBar" >
 <item name="android:numStars">5</item>
 <item name="android:stepSize">1.0</item>
 <item name="android:layout_width">wrap_content</item>
 <item name="android:layout_height">wrap_content</item>
 <item name="android:paddingBottom">44dp</item>
 <item name="android:layout_marginLeft">4dp</item>
 <item name="android:layout_marginTop">4dp</item>
  </style>
<resources />

And then in your RatingBar add a style:

style="@style/CustomRatingBar"


问:
GetTransactionDetails and permissions in the new REST API world
I'm still trying to wrap my head around all this, so my apologies if I've made a mistake, but it seems like the old NVP apps that are now unable to be registered as of December 1st had some features available that can't be replicated in the new REST world order...

Here's what I want/need:  I need to be able to translate buyer-side transaction IDs into my seller-side transaction IDs, and I want to be able to do this on a webserver that is secure but I don't want it to have full access to my account, so I'd like fine-grained authz for this server.

It seems like I am a couple days too late to actually get what I want/need.  Basically, GetTransactionDetails does exactly what I want (convert buyer to seller transaction IDs, and returns the rest of the transaction information for good measure). And, although I haven't gotten it working, it looks like the Permissions SDK plus an NVP AppID would allow me to have just the TRANSACTION_DETAILS permission on this service which is exactly what I want.

However, as of Friday apparently I can't get an AppID for the classic NVP API?  If so, my timing is impeccable.

Trying to figure out how to do this in the REST API has proven difficult.  This thread talks about the sale record, which does indeed take a buyer-side transaction ID, but it does not actually translate it into a seller-side one.  It does have the custom field, which helps me a little, but I really need the seller-side transaction ID.  It looks like maybe the parent_payment URL in the return from the sale might help, but the API started returning PERMISSION_DENIED on me even on previously successful queries so I can't exactly test this right now.  And, even if that did work, it seems like the permissions on the REST API are incredibly coarse compared to the Permissions SDK, for example the sale endpoint is under /v1/payments which seems to also include refunds and all kinds of other stuff I don't want exposed.  It looks like there's a Transaction Search permission but it's marked beta and it didn't work for querying a sale for me.  But maybe it means they're working on it?

What are my options here?

Thanks,
Chris

答:
Okay, so I played around with this for a while, and it seems like the PayPal REST API is just not very good.  So, I worked around the limitations here using AWS Lambda and its fine-grained IAM permissions.  I created a Lambda function that took my PayPal NVP credentials as encrypted env vars, and an IAM account that could only call my Lambda function, and so now I've got a microservice that will translate transaction IDs and return some extra info (custom and email) from the transaction to boot.

I wish I didn't have to use AWS to work around PayPal's limitations (which seem to be getting worse with the REST API, the NVP api would have been fine if I could have gotten and AppID and used the Permissions SDK), but oh well.

Chris


问:
How to create Tree Structure of Directory with check box using Tkinter

I am making a GUI which will copy folder or file from source to destination.I need to make Tree structure of Directory with checkbox to browse file.I refered this How to create a tree view with checkboxes in Python but i did't find logic to create whole folder .
Please help me to solve this issue.    </p>

```<code>from tkinter import tix

import os
i = 0

class View(object):

 def __init__(self, root,path):
    self.root = root
    self.path = path
    self.makeCheckList(self.path)

 def makeCheckList(self,path1):
    global i
    self.cl = tix.CheckList(self.root, browsecmd=self.selectItem)
    self.cl.pack(fill='both',expand="yes")

    self.cl.hlist.add("CL1", text=path1)
    self.cl.setstatus("CL1", "off")
    self.check(path1)

    self.cl.autosetmode()

 def selectItem(self, item):
    print (item, self.cl.getstatus(item))

 def check(self,path1):
    global i
    self.path1 = path1
    file = os.listdir(path1)
    for p in file:
        #print(p)
        full_path = path1 +"\\"+ p
        val = "CL1.Item1"
        if os.path.isdir(full_path) != True :
            self.cl.hlist.add("CL1.Item"+ str(i), text=p)
            self.cl.setstatus("CL1.Item"+str(i), "off")
            i = i + 1
    self.dir(path1)

 def dir(self,path1):

    global i
    self.path1 = path1
    file = os.listdir(path1)
    for folder in file:
        full_path = path1 +"\\"+ folder
        if os.path.isdir(full_path) == True :
            self.cl.hlist.add("CL1.Item"+str(i), text=folder)
            self.cl.setstatus("CL1.Item"+str(i), "off")
            i = i + 1
            #self.dir(full_path)

def main():
   root = tix.Tk()
   root.geometry("800x400")
   view = View(root,"C:\\")
   root.update()
   root.mainloop()

if __name__ == '__main__':
   main()
</code>```

<p>
My logic is not correct here.I want a recursive function which will create whole directory
</p>

答:
If you want to make a tree of the content of a directory, you indeed need a recursive function. For each element of the directory, first put it in the tree and then, if it is a directory, reapply the function:

```<code>def check(self, parent, path):
    content = os.listdir(path)
    for i, item in enumerate(content):
        full_path = os.path.join(path, item)  # item absolute path
        entry = "{}.Item{}".format(parent, i)  # item path in the tree
        self.cl.hlist.add(entry, text=item)   # add item in the tree
        self.cl.setstatus(entry, "off")
        if os.path.isdir(full_path):
            # reapply the function if the item is a directory
            self.check(entry, full_path)
</code>```

In this function, I need to keep track both of the parent directory absolute path and its path in the tree.

Then, to generate the tree, use the makeCheckList method:

```<code>def makeCheckList(self):  # no need of any extra argument here
    self.cl = tix.CheckList(self.root, browsecmd=self.selectItem)
    self.cl.pack(fill='both',expand="yes")
    # add the root directory in the tree
    self.cl.hlist.add("CL1", text=self.path)
    self.cl.setstatus("CL1", "off")
    # build the tree
    self.check("CL1", self.path)

    self.cl.autosetmode()
</code>```

If you use python 3.5 or higher, you can replace os.listdir by os.scandir to speed up your program:

```<code>def check(self, parent, path):
    with os.scandir(path) as content:
        for i, item in enumerate(content):
            entry = "{}.Item{}".format(parent, i)
            self.cl.hlist.add(entry, text=item.name)
            self.cl.setstatus(entry, "off")
            if item.is_dir():
                self.check(entry, item.path)
</code>```

Body:
I am making a GUI which will copy folder or file from source to destination.I need to make Tree structure of Directory with checkbox to browse file.I refered this How to create a tree view with checkboxes in Python but i did't find logic to create whole folder .
Please help me to solve this issue.

from tkinter import tix

import os
i = 0

class View(object):

 def __init__(self, root,path):
    self.root = root
    self.path = path
    self.makeCheckList(self.path)

 def makeCheckList(self,path1):
    global i
    self.cl = tix.CheckList(self.root, browsecmd=self.selectItem)
    self.cl.pack(fill='both',expand="yes")

    self.cl.hlist.add("CL1", text=path1)
    self.cl.setstatus("CL1", "off")
    self.check(path1)

    self.cl.autosetmode()

 def selectItem(self, item):
    print (item, self.cl.getstatus(item))

 def check(self,path1):
    global i
    self.path1 = path1
    file = os.listdir(path1)
    for p in file:
        #print(p)
        full_path = path1 +"\\"+ p
        val = "CL1.Item1"
        if os.path.isdir(full_path) != True :
            self.cl.hlist.add("CL1.Item"+ str(i), text=p)
            self.cl.setstatus("CL1.Item"+str(i), "off")
            i = i + 1
    self.dir(path1)

 def dir(self,path1):

    global i
    self.path1 = path1
    file = os.listdir(path1)
    for folder in file:
        full_path = path1 +"\\"+ folder
        if os.path.isdir(full_path) == True :
            self.cl.hlist.add("CL1.Item"+str(i), text=folder)
            self.cl.setstatus("CL1.Item"+str(i), "off")
            i = i + 1
            #self.dir(full_path)

def main():
   root = tix.Tk()
   root.geometry("800x400")
   view = View(root,"C:\\")
   root.update()
   root.mainloop()

if __name__ == '__main__':
   main()

My logic is not correct here.I want a recursive function which will create whole directory

Body:
If you want to make a tree of the content of a directory, you indeed need a recursive function. For each element of the directory, first put it in the tree and then, if it is a directory, reapply the function:

def check(self, parent, path):
    content = os.listdir(path)
    for i, item in enumerate(content):
        full_path = os.path.join(path, item)  # item absolute path
        entry = "{}.Item{}".format(parent, i)  # item path in the tree
        self.cl.hlist.add(entry, text=item)   # add item in the tree
        self.cl.setstatus(entry, "off")
        if os.path.isdir(full_path):
            # reapply the function if the item is a directory
            self.check(entry, full_path)

In this function, I need to keep track both of the parent directory absolute path and its path in the tree.

Then, to generate the tree, use the makeCheckList method:

def makeCheckList(self):  # no need of any extra argument here
    self.cl = tix.CheckList(self.root, browsecmd=self.selectItem)
    self.cl.pack(fill='both',expand="yes")
    # add the root directory in the tree
    self.cl.hlist.add("CL1", text=self.path)
    self.cl.setstatus("CL1", "off")
    # build the tree
    self.check("CL1", self.path)

    self.cl.autosetmode()

If you use python 3.5 or higher, you can replace os.listdir by os.scandir to speed up your program:

def check(self, parent, path):
    with os.scandir(path) as content:
        for i, item in enumerate(content):
            entry = "{}.Item{}".format(parent, i)
            self.cl.hlist.add(entry, text=item.name)
            self.cl.setstatus(entry, "off")
            if item.is_dir():
                self.check(entry, item.path)


问:
How to correctly make an Observable.ajax.post request in RXJS5
Im using redux-observable with rxjs 5.5 and I am attempting to make a basic ajax POST request to a node express server.

I cant seem to find any relevant documentation or up to date working examples for Observable.ajax. Whatever solution is offered appears to throw some error, despite seeming to be the correct signature according to the actual API

My current code snippet using (redux-observable and rxjs 5.5: is as follows:

```<code>const loginEpic = (actions) =>  {

    const opts = credentials => {
        const { username, password } = credentials;
        return {
            url: 'http://localhost:3001/login',
            body:{ username, password },
            headers: {  'Content-Type': 'application/json; charset=utf-8' },
        };
    };

     return actions.ofType(ActionTypes.LOGIN_REQUESTED)
        .switchMap(({credentials}) => {
            const { url, body, headers } = opts(credentials)
            return Observable.ajax.post(url, body, headers)
            .map(loginResponse =>
                loginResponse.status===200
                    ? loginResolvedAction(loginResponse.response)
                    : loginFailedAction(loginResponse.response))})
}
</code>```

This is a nth iteration of trying to get this working, but to no avail. First issue, is the fact that I would like to set the crossDomain property to true, as its default to false, however, there seems to be nowhere for such a property to be set (despite the Chrome Dev Tools showing it to be there.

Here is the error:

```<code>Failed to load http://localhost:3001/login: Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers in preflight response.
</code>```

I am using a simple express server on the back end which simply returns a basic JSON object when the url is hit on post. However, this endpoint is not hit with the current Observable.ajax.post request above.

I have a Chrome plugin which allows CORS, and using other libraries such as Axios seems to work. However, I prefer to use Observables and redux-observable and rxjs are great libraries, kudos to the authors, but I cant get to the bottom of the ajax issue. Can anyone help?

答:
Hmm, I seem to have overcome the issue, though I cannot see how this solution actually fixed it, since its not aligned with the Api. Here is my solution in case anyone has similar issues.

```<code>const reportsEpic = (actions) => {

    const requestSettings = token => ({
        url:`http://localhost:3001/testReports/${token}`,
        crossDomain: true,
        contentType: "application/json; charset=utf-8",
        responseType:'json',
    })

    return actions.ofType(ActionTypes.REPORTS_REQUESTED)
        .switchMap(({token}) =>
            Observable.ajax(requestSettings(token))
            .map(reportsResponse =>
                reportsResolvedAction(reportsResponse.response)));
}
</code>```

My confusion arises from the Api which provides for Observable.ajax.post as:

```<code>(method) AjaxCreationMethod.post(url: string, body?: any, headers?: Object): Observable<AjaxResponse>
</code>```

However using ajax without the specific post metho is given as:

```<code>let Observable<T>.ajax: AjaxCreationMethod(urlOrRequest: string | AjaxRequest) => Observable<AjaxResponse>
</code>```

Passing in 'POST' as a request object parameter. These two signatures seem confusing. Why would one use ajax.post(), if it fails where ajax() doesn't?

Anyone have any insight to this?

Body:
Im using redux-observable with rxjs 5.5 and I am attempting to make a basic ajax POST request to a node express server.

I cant seem to find any relevant documentation or up to date working examples for Observable.ajax. Whatever solution is offered appears to throw some error, despite seeming to be the correct signature according to the actual API

My current code snippet using (redux-observable and rxjs 5.5: is as follows:

const loginEpic = (actions) =>  {

    const opts = credentials => {
        const { username, password } = credentials;
        return {
            url: 'http://localhost:3001/login',
            body:{ username, password },
            headers: {  'Content-Type': 'application/json; charset=utf-8' },
        };
    };

     return actions.ofType(ActionTypes.LOGIN_REQUESTED)
        .switchMap(({credentials}) => {
            const { url, body, headers } = opts(credentials)
            return Observable.ajax.post(url, body, headers)
            .map(loginResponse =>
                loginResponse.status===200
                    ? loginResolvedAction(loginResponse.response)
                    : loginFailedAction(loginResponse.response))})
}

This is a nth iteration of trying to get this working, but to no avail. First issue, is the fact that I would like to set the crossDomain property to true, as its default to false, however, there seems to be nowhere for such a property to be set (despite the Chrome Dev Tools showing it to be there.

Here is the error:

Failed to load http://localhost:3001/login: Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers in preflight response.

I am using a simple express server on the back end which simply returns a basic JSON object when the url is hit on post. However, this endpoint is not hit with the current Observable.ajax.post request above.

I have a Chrome plugin which allows CORS, and using other libraries such as Axios seems to work. However, I prefer to use Observables and redux-observable and rxjs are great libraries, kudos to the authors, but I cant get to the bottom of the ajax issue. Can anyone help?

Body:
Hmm, I seem to have overcome the issue, though I cannot see how this solution actually fixed it, since its not aligned with the Api. Here is my solution in case anyone has similar issues.

const reportsEpic = (actions) => {

    const requestSettings = token => ({
        url:`http://localhost:3001/testReports/${token}`,
        crossDomain: true,
        contentType: "application/json; charset=utf-8",
        responseType:'json',
    })

    return actions.ofType(ActionTypes.REPORTS_REQUESTED)
        .switchMap(({token}) =>
            Observable.ajax(requestSettings(token))
            .map(reportsResponse =>
                reportsResolvedAction(reportsResponse.response)));
}

My confusion arises from the Api which provides for Observable.ajax.post as:

(method) AjaxCreationMethod.post(url: string, body?: any, headers?: Object): Observable<AjaxResponse>

However using ajax without the specific post metho is given as:

let Observable<T>.ajax: AjaxCreationMethod(urlOrRequest: string | AjaxRequest) => Observable<AjaxResponse>

Passing in 'POST' as a request object parameter. These two signatures seem confusing. Why would one use ajax.post(), if it fails where ajax() doesn't?

Anyone have any insight to this?


问:
Partition pruning/elimination in SAP ASE database
I want to implement partition pruning for an SAP ASE database, but the partitioning does not seem to get used.

Here is a minimal verifyable example of my problem:

I have created a table:

```<code>create table Employee(
    empId INT not null,
    empName VARCHAR(50) not null,
    CONSTRAINT Employee_bk PRIMARY KEY(empId)
)
partition by range (empId)
(
    Employee_p1 values <= (5),
    Employee_p2 values <= (10),
    Employee_p3 values <= (15),
    Employee_p4 values <= (20)
)
</code>```

The following data is inserted into the table:

```<code>empId  empName
   1  hskf
   6  fdgfh
   8  kygj
  15  zcc
  17  xvx
</code>```

When I select from the table, the query returns the correct record:

```<code>1>select * from Employee where empId=6
2>go

empId       empName
----------- --------------------------------------------------
6           fdgfh
</code>```

The problem is that the Query plan shows that the query is scanning all partitions instead of eliminating other partitions scan:

```<code>STEP 1
The type of query is SELECT.

1 operator(s) under root

|ROOT:EMIT Operator (VA = 1)
|
|   |SCAN Operator (VA = 0)
|   |  FROM TABLE
|   |  Employee
|   |  [ Partitions Used: 4, Eliminated: 0]
|   |  [ Eliminated Partition ids : ]
|   |  [ Used Partition ids : ]
|   |  [ Using Dynamic Partition Elimination ]
|   |  Using Clustered Index.
|   |  Index : Employee_bk
|   |  Forward Scan.
|   |  Positioning by key.
|   |  Keys are:
|   |    empId ASC
|   |  Using I/O Size 2 Kbytes for data pages.
|   |  With LRU Buffer Replacement Strategy for data pages.
</code>```

As per the documentation, the setting enable semantic partitioning is set to 1.

Can anyone please suggest how to eliminate unnecessary partition scan?

答:
On possible solution is that the database setting

```<code>basic_optimization_partitions
</code>```

is switched off. Check if this setting is disabled and if the partition pruning works when this is switched on.

Body:
I want to implement partition pruning for an SAP ASE database, but the partitioning does not seem to get used.

Here is a minimal verifyable example of my problem:

I have created a table:

create table Employee(
    empId INT not null,
    empName VARCHAR(50) not null,
    CONSTRAINT Employee_bk PRIMARY KEY(empId)
)
partition by range (empId)
(
    Employee_p1 values <= (5),
    Employee_p2 values <= (10),
    Employee_p3 values <= (15),
    Employee_p4 values <= (20)
)

The following data is inserted into the table:

empId  empName
   1  hskf
   6  fdgfh
   8  kygj
  15  zcc
  17  xvx

When I select from the table, the query returns the correct record:

1>select * from Employee where empId=6
2>go

empId       empName
----------- --------------------------------------------------
6           fdgfh

The problem is that the Query plan shows that the query is scanning all partitions instead of eliminating other partitions scan:

STEP 1
The type of query is SELECT.

1 operator(s) under root

|ROOT:EMIT Operator (VA = 1)
|
|   |SCAN Operator (VA = 0)
|   |  FROM TABLE
|   |  Employee
|   |  [ Partitions Used: 4, Eliminated: 0]
|   |  [ Eliminated Partition ids : ]
|   |  [ Used Partition ids : ]
|   |  [ Using Dynamic Partition Elimination ]
|   |  Using Clustered Index.
|   |  Index : Employee_bk
|   |  Forward Scan.
|   |  Positioning by key.
|   |  Keys are:
|   |    empId ASC
|   |  Using I/O Size 2 Kbytes for data pages.
|   |  With LRU Buffer Replacement Strategy for data pages.

As per the documentation, the setting enable semantic partitioning is set to 1.

Can anyone please suggest how to eliminate unnecessary partition scan?

Body:
On possible solution is that the database setting

basic_optimization_partitions

is switched off. Check if this setting is disabled and if the partition pruning works when this is switched on.


问:
PHP - Is dynamic CSS/JS cached by browsers?
I'm including javascript generated by php for each page, like

Will this be cached by browser, so if you would go on another page some js might not work, because the previous page js is used?

If it is, how could I prevent caching?

答:
You are going to have to modify the HTTP headers to tell the browser not to cache the file.

Take a look at example 1:
http://www.w3schools.com/php/func_http_header.asp


问:
AngularJS: How to render HTML in $scope variable in view?
I have been trying to create a blog app using the MEAN stack. I am having problem to render the posts as HTML. On the browser, it is just showing {{posts}}

HTML code:

```<code><!DOCTYPE html>
<html lang="en" ng-app="BlogApp">
    <head>
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
        <script src="app.js"></script>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
        <div class="container" ng-controller="BlogController">
            <h1>Blog</h1>
            <input ng-model="post.title" class="form-control" placeholder="title"/>
            <textarea ng-model="post.body" class="form-control" placeholder="body"></textarea>
            <button ng-click="createPost(post)" class="btn btn-primary btn-block">Post</button>

            {{posts}}

        </div>
    </body>
</html>
</code>```

Angular code:

```<code>(function() {
    angular.module("BlogApp", []).controller("BlogController", BlogController);
    function BlogController($scope, $http) {
        $scope.createPost=createPost;

        function init() {
            getAllPosts();
        }

        init();

        function getAllPosts() {
            $http.get("/api/blogpost").success(function(posts) {
                $scope.posts=posts;
            });
        }

        function createPost(post) {
            console.log(post);
            $http.post("/api/blogpost", post);
        }
    }
})();
</code>```

答:
Since you are using angular 1.6.x, you have to use .then and .catch instead of .success and .error because the latter are deprecated in newer versions.

```<code>  (function() {
        angular.module("BlogApp", []).controller("BlogController", BlogController);
        function BlogController($scope, $http) {
            $scope.createPost=createPost;

            getAllPosts();

        function getAllPosts() {
                $http.get("/api/blogpost").then(function(response) {
                    $scope.posts=response.data; //check if this is what you are looking for
                });
            }

            function createPost(post) {
                console.log(post);
                $http.post("/api/blogpost", post);
            }
        }
    })();
</code>```

Body:
I have been trying to create a blog app using the MEAN stack. I am having problem to render the posts as HTML. On the browser, it is just showing {{posts}}

HTML code:

<!DOCTYPE html>

        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>

Blog

            <input ng-model="post.title" class="form-control" placeholder="title"/>
            <textarea ng-model="post.body" class="form-control" placeholder="body"></textarea>
            <button ng-click="createPost(post)" class="btn btn-primary btn-block">Post</button>

            {{posts}}

Angular code:

(function() {
    angular.module("BlogApp", []).controller("BlogController", BlogController);
    function BlogController($scope, $http) {
        $scope.createPost=createPost;

        function init() {
            getAllPosts();
        }

        init();

        function getAllPosts() {
            $http.get("/api/blogpost").success(function(posts) {
                $scope.posts=posts;
            });
        }

        function createPost(post) {
            console.log(post);
            $http.post("/api/blogpost", post);
        }
    }
})();

Body:
Since you are using angular 1.6.x, you have to use .then and .catch instead of .success and .error because the latter are deprecated in newer versions.

  (function() {
        angular.module("BlogApp", []).controller("BlogController", BlogController);
        function BlogController($scope, $http) {
            $scope.createPost=createPost;

            getAllPosts();

        function getAllPosts() {
                $http.get("/api/blogpost").then(function(response) {
                    $scope.posts=response.data; //check if this is what you are looking for
                });
            }

            function createPost(post) {
                console.log(post);
                $http.post("/api/blogpost", post);
            }
        }
    })();


问:
Spring Boot resource handler patterns for single page applications
I have the following in my Spring Boot configuration:

```<code>@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.setOrder(Ordered.HIGHEST_PRECEDENCE)
            .addResourceHandler("**/*.*")
            .addResourceLocations("file:static/");
}
</code>```

Since I'm creating a single page app I want this resource handler to deliver static files if the following is true:

URL does not start with /api

This resource handler contains a file that matches the path from the URL

If there are no matching file, the resource handler should not respond with 404 but let the call through to the controllers of the project.

In one of them I place my fallback to index.html annotation (again unless the URL starts with /api):

```<code>@GetMapping({"/**", "/"})
</code>```

This last part works fine but the problem is that the resource handler returns a 404 if there are no matching files instead of letting the call through (I'm used to the middleware patterns of Node.js and Go) to the controllers. How can I achieve this? Can I create my own resource handler that acts more middleware like?

In Go with Echo for example you just need to enable HTML5 with a skipper function for /api:

```<code>func main() {
    server := echo.New()

    server.Use(middleware.Static("static"))
    server.Use(middleware.StaticWithConfig(middleware.StaticConfig{
        Root:    "static",
        HTML5:   true,
        Skipper: noHTML5IfAPICallSkipper,
    }))

    server.Logger.Fatal(server.Start(":1323"))
}

func noHTML5IfAPICallSkipper(context echo.Context) bool {
    if strings.HasPrefix(context.Path(), "/api/") {
        return true
    }

    return false
}
</code>```

How to enable this single page app routing patterns in Spring Boot?

Oh, and by the way, it's crucial that the static files are served from disk rather than from a classpath or anything else that is packaged inside a jar. This service will run with Docker and it has to be possible to mount the files from outside the container.

答:
Try with this:

```<code>public class Application  extends WebMvcConfigurerAdapter { // or implements WebMvcConfigurer (Spring Boot 2)

    @Value("${static.path}")
    private String staticPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
         registry.addResourceHandler("/**/*.*").addResourceLocations("file:"+staticPath);
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("/index.html");
    }

    ...
}
</code>```

You must to add to application.properties file the line:

```<code>`static.path=path/to/static/content`
</code>```

If you want to use Docker, this path need to reference to internal docker container directory, an example: /opt/app/statics and then, map the external path to this:

You must to add to application.properties file the line: static.path=/opt/app/statics

And execute docker like this:

docker run ... -v /absolute/static/path/at/host:/opt/app/statics image:version

Body:
I have the following in my Spring Boot configuration:

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.setOrder(Ordered.HIGHEST_PRECEDENCE)
            .addResourceHandler("**/*.*")
            .addResourceLocations("file:static/");
}

Since I'm creating a single page app I want this resource handler to deliver static files if the following is true:

URL does not start with /api

This resource handler contains a file that matches the path from the URL

If there are no matching file, the resource handler should not respond with 404 but let the call through to the controllers of the project.

In one of them I place my fallback to index.html annotation (again unless the URL starts with /api):

@GetMapping({"/**", "/"})

This last part works fine but the problem is that the resource handler returns a 404 if there are no matching files instead of letting the call through (I'm used to the middleware patterns of Node.js and Go) to the controllers. How can I achieve this? Can I create my own resource handler that acts more middleware like?

In Go with Echo for example you just need to enable HTML5 with a skipper function for /api:

func main() {
    server := echo.New()

    server.Use(middleware.Static("static"))
    server.Use(middleware.StaticWithConfig(middleware.StaticConfig{
        Root:    "static",
        HTML5:   true,
        Skipper: noHTML5IfAPICallSkipper,
    }))

    server.Logger.Fatal(server.Start(":1323"))
}

func noHTML5IfAPICallSkipper(context echo.Context) bool {
    if strings.HasPrefix(context.Path(), "/api/") {
        return true
    }

    return false
}

How to enable this single page app routing patterns in Spring Boot?

Oh, and by the way, it's crucial that the static files are served from disk rather than from a classpath or anything else that is packaged inside a jar. This service will run with Docker and it has to be possible to mount the files from outside the container.

Body:
Try with this:

public class Application  extends WebMvcConfigurerAdapter { // or implements WebMvcConfigurer (Spring Boot 2)

    @Value("${static.path}")
    private String staticPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
         registry.addResourceHandler("/**/*.*").addResourceLocations("file:"+staticPath);
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("/index.html");
    }

    ...
}

You must to add to application.properties file the line:

`static.path=path/to/static/content`

If you want to use Docker, this path need to reference to internal docker container directory, an example: /opt/app/statics and then, map the external path to this:

You must to add to application.properties file the line: static.path=/opt/app/statics

And execute docker like this:

docker run ... -v /absolute/static/path/at/host:/opt/app/statics image:version


问:
Are NSManagedObject objectIDs unique across space and time like a CFUUID?
The NSManagedObjectID documentation states:

An NSManagedObjectID object is a compact, universal, identifier for a managed object. This forms the basis for uniquing in the Core Data Framework. A managed object ID uniquely identifies the same managed object both between managed object contexts in a single application, and in multiple applications (as in distributed systems).

Translation in my head: "There is probably no way that any two NSManagedObjectIDs are ever the same across the set of all instances of my application."

The CFUUID documentation states:

UUIDs ... are 128-bit values
  guaranteed to be unique. A UUID is
  made unique over both space and time
  by combining a value unique to the
  computer on which it was
  generated—usually the Ethernet
  hardware address—and a value
  representing the number of
  100-nanosecond intervals since October
  15, 1582 at 00:00:00.

Translation in my head: "There is definitely no way that any two CFUUIDs are ever the same across the set of all instances of my application."

The fact that NSManagedObjectIDs are described as a "universal identifier" makes me almost certain that they offer the same uniqueness as a CFUUID, whereas "unique across space and time" leaves absolutely no room for doubt. Can anybody with more Core Data experience than me confirm or deny my thoughts?

答:
Beyond uniqueness, there is one case where the object ID will change, and that's if you query it before persisting the object to disk.  After saving, it will have a different ID.  Beyond that point, the ID will not change.  I just wanted to point this out because it caused me a bit of confusion until I figured out what was happening.

I can't comment on the hashing used to generate the NSManagedObjectID, but it does seem like the odds of it matching another NSManagedObject are vanishingly small, based on looking at the IDs generated.


答:
Your getAllPosts function should use .then instead of .success as .success is deprecated with angular version above 1.3

```<code>  function getAllPosts() {
     $http.get("/api/blogpost").then(function(response) {
         $scope.posts=response.data;
      });
   }
</code>```

Title: AngularJS: How to render HTML in $scope variable in view?

Body:
Your getAllPosts function should use .then instead of .success as .success is deprecated with angular version above 1.3

  function getAllPosts() {
     $http.get("/api/blogpost").then(function(response) {
         $scope.posts=response.data;
      });
   }


问:
HTML Certificate
I need to create an HTML certificate page it should be responsive and the user can print the certificate by clicking ctrl+p which only captures the certificate not other content of the page. Can I get the reference for this? </p>

答: Design certificate with inline CSS. for reference read about "Emailer".

Title: HTML Certificate


问:
Unity Server Camera Set
I'm currently working at a multiplayer server using unity and photon. The problem is when I spawn a character for each player I want to set the LocalCamera for that client on the character attached camera. When I have a player and I spawn the second, in the project there will be 2 active cameras at the same time (my own character camera and the other player's camera) and I don't know how to set the view on my camera. It automatically sets from what I see to the last created one. Please lend me a hand! :)</p>

答:
You could simply create a script and set the camera active within. The only thing you have to check is if the client is the one who created the object.
This could be done with isLocalPlayer from the NetworkBehaviour.

https://docs.unity3d.com/ScriptReference/Networking.NetworkBehaviour-isLocalPlayer.html

```<code>if (!isLocalPlayer)
    {
        return;
    }
this.GetComponent<Camera>().enabled = true;
</code>```

Edit: My bad, this might only be support on the unityNetworking API

Title: Unity Server Camera Set

Body:
You could simply create a script and set the camera active within. The only thing you have to check is if the client is the one who created the object.
This could be done with isLocalPlayer from the NetworkBehaviour.

https://docs.unity3d.com/ScriptReference/Networking.NetworkBehaviour-isLocalPlayer.html

if (!isLocalPlayer)
    {
        return;
    }
this.GetComponent<Camera>().enabled = true;

Edit: My bad, this might only be support on the unityNetworking API


问:
Unexpected EOF in PHP code block
I have a block of code that gives the unexpected EOF (end of file) error. I just can't find it.

$statement = $pdo->prepare($sql);
    $statement->execute([

```<code>        $query = "UPDATE images SET
        `filename`= :filename,
        `display_start_date`= :display_start_date,
        `display_end_date` = :display_end_date,
        `display_delay` = :display_delay;

            $pdoResult =  $pdo->prepare($query);
            $pdoExecute = $pdoResult->execute(
            [
                ':name'               => $imageName,
                ':path'               => $path;
                ':filename'           => $imageFilename,
                ':display_start_date' => $displayStartDate,
                ':display_end_date'   => $displayEndDate,
                ':display_delay'      => $displayDelay,
                ':upload_date'        => date('Y-m-d'),
                ':image_id'           => $imageId)
            ]
            )
        }
</code>```

More PHP comes after this so I do not need a ?>.

Thanks in advance.

答:
are you closing the quotes for this line?
<code>$query = "UPDATE images SET
</code></p>

```<code>    $query = "UPDATE images SET
    `filename`= :filename,
    `display_start_date`= :display_start_date,
    `display_end_date` = :display_end_date,
    `display_delay` = :display_delay";
</code>```

Title: Unexpected EOF in PHP code block

Body:
I have a block of code that gives the unexpected EOF (end of file) error. I just can't find it.

$statement = $pdo->prepare($sql);
    $statement->execute([

        $query = "UPDATE images SET
        `filename`= :filename,
        `display_start_date`= :display_start_date,
        `display_end_date` = :display_end_date,
        `display_delay` = :display_delay;

            $pdoResult =  $pdo->prepare($query);
            $pdoExecute = $pdoResult->execute(
            [
                ':name'               => $imageName,
                ':path'               => $path;
                ':filename'           => $imageFilename,
                ':display_start_date' => $displayStartDate,
                ':display_end_date'   => $displayEndDate,
                ':display_delay'      => $displayDelay,
                ':upload_date'        => date('Y-m-d'),
                ':image_id'           => $imageId)
            ]
            )
        }

More PHP comes after this so I do not need a ?>.

Thanks in advance.

Body:
are you closing the quotes for this line?
$query = "UPDATE images SET

    $query = "UPDATE images SET
    `filename`= :filename,
    `display_start_date`= :display_start_date,
    `display_end_date` = :display_end_date,
    `display_delay` = :display_delay";