答:
```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_splash"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.myproject.SplashActivity"
    android:orientation="horizontal"
    android:background="@drawable/my_image_background">
     <ImageView
         android:scaleType="fitXY"
         android:src="@drawable/my_image_background"
         android:layout_width="match_parent"
         android:layout_height="match_parent"/>
</LinearLayout>
</code>```

Use ImageView and use attribute scaleType .This would automatically fit any screen resolution.

----- Update -------

As suggested by Ahamed Other than that if you want to add more Views into the layout , Its better to use RelativeLayout ( Since it would stack your views ).Consider the below implementation of RelativeLayout.

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_splash"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
         <ImageView
             android:scaleType="fitXY"
             android:src="@drawable/my_image_background"
             android:layout_width="match_parent"
             android:layout_height="match_parent"/>
          <!-- Add other views depending on your screen specs -->
    </RelativeLayout>
</code>```

Body:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_splash"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.myproject.SplashActivity"
    android:orientation="horizontal"
    android:background="@drawable/my_image_background">
     <ImageView
         android:scaleType="fitXY"
         android:src="@drawable/my_image_background"
         android:layout_width="match_parent"
         android:layout_height="match_parent"/>
</LinearLayout>

Use ImageView and use attribute scaleType .This would automatically fit any screen resolution.

----- Update -------

As suggested by Ahamed Other than that if you want to add more Views into the layout , Its better to use RelativeLayout ( Since it would stack your views ).Consider the below implementation of RelativeLayout.

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_splash"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
         <ImageView
             android:scaleType="fitXY"
             android:src="@drawable/my_image_background"
             android:layout_width="match_parent"
             android:layout_height="match_parent"/>
          <!-- Add other views depending on your screen specs -->
    </RelativeLayout>


来源: stackexchange

问:
jQuery Ajax clicks doesn't work unless page is refreshed
I've been messing around with some JS and ajax in my PHP project and I am facing some problems. The ajax only seems to work when the page is refreshed after clicking or just refresh to click. I'm using jquery 3.2.1.

I was first using .live() but that is deprecated now and I read that .on() is an alternative so I am using that now.

This is my JS part:

```<code>  $(".up_vote").on("click", function() {
    var post_id = $(this).attr('postid');
    $.ajax({
      type: "POST",
      data: {
        'post_id': post_id,
        'action': 'upvote'
      },
      url: '<?php echo $url; ?>/includes/functions.php',
      dataType: 'json',
      success: function(response) {
        if (response.ResponseCode == 200) {
          $('#postbox_' + post_id).load('<?php echo $url; ?>/index.php #postbox_' + post_id + ' >*');
        } else {
          alert(response.Message);
        }
      }
    });
  });

  $(".down_vote").on("click", function() {
    var post_id = $(this).attr('postid');
    $.ajax({
      type: "POST",
      data: {
        'post_id': post_id,
        'action': 'downvote'
      },
      url: '<?php echo $url; ?>/includes/functions.php',
      dataType: 'json',
      success: function(response) {
        if (response.ResponseCode == 200) {
          $('#postbox_' + post_id).load('<?php echo $url; ?>/index.php #postbox_' + post_id + ' >*');
        } else {
          alert(response.Message);
        }
      }
    });
  });

  $("#btnpost").click(function() {
    var post = $("#post_feed").val();
    if (post == "") {
      alert("This can't be empty.");
      return false;
    } else {
      $.ajax({
        type: "POST",
        data: {
          'post_feed': post,
          'action': 'post'
        },
        url: '<?php echo $url; ?>/includes/functions.php',
        dataType: 'json',
        success: function(response) {
          if (response.ResponseCode == 200) {
            $("#post_feed").val("");
            $('#feed_div').load('<?php echo $url; ?>/index.php #feed_div');
          } else {
            alert(response.Message);
          }
        }
      });
    }
  });
});
</code>```

Is there anything I am missing or done wrong?

答:
First make sure you're hitting the target, try this and see if the alert shows :

```<code>$(function() {
    $(document).on('click', '.up_vote', function() {
       alert('ok');
    });
});
</code>```

Click event is attached to existing elements on page load. The key word here is “existing”. When we load something with ajax we manipulate DOM. We are placing totally new element. So what we need to do is to attach that event after placing new content.

so to attach event everytime ajax is called we use .on

edit your code accordingly

```<code>  $(document).on('click', '.up_vote', function() {
    var post_id = $(this).attr('postid');
    $.ajax({
      type: "POST",
      data: {
        'post_id': post_id,
        'action': 'upvote'
      },
      url: '<?php echo $url; ?>/includes/functions.php',
      dataType: 'json',
      success: function(response) {
        if (response.ResponseCode == 200) {
          $('#postbox_' + post_id).load('<?php echo $url; ?>/index.php #postbox_' + post_id + ' >*');
        } else {
          alert(response.Message);
        }
      }
    });
  });

  $(document).on('click', '.down_vote', function() {
    var post_id = $(this).attr('postid');
    $.ajax({
      type: "POST",
      data: {
        'post_id': post_id,
        'action': 'downvote'
      },
      url: '<?php echo $url; ?>/includes/functions.php',
      dataType: 'json',
      success: function(response) {
        if (response.ResponseCode == 200) {
          $('#postbox_' + post_id).load('<?php echo $url; ?>/index.php #postbox_' + post_id + ' >*');
        } else {
          alert(response.Message);
        }
      }
    });
  });

  $(document).on('click', '#btnpost', function() {
    var post = $("#post_feed").val();
    if (post == "") {
      alert("This can't be empty.");
      return false;
    } else {
      $.ajax({
        type: "POST",
        data: {
          'post_feed': post,
          'action': 'post'
        },
        url: '<?php echo $url; ?>/includes/functions.php',
        dataType: 'json',
        success: function(response) {
          if (response.ResponseCode == 200) {
            $("#post_feed").val("");
            $('#feed_div').load('<?php echo $url; ?>/index.php #feed_div');
          } else {
            alert(response.Message);
          }
        }
      });
    }
  });
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've been messing around with some JS and ajax in my PHP project and I am facing some problems. The ajax only seems to work when the page is refreshed after clicking or just refresh to click. I'm using jquery 3.2.1.

I was first using .live() but that is deprecated now and I read that .on() is an alternative so I am using that now.

This is my JS part:

  $(".up_vote").on("click", function() {
    var post_id = $(this).attr('postid');
    $.ajax({
      type: "POST",
      data: {
        'post_id': post_id,
        'action': 'upvote'
      },
      url: '<?php echo $url; ?>/includes/functions.php',
      dataType: 'json',
      success: function(response) {
        if (response.ResponseCode == 200) {
          $('#postbox_' + post_id).load('<?php echo $url; ?>/index.php #postbox_' + post_id + ' >*');
        } else {
          alert(response.Message);
        }
      }
    });
  });

  $(".down_vote").on("click", function() {
    var post_id = $(this).attr('postid');
    $.ajax({
      type: "POST",
      data: {
        'post_id': post_id,
        'action': 'downvote'
      },
      url: '<?php echo $url; ?>/includes/functions.php',
      dataType: 'json',
      success: function(response) {
        if (response.ResponseCode == 200) {
          $('#postbox_' + post_id).load('<?php echo $url; ?>/index.php #postbox_' + post_id + ' >*');
        } else {
          alert(response.Message);
        }
      }
    });
  });

  $("#btnpost").click(function() {
    var post = $("#post_feed").val();
    if (post == "") {
      alert("This can't be empty.");
      return false;
    } else {
      $.ajax({
        type: "POST",
        data: {
          'post_feed': post,
          'action': 'post'
        },
        url: '<?php echo $url; ?>/includes/functions.php',
        dataType: 'json',
        success: function(response) {
          if (response.ResponseCode == 200) {
            $("#post_feed").val("");
            $('#feed_div').load('<?php echo $url; ?>/index.php #feed_div');
          } else {
            alert(response.Message);
          }
        }
      });
    }
  });
});

Is there anything I am missing or done wrong?

Body:
First make sure you're hitting the target, try this and see if the alert shows :

$(function() {
    $(document).on('click', '.up_vote', function() {
       alert('ok');
    });
});

Click event is attached to existing elements on page load. The key word here is “existing”. When we load something with ajax we manipulate DOM. We are placing totally new element. So what we need to do is to attach that event after placing new content.

so to attach event everytime ajax is called we use .on

edit your code accordingly

  $(document).on('click', '.up_vote', function() {
    var post_id = $(this).attr('postid');
    $.ajax({
      type: "POST",
      data: {
        'post_id': post_id,
        'action': 'upvote'
      },
      url: '<?php echo $url; ?>/includes/functions.php',
      dataType: 'json',
      success: function(response) {
        if (response.ResponseCode == 200) {
          $('#postbox_' + post_id).load('<?php echo $url; ?>/index.php #postbox_' + post_id + ' >*');
        } else {
          alert(response.Message);
        }
      }
    });
  });

  $(document).on('click', '.down_vote', function() {
    var post_id = $(this).attr('postid');
    $.ajax({
      type: "POST",
      data: {
        'post_id': post_id,
        'action': 'downvote'
      },
      url: '<?php echo $url; ?>/includes/functions.php',
      dataType: 'json',
      success: function(response) {
        if (response.ResponseCode == 200) {
          $('#postbox_' + post_id).load('<?php echo $url; ?>/index.php #postbox_' + post_id + ' >*');
        } else {
          alert(response.Message);
        }
      }
    });
  });

  $(document).on('click', '#btnpost', function() {
    var post = $("#post_feed").val();
    if (post == "") {
      alert("This can't be empty.");
      return false;
    } else {
      $.ajax({
        type: "POST",
        data: {
          'post_feed': post,
          'action': 'post'
        },
        url: '<?php echo $url; ?>/includes/functions.php',
        dataType: 'json',
        success: function(response) {
          if (response.ResponseCode == 200) {
            $("#post_feed").val("");
            $('#feed_div').load('<?php echo $url; ?>/index.php #feed_div');
          } else {
            alert(response.Message);
          }
        }
      });
    }
  });
});


问:
How to inject an ASP.MVC DLL file at runtime and calls it's actions?
I am working on a CMS and I need to make it modular. so I've created a simple controller named TestController that contains an action named Index.

How can I inject that DLL file into the main project at runtime and render Index action of TestController at runtime?

答:
Html.Action returns MvcHtmlString, so you should be able to just do:

```<code>var html = Html.Action("MyAwesomeAction", new { foo = "bar" });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Html.Action returns MvcHtmlString, so you should be able to just do:

var html = Html.Action("MyAwesomeAction", new { foo = "bar" });


问:
Xaml Parse Exception - type mismatch between "Xamarin.Forms.Binding" and "System.Collections.Generic.IEnumerable`1[System.String]"
I am trying to set/bind a list property in a content view class in xaml.

This is my Class :

```<code>public class Myclass:ContentView
{
public static readonly BindableProperty TabItemSourceProperty = BindableProperty.Create(
            "TabIndicatorItemSource",
            typeof(IEnumerable<string>),
            typeof(Myclass)
        );

public IEnumerable<string> TabIndicatorItemSource {
get
{
    return (IEnumerable<string>)GetValue(TabItemSourceProperty);
}
set
{
    SetValue(TabItemSourceProperty, value);
}
}}
</code>```

and This is my Xaml in ExampleClass.xaml.cs

```<code>local:Myclass x:Name="myCarouselView" TabTextSizeTabIndicatorItemSource ="{Binding tabListSource}"
</code>```

And tabListSource is a List property in ExampleClass.cs.

However I get this type mismatch error. Where am I going wrong?

答:
Bindable Properties need to adhere to a set naming convention. e.g. TabItemSourceProperty relates to TabItemSource

```<code>public class Myclass: ContentView
{
    public static readonly BindableProperty TabItemSourceProperty = BindableProperty.Create(
            "TabItemSource",
            typeof(IEnumerable<string>),
            typeof(Myclass)
        );

    public IEnumerable<string> TabItemSource {
        get
        {
             return (IEnumerable<string>)GetValue(TabItemSourceProperty);
        }
        set
        {
            SetValue(TabItemSourceProperty, value);
        }
    }}
</code>```

with

```<code>local:Myclass x:Name="myCarouselView" TabItemSource="{Binding tabListSource}"
</code>```

Body:
I am trying to set/bind a list property in a content view class in xaml.

This is my Class :

public class Myclass:ContentView
{
public static readonly BindableProperty TabItemSourceProperty = BindableProperty.Create(
            "TabIndicatorItemSource",
            typeof(IEnumerable<string>),
            typeof(Myclass)
        );

public IEnumerable<string> TabIndicatorItemSource {
get
{
    return (IEnumerable<string>)GetValue(TabItemSourceProperty);
}
set
{
    SetValue(TabItemSourceProperty, value);
}
}}

and This is my Xaml in ExampleClass.xaml.cs

local:Myclass x:Name="myCarouselView" TabTextSizeTabIndicatorItemSource ="{Binding tabListSource}"

And tabListSource is a List property in ExampleClass.cs.

However I get this type mismatch error. Where am I going wrong?

Body:
Bindable Properties need to adhere to a set naming convention. e.g. TabItemSourceProperty relates to TabItemSource

public class Myclass: ContentView
{
    public static readonly BindableProperty TabItemSourceProperty = BindableProperty.Create(
            "TabItemSource",
            typeof(IEnumerable<string>),
            typeof(Myclass)
        );

    public IEnumerable<string> TabItemSource {
        get
        {
             return (IEnumerable<string>)GetValue(TabItemSourceProperty);
        }
        set
        {
            SetValue(TabItemSourceProperty, value);
        }
    }}

with

local:Myclass x:Name="myCarouselView" TabItemSource="{Binding tabListSource}"


问:
Cordova - Error code 1 for command | Command failed for
I'm new on cordova, so if my question is not relevant, forgive me.
i have a cordova project in my Windows 7 x64 machine.
Yesterday i was build my cordova app via cordova build android --release.
But i need to add new plugin cordova-plugin-zip to update my cordova project.
What i did to add this plugin to my cordova app;

I installed a git application to my win7 x64 env.

npm install -g git i wrote this command on cmd.

I Opened Windows Environment Variables/Path Window and added ;C:\Program Files (x86)\Git\bin;C:\Program Files (x86)\Git\cmd

add plugin via this command cordova plugin add https://github.com/apache/cordova-plugin-file.git

then added other plugin cordova plugin add https://github.com/MobileChromeApps/zip.git
(Everything fine till this step)

Then i run on cmd cordova build android --release

Unfourtunately it throws following error;

BUILD FAILED C:\android\sdk\tools\ant\build.xml:720: The following
  error occurred while execu ting this line:
  C:\android\sdk\tools\ant\build.xml:734: Compile failed; see the
  compiler error o utput for details.

Total time: 7 seconds

C:\hascevher\platforms\android\cordova\node_modules\q\q.js:126
                      throw e;
                            ^ Error code 1 for command: cmd with args: /s,/c,ant,release,-f,C:\hascevher\platf
  orms\android\build.xml,-Dout.dir=ant-build,-Dgen.absolute.dir=ant-gen
  ERROR building one of the platforms: Error: cmd: Command failed with
  exit code 1

You may not have the required environment or OS to build this project
  Error: cmd: Command failed with exit code 1
      at ChildProcess.whenDone (C:\Users\Hddn\AppData\Roaming\npm\node_modules\cor
  dova\node_modules\cordova-lib\src\cordova\superspawn.js:134:23)
      at ChildProcess.emit (events.js:110:17)
      at maybeClose (child_process.js:1015:16)
      at Process.ChildProcess._handle.onexit (child_process.js:1087:5)

When i try to create a new helloworld cordova project and adding android platform then from cmd cordova build android it creates sample app?

So what is wrong with my other application?

Any help greatly appricated.

OS: Windows 7 x64

Cordova v 5.1.1

Ant version 1.9.4

Plugins On Cordova Project:

cordova-plugin-file

cordova-plugin-zip

org.apache.cordova.console

org.apache.cordova.device

org.apache.cordova.inappbrowser

Full Windows Environment Variables/Path:

C:\ProgramData\Oracle\Java\javapath;C:\Program Files\Common
  Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Common
  Files\Microsoft Shared\Windows
  Live;%C_EM64T_REDIST11%bin\Intel64;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program
  Files (x86)\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files
  (x86)\Windows Live\Shared;C:\Program Files
  (x86)\QuickTime\QTSystem\;C:\Program Files
  (x86)\Java\jdk1.7.0_75\bin;C:\cordova\apache-ant-1.9.4\bin;C:\android\sdk\tools;C:\android\sdk\platform-tools;C:\Program
  Files\nodejs\;C:\Program Files (x86)\Git\bin;C:\Program Files
  (x86)\Git\cmd

答:
Delete all the apk files from platfroms >> android >> build >> generated >> outputs >> apk
 and run command cordova run android


问:
Splash Screen image background in LinearLayout not fit
I used an image as a background of LinearLayout in splash screen activity but it show not fit for the screen. I don't know how to use attribute for it to stretching it.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_splash"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.myproject.SplashActivity"
    android:orientation="horizontal"
    android:background="@drawable/my_image_background">

</LinearLayout>
</code>```

答:
Better to use ImageView for image, so I have changed your layout as below & it shoul work as you expect.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_splash"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context="com.myproject.SplashActivity">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitXY"
        android:src="@drawable/my_image_background" />

</LinearLayout>
</code>```

Body:
I used an image as a background of LinearLayout in splash screen activity but it show not fit for the screen. I don't know how to use attribute for it to stretching it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_splash"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.myproject.SplashActivity"
    android:orientation="horizontal"
    android:background="@drawable/my_image_background">

</LinearLayout>

Body:
Better to use ImageView for image, so I have changed your layout as below & it shoul work as you expect.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_splash"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context="com.myproject.SplashActivity">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitXY"
        android:src="@drawable/my_image_background" />

</LinearLayout>


问:
how to attach multiple files to email client in android
I am using Intent .ACTION_SEND to get default email client. It works fine but now  i need to attach more than one file to email.

email.putExtra(android.content.Intent.EXTRA_STREAM,...) attaches only last uri added to it.

So can I attach multiple files? I think this can be done by using Intent.ACTION_SEND_MULTIPLE. Here is the code I am trying:

```<code>String uri=getScreenShot();

Intent email = new Intent(android.content.Intent.ACTION_SEND);
            email.setType("application/octet-stream");
            email.putExtra(Intent.EXTRA_STREAM, Uri.parse(uri));
            email.putExtra(android.content.Intent.EXTRA_STREAM, Uri.parse("file:"+csvpath));
            alert.dismiss();
            ctx.startActivity(Intent.createChooser(email, "Send mail..."));
</code>```

Thanks in advance.

答:
Worked For Me</p>

```<code> Intent emailIntent=new Intent(Intent.ACTION_SEND_MULTIPLE, Uri.parse("mailto:"+ clientEmail));
                emailIntent.putExtra(Intent.EXTRA_SUBJECT,"working-tutor-form From App");
                emailIntent.setType("text/plain");
                Uri uri1 = Uri.parse("file://" +  URI1);
                Uri uri2 = Uri.parse("file://" +  URI2);
                Uri uri3 = Uri.parse("file://" +  URI3);
                ArrayList<Uri> arrayList=new ArrayList<Uri>();
                arrayList.add(uri1);
                arrayList.add(uri2);
                arrayList.add(uri3);
                emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM,arrayList);

                emailIntent.putExtra(Intent.EXTRA_TEXT,body);
                startActivity(Intent.createChooser(emailIntent,"Send Via..."));
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am using Intent .ACTION_SEND to get default email client. It works fine but now  i need to attach more than one file to email.

email.putExtra(android.content.Intent.EXTRA_STREAM,...) attaches only last uri added to it.

So can I attach multiple files? I think this can be done by using Intent.ACTION_SEND_MULTIPLE. Here is the code I am trying:

String uri=getScreenShot();

Intent email = new Intent(android.content.Intent.ACTION_SEND);
            email.setType("application/octet-stream");
            email.putExtra(Intent.EXTRA_STREAM, Uri.parse(uri));
            email.putExtra(android.content.Intent.EXTRA_STREAM, Uri.parse("file:"+csvpath));
            alert.dismiss();
            ctx.startActivity(Intent.createChooser(email, "Send mail..."));

Thanks in advance.

Body:
Worked For Me

 Intent emailIntent=new Intent(Intent.ACTION_SEND_MULTIPLE, Uri.parse("mailto:"+ clientEmail));
                emailIntent.putExtra(Intent.EXTRA_SUBJECT,"working-tutor-form From App");
                emailIntent.setType("text/plain");
                Uri uri1 = Uri.parse("file://" +  URI1);
                Uri uri2 = Uri.parse("file://" +  URI2);
                Uri uri3 = Uri.parse("file://" +  URI3);
                ArrayList<Uri> arrayList=new ArrayList<Uri>();
                arrayList.add(uri1);
                arrayList.add(uri2);
                arrayList.add(uri3);
                emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM,arrayList);

                emailIntent.putExtra(Intent.EXTRA_TEXT,body);
                startActivity(Intent.createChooser(emailIntent,"Send Via..."));


问:
Annotation box does not appear in matplotlib
The planned annotation box does not appear on my plot, however, I've tried a wide range of values for its coordinates.

What's wrong with that?!

```<code>import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt

def f(s,t):
    a = 0.7
    b = 0.8
    Iext= 0.5
    tau = 12.5
    v = s[0]
    w = s[1]
    dndt = v - np.power(v,3)/3 - w + Iext
    dwdt = (v + a - b * w)/tau
    return [dndt, dwdt]

t = np.linspace(0,200)
s0=[1,1]

s = odeint(f,s0,t)

plt.plot(t,s[:,0],'b-', linewidth=1.0)
plt.xlabel(r"$t(sec.)$")
plt.ylabel(r"$V (volt)$")
plt.legend([r"$V$"])

annotation_string = r"$I_{ext}=0.5$"
plt.text(15, 60, annotation_string, bbox=dict(facecolor='red', alpha=0.5))

plt.show()
</code>```

答:
The annotation is appearing far above your plot because you have given a 'y' coordinate of 60, whereas your plot ends at '2' (upwards).

Change the second argument here:

```<code>plt.text(15, 60, annotation_string, bbox=dict(facecolor='red', alpha=0.5))
</code>```

It needs to be <=2 to show up on the plot itself. You may also want to change the x coorinate (from 15 to something less), so that it doesn't obscure your lines.

e.g.

```<code>plt.text(5, 1.5, annotation_string, bbox=dict(facecolor='red', alpha=0.5))
</code>```

Don't be alarmed by my (5,1.5) suggestion, I would then add the following line to the top of your script (beneath your imports):

```<code>rcParams['legend.loc'] = 'best'
</code>```

This will choose a 'best fit' for your legend; in this case, top left (just above your annotation). Both look quite neat then, your choice though :)

Body:
The planned annotation box does not appear on my plot, however, I've tried a wide range of values for its coordinates.

What's wrong with that?!

import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt

def f(s,t):
    a = 0.7
    b = 0.8
    Iext= 0.5
    tau = 12.5
    v = s[0]
    w = s[1]
    dndt = v - np.power(v,3)/3 - w + Iext
    dwdt = (v + a - b * w)/tau
    return [dndt, dwdt]

t = np.linspace(0,200)
s0=[1,1]

s = odeint(f,s0,t)

plt.plot(t,s[:,0],'b-', linewidth=1.0)
plt.xlabel(r"$t(sec.)$")
plt.ylabel(r"$V (volt)$")
plt.legend([r"$V$"])

annotation_string = r"$I_{ext}=0.5$"
plt.text(15, 60, annotation_string, bbox=dict(facecolor='red', alpha=0.5))

plt.show()

Body:
The annotation is appearing far above your plot because you have given a 'y' coordinate of 60, whereas your plot ends at '2' (upwards).

Change the second argument here:

plt.text(15, 60, annotation_string, bbox=dict(facecolor='red', alpha=0.5))

It needs to be <=2 to show up on the plot itself. You may also want to change the x coorinate (from 15 to something less), so that it doesn't obscure your lines.

e.g.

plt.text(5, 1.5, annotation_string, bbox=dict(facecolor='red', alpha=0.5))

Don't be alarmed by my (5,1.5) suggestion, I would then add the following line to the top of your script (beneath your imports):

rcParams['legend.loc'] = 'best'

This will choose a 'best fit' for your legend; in this case, top left (just above your annotation). Both look quite neat then, your choice though :)


问:
Rotate frame but not image
I want to rotate a frame but not the image inside it. Here is a JSFiddle that does the rotation but the image still moves. How can I keep the image stationary but move the frame only.

https://jsfiddle.net/q6n2w4qm/2/

HTML:

```<code><body>
<div class="center">
<div class="hexagon">
<div class="hexagon-in1">
<div class="hexagon-in2">

</div></div>
</div>
</div>

</body>
</code>```

CSS:

```<code>.center{
  width: 200px;
  margin: auto;
  margin-top: -50px;
}
.hexagon{
  width: 200px;
  height: 400px;
  overflow: hidden;
  visibility: hidden;
  transform: rotate(120deg);
  cursor: pointer;
  -moz-transition: all 1s ease-in-out;
  -webkit-transition: all 1s ease-in-out;
  -o-transition: all 1s ease-in-out;
  transition: all 1s ease-in-out;
}
.hexagon-in1{
  overflow: hidden;
  width: 100%;
  height: 100%;
  transform: rotate(-60deg);
}
.hexagon-in2{
  width: 100%;
  height: 100%;
  visibility: visible;
  transform: rotate(-60deg);
  background: url('http://lorempixel.com/g/250/350/city');
  repeat: no-repeat;
  position: relative;

}

.hexagon:hover{
  -ms-transform: rotate(150deg); /* IE 9 */
   -webkit-transform: rotate(150deg); /* Chrome, Safari, Opera */
   transform: rotate(150deg);
}
</code>```

答:
1) PNG pseudo-mask overlay

I created a simple HTML/CSS solution, but is only possible with the following three criteria:

The background color behind the image is a solid color

There is enough margin on all sides of the image

You have Photoshop or some comparable image editing software

Working Example

body {
  background-color:#222222;
}

.hex-hack {
  position:relative;
  top:0;
  left:0;
}
.base-image {
  position:relative;
  top:0;
  left:0;
  z-index:1;
  margin: 84px;
}

.hex-overlay {
  position:absolute;
  width:568px;
  height:568px;
  top:0px;
  left:0px;
  z-index:3;
  -moz-transition: all 1s ease-in-out;
  -webkit-transition: all 1s ease-in-out;
  -o-transition: all 1s ease-in-out;
  transition: all 1s ease-in-out;
}

.hex-overlay:hover {
   -ms-transform: rotate(30deg); /* IE 9 */
   -webkit-transform: rotate(30deg); /* Chrome, Safari, Opera */
   transform: rotate(30deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="hex-hack">
    <img class="base-image" src="https://lorempixel.com/output/technics-q-g-400-400-2.jpg" alt="" />
    <img class="hex-overlay" src="https://i.imgur.com/zYa31Tw.png" alt="" />
  </div>
</body></code>```

Note that the margin of the top image is half of the difference between the widths of the bottom image and the top image to keep it centered.

How I Made the Hexagon Mask in Photoshop

I started with a 400 by 400 image on a 800 by 800 canvas and created a perfect circle around the image so that each corner pixel of the image touched the circle. I cropped the canvas down to the width of the circle (568px). The purpose of this is to guarantee that the image is completely covered as the hexagon mask rotates.

Next, I had to create a 350 by 400 hexagon with no fill, rotate it 30 degrees, and center it in the middle of the canvas. Then I selected the hexagon's pixels (ctrl + click the hexagon layer), inverted the selection (shift + ctrl + I), and filled a new layer with the #222222 background color. I hid every other layer and saved it as a png.

2) CSS clip-path and animate

Another possible solution for you to consider is to use CSS to animate an image's clipping path via the clip-path and animate properties. This might be an easier approach, however, the clip-path property is relatively new and doesn't have the greatest browser support - especially with IE, Edge, and Opera. Here are a couple resources to check out:

CSS Masking - Excellent article on the clip-path property (includes animation demo)

Clippy - Great tool for creating CSS clip-paths

3) SVG animation and clipPath

Finally, this is a very browser-friendly solution, but you'll need some software (like Illustrator) to create an SVG from an image. This is also something I have no actual experience with, but I'm positive it can be achieved with a little research, and some trial and error. Here are some resources to get you started.

SVG clipping/masking techniques

Animating SVGs with CSS

Title: Rotate frame but not image

Body:
I want to rotate a frame but not the image inside it. Here is a JSFiddle that does the rotation but the image still moves. How can I keep the image stationary but move the frame only.

https://jsfiddle.net/q6n2w4qm/2/

HTML:

CSS:

.center{
  width: 200px;
  margin: auto;
  margin-top: -50px;
}
.hexagon{
  width: 200px;
  height: 400px;
  overflow: hidden;
  visibility: hidden;
  transform: rotate(120deg);
  cursor: pointer;
  -moz-transition: all 1s ease-in-out;
  -webkit-transition: all 1s ease-in-out;
  -o-transition: all 1s ease-in-out;
  transition: all 1s ease-in-out;
}
.hexagon-in1{
  overflow: hidden;
  width: 100%;
  height: 100%;
  transform: rotate(-60deg);
}
.hexagon-in2{
  width: 100%;
  height: 100%;
  visibility: visible;
  transform: rotate(-60deg);
  background: url('http://lorempixel.com/g/250/350/city');
  repeat: no-repeat;
  position: relative;

}

.hexagon:hover{
  -ms-transform: rotate(150deg); /* IE 9 */
   -webkit-transform: rotate(150deg); /* Chrome, Safari, Opera */
   transform: rotate(150deg);
}

Body:
1) PNG pseudo-mask overlay

I created a simple HTML/CSS solution, but is only possible with the following three criteria:

The background color behind the image is a solid color

There is enough margin on all sides of the image

You have Photoshop or some comparable image editing software

Working Example

body {
  background-color:#222222;
}

.hex-hack {
  position:relative;
  top:0;
  left:0;
}
.base-image {
  position:relative;
  top:0;
  left:0;
  z-index:1;
  margin: 84px;
}

.hex-overlay {
  position:absolute;
  width:568px;
  height:568px;
  top:0px;
  left:0px;
  z-index:3;
  -moz-transition: all 1s ease-in-out;
  -webkit-transition: all 1s ease-in-out;
  -o-transition: all 1s ease-in-out;
  transition: all 1s ease-in-out;
}

.hex-overlay:hover {
   -ms-transform: rotate(30deg); /* IE 9 */
   -webkit-transform: rotate(30deg); /* Chrome, Safari, Opera */
   transform: rotate(30deg);
}

<body>
  <div class="hex-hack">
    <img class="base-image" src="https://lorempixel.com/output/technics-q-g-400-400-2.jpg" alt="" />
    <img class="hex-overlay" src="https://i.imgur.com/zYa31Tw.png" alt="" />
  </div>
</body>

Note that the margin of the top image is half of the difference between the widths of the bottom image and the top image to keep it centered.

How I Made the Hexagon Mask in Photoshop

I started with a 400 by 400 image on a 800 by 800 canvas and created a perfect circle around the image so that each corner pixel of the image touched the circle. I cropped the canvas down to the width of the circle (568px). The purpose of this is to guarantee that the image is completely covered as the hexagon mask rotates.

Next, I had to create a 350 by 400 hexagon with no fill, rotate it 30 degrees, and center it in the middle of the canvas. Then I selected the hexagon's pixels (ctrl + click the hexagon layer), inverted the selection (shift + ctrl + I), and filled a new layer with the #222222 background color. I hid every other layer and saved it as a png.

2) CSS clip-path and animate

Another possible solution for you to consider is to use CSS to animate an image's clipping path via the clip-path and animate properties. This might be an easier approach, however, the clip-path property is relatively new and doesn't have the greatest browser support - especially with IE, Edge, and Opera. Here are a couple resources to check out:

CSS Masking - Excellent article on the clip-path property (includes animation demo)

Clippy - Great tool for creating CSS clip-paths

3) SVG animation and clipPath

Finally, this is a very browser-friendly solution, but you'll need some software (like Illustrator) to create an SVG from an image. This is also something I have no actual experience with, but I'm positive it can be achieved with a little research, and some trial and error. Here are some resources to get you started.

SVG clipping/masking techniques

Animating SVGs with CSS


问:
Can a user subscribe for push notification for multiple users, using delegation?
On Exchange/O365,can a single user subscribe for push notifications (using EWS) from a multiple users ?  I know this is possible using impersonation but would like to know if we  can achieve this  using delegation. If yes , what would the request look like ?

Side question: Are there any limits to number of accounts that can be delegated to a single user ?

Thanks

答:
You can but they need to separate subscriptions eg you can't create a single Push subscription that subscribes to folders in different Mailboxes (eg the Inbox in Mailbox 1 and Mailbox 2). You can create a separate Push subscription against any folder in any Mailbox you have access to (eg Subscription 1 subscribes to the Inbox in Mailbox 1 and subscription 2 subscribes to the Inbox in Mailbox 2), and you can create a subscription that subscribes to multiple folders within one mailbox.

Side question: Are there any limits to number of accounts that can be delegated to a single user ?

No but there are throttling restrictions that control how many Mailbox you can connect to concurrently as well as how many you can create subscriptions against https://blogs.msdn.microsoft.com/exchangedev/2011/06/23/exchange-online-throttling-and-limits-faq/ .


问:
ArrayIndexOutOfBoundsException iterating over 2D arrays in Java
Sorry this question can't really be applied to others. I've been looking at it for a couple hours and I still can't see it. It must  be super simple yet I can't find where I'm trying to access something that isnt there. I am getting a

ArrayIndexOutOfBoundsException while iterating over a 9x9 grid.

```<code>public ArrayList<Grid> next9Grids()
{
    ArrayList<Grid> next9 = new ArrayList<Grid>();//list of new Grids

    for(int i = 0; i < values.length; i++){
        for(int j = 0; i < values[i].length; j++){
            if (values[i][j] == 0){//if empty
                for(int next = 1; next <= 9; next++){
                    Grid temp9 = new Grid(this);//need to make another grid for each #
                    temp9.values[i][j] = next; // changes value of empty space to 1->9
                    next9.add(temp9); //add grid to arrayList
                }
                return next9;
            }
        }

    }
    return null;

}
</code>```

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
    at sudoku.Grid.next9Grids(Grid.java:112)    at
  sudoku.Solver.solveRecurse(Solver.java:54)    at
  sudoku.Solver.solveRecurse(Solver.java:56)    at
  sudoku.Solver.solveRecurse(Solver.java:56)

This is the source of the error.(Grid.java:112) is ----> if(values[i][j] ==0){

Another question is Why is an error thrown on line 112 when it's accessing something that the second for loop is first iterating over and not the second for loop?

Anything is greatly appreciated. Thanks for the feedback.

答:
your condition in the nested forloop is wrong. It should be j instead of i

```<code>public ArrayList<Grid> next9Grids()
    {
        ArrayList<Grid> next9 = new ArrayList<Grid>();//list of new Grids

        for(int i = 0; i < values.length; i++){
            for(int j = 0; j < values[i].length; j++){
                if (values[i][j] == 0){//if empty
                    for(int next = 1; next <= 9; next++){
                        Grid temp9 = new Grid(this);//need to make another grid for each #
                        temp9.values[i][j] = next; // changes value of empty space to 1->9
                        next9.add(temp9); //add grid to arrayList
                    }
                    return next9;
                }
            }

        }
        return null;

    }
</code>```

Body:
Sorry this question can't really be applied to others. I've been looking at it for a couple hours and I still can't see it. It must  be super simple yet I can't find where I'm trying to access something that isnt there. I am getting a

ArrayIndexOutOfBoundsException while iterating over a 9x9 grid.

public ArrayList<Grid> next9Grids()
{
    ArrayList<Grid> next9 = new ArrayList<Grid>();//list of new Grids

    for(int i = 0; i < values.length; i++){
        for(int j = 0; i < values[i].length; j++){
            if (values[i][j] == 0){//if empty
                for(int next = 1; next <= 9; next++){
                    Grid temp9 = new Grid(this);//need to make another grid for each #
                    temp9.values[i][j] = next; // changes value of empty space to 1->9
                    next9.add(temp9); //add grid to arrayList
                }
                return next9;
            }
        }

    }
    return null;

}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
    at sudoku.Grid.next9Grids(Grid.java:112)    at
  sudoku.Solver.solveRecurse(Solver.java:54)    at
  sudoku.Solver.solveRecurse(Solver.java:56)    at
  sudoku.Solver.solveRecurse(Solver.java:56)

This is the source of the error.(Grid.java:112) is ----> if(values[i][j] ==0){

Another question is Why is an error thrown on line 112 when it's accessing something that the second for loop is first iterating over and not the second for loop?

Anything is greatly appreciated. Thanks for the feedback.

Body:
your condition in the nested forloop is wrong. It should be j instead of i

public ArrayList<Grid> next9Grids()
    {
        ArrayList<Grid> next9 = new ArrayList<Grid>();//list of new Grids

        for(int i = 0; i < values.length; i++){
            for(int j = 0; j < values[i].length; j++){
                if (values[i][j] == 0){//if empty
                    for(int next = 1; next <= 9; next++){
                        Grid temp9 = new Grid(this);//need to make another grid for each #
                        temp9.values[i][j] = next; // changes value of empty space to 1->9
                        next9.add(temp9); //add grid to arrayList
                    }
                    return next9;
                }
            }

        }
        return null;

    }


问:
I can't create login in django 1.10.1 version
I know it is basic to create login User Authentication. And I am a newbie here in using Django.

I have a problem in creating User Authentication:

Views.py

```<code>def Logins(request):
if request.method == 'POST':
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None and user.is_active:
        login(request, user)
        return HttpResponseRedirect('music/login')
    return HttpResponseRedirect('music/login')
form = Userlogin
return render(request, 'music/login.html', {'Login_form': Userlogin})
</code>```

urls.py
    url(r'^login/$', views.Logins, name='login'),

It shows
    It shows MultiValueDictKeyError at /music/login/.
    "'username'"
    Request Method: POST
    Request URL:    http://127.0.0.1:8000/music/login/
    Django Version: 1.10.4
    Exception Type: MultiValueDictKeyError
    Exception Value:

    "'username'"

login.html

```<code>{% block body %}
{% if form.errors %}
<p>Something is wrong</p>
{% endif %}

<form action="" method="post">
    {% csrf_token %}
    <label for="email">Login:</label>
    <label for="password">Password:</label>
    <input type="password" name="password" value="" id="username">

    <input type="submit" value="login" />

</form>
{% endblock %}
</code>```

Thanks in advance.

答:
request.POST is a dictionary. You should be doing it this way:

```<code>username = request.POST.get('username', None)
password = request.POST.get('password', None)
</code>```

Body:
I know it is basic to create login User Authentication. And I am a newbie here in using Django.

I have a problem in creating User Authentication:

Views.py

def Logins(request):
if request.method == 'POST':
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None and user.is_active:
        login(request, user)
        return HttpResponseRedirect('music/login')
    return HttpResponseRedirect('music/login')
form = Userlogin
return render(request, 'music/login.html', {'Login_form': Userlogin})

urls.py
    url(r'^login/$', views.Logins, name='login'),

It shows
    It shows MultiValueDictKeyError at /music/login/.
    "'username'"
    Request Method: POST
    Request URL:    http://127.0.0.1:8000/music/login/
    Django Version: 1.10.4
    Exception Type: MultiValueDictKeyError
    Exception Value:

    "'username'"

login.html

{% block body %}
{% if form.errors %}

Something is wrong

{% endif %}

<form action="" method="post">
    {% csrf_token %}
    Login:
    Password:
    <input type="password" name="password" value="" id="username">

    <input type="submit" value="login" />

</form>
{% endblock %}

Thanks in advance.

Body:
request.POST is a dictionary. You should be doing it this way:

username = request.POST.get('username', None)
password = request.POST.get('password', None)


问:
JSONException: End of input at character 0
I'm facing the error as given in the logs below. The error says that the return code which is passed is 0. I can successfully receive the OPT via my email and when I enter it and press confirm registration there's the toast error message I get Unable to generate valid response for registration. Try again. I don't understand exactly why this is happening.

Error:

答:
your json response is not correct.

Set response this way:

```<code>{"serviceName":"register",
"emailID":"aditi.shrivastava@allianz.com",
"token":"728962"}
</code>```

Body:
your json response is not correct.

Set response this way:

{"serviceName":"register",
"emailID":"aditi.shrivastava@allianz.com",
"token":"728962"}


问:
Codeigniter Youtube videos is not coming
I try to show a youtube video in my cms project using codeigniter. But its not working.. I insert the youtube url in one table path in my mysql database and i just call that url using codeigniter view area under iframe tag.. But its not showing i check it in the Browser inspect the video url is showing but below of the  tag  this is generated automatically. Can any one help me..

This is my view code..

```<code><div class="container">
        <div class="row">
            <?php foreach($advertisement as $ad) { ?>
          <table>
    <td>
  <iframe src="<?php echo $ad->url?>"
   width="560" height="315" frameborder="0" ></iframe>
   </td>
   </table>

            <?php
            } ?>
     </div>
</div>
</code>```

This is my Controller Code

```<code>  public function advertisement(){
        $data['advertisement'] = $this->modelHome->populateAds();

        $this->load->view('layouts/head',$data);
        $this->load->view('commercial',$data);
        $this->load->view('layouts/footer');
    }
</code>```

This is my modal code

```<code> public function populateAds(){
        $this->db->select('*');
        $this->db->from('advertisement');
        $this->db->where('status','approved');
        $this->db->order_by('id','DESC');
        $query=$this->db->get();
         if ($query->num_rows() > 0) {
            return $query->result();
        }
     }
</code>```

This is my Table

答:
in your model</p>

```<code>public function populateAds(){
        $this->db->select('*');
        $this->db->from('advertisement');
        $this->db->where('status','approve');
        $this->db->order_by('id','DESC');
        $query=$this->db->get();
         if ($query->num_rows() > 0) {
            return $query->result();
        }
     }
</code>```

Body:
I try to show a youtube video in my cms project using codeigniter. But its not working.. I insert the youtube url in one table path in my mysql database and i just call that url using codeigniter view area under iframe tag.. But its not showing i check it in the Browser inspect the video url is showing but below of the  tag  this is generated automatically. Can any one help me..

This is my view code..

            <?php foreach($advertisement as $ad) { ?>

  <iframe src="<?php echo $ad->url?>"
   width="560" height="315" frameborder="0" >

            <?php
            } ?>

This is my Controller Code

  public function advertisement(){
        $data['advertisement'] = $this->modelHome->populateAds();

        $this->load->view('layouts/head',$data);
        $this->load->view('commercial',$data);
        $this->load->view('layouts/footer');
    }

This is my modal code

 public function populateAds(){
        $this->db->select('*');
        $this->db->from('advertisement');
        $this->db->where('status','approved');
        $this->db->order_by('id','DESC');
        $query=$this->db->get();
         if ($query->num_rows() > 0) {
            return $query->result();
        }
     }

This is my Table

Body:
in your model

public function populateAds(){
        $this->db->select('*');
        $this->db->from('advertisement');
        $this->db->where('status','approve');
        $this->db->order_by('id','DESC');
        $query=$this->db->get();
         if ($query->num_rows() > 0) {
            return $query->result();
        }
     }


问:
Find occurence of a word in a sentence
I want to find the occurence of a certain word in a sentence and then remove it. I'm able to do it but sometimes the word I wanna remove can be a subword. For example I wanna find/remove the word "word" in the sentence "Music is worldwide". My program will fin/remove return a positive value that it found the word "word" in the sentence while in fact it encountered the word "worldwide" and I would like it to return a negative value.
I'm currently using

index = text.find(word)```

Is there any other way to avoid this problem of the word being a subword in a sentence ? Thank you in advance!

答:
You can use the regular expression module, and rely on regular expression word boundaries (\b) to only match the complete word.

Since you're trying to remove the word from the sentence, here's an example that replaces all the matches with an empty string:

```<code>import re

sentence = 'Music world is worldwide'
word = 'world'
removed = re.sub(r'\b%s\b' % word, '', sentence)

print removed # prints "Music   is worldwide"
</code>```

If you just want to find the position of the first occurrence, you can do it as follows:

```<code>import re

sentence = 'Music is worldwide in the world'
word = 'world'
match = re.search(r'\b%s\b' % word, sentence)

if match:
    print match.start() # prints 26
</code>```

Check the documentation of the re module for details.

Title: Find occurence of a word in a sentence

Body:
I want to find the occurence of a certain word in a sentence and then remove it. I'm able to do it but sometimes the word I wanna remove can be a subword. For example I wanna find/remove the word "word" in the sentence "Music is worldwide". My program will fin/remove return a positive value that it found the word "word" in the sentence while in fact it encountered the word "worldwide" and I would like it to return a negative value.
I'm currently using

index = text.find(word)

Is there any other way to avoid this problem of the word being a subword in a sentence ? Thank you in advance!

Body:
You can use the regular expression module, and rely on regular expression word boundaries (\b) to only match the complete word.

Since you're trying to remove the word from the sentence, here's an example that replaces all the matches with an empty string:

import re

sentence = 'Music world is worldwide'
word = 'world'
removed = re.sub(r'\b%s\b' % word, '', sentence)

print removed # prints "Music   is worldwide"

If you just want to find the position of the first occurrence, you can do it as follows:

import re

sentence = 'Music is worldwide in the world'
word = 'world'
match = re.search(r'\b%s\b' % word, sentence)

if match:
    print match.start() # prints 26

Check the documentation of the re module for details.


问:
Receive two json objects at once in ajax method jquery
I am trying to return two json objects.But i am able to receive only one. Am i doing wrong? Success is just showing 'success' as string when i try to alert this but otherwise in firebug it has value=true
.So, it must show true which is its value and not the variable instead.

I am returning below in which data is receiving but success is not
showing its value. How should i extract the value of success in
my $.ajax funtion..

```<code> return Json(new { data = obj, success = isSuccess });

$.ajax({
            type: "POST",
            url: "controller/Action",
            data: "",
            success: function (data, success) {
                debugger;
                alert(success);

            },
</code>```

答:
You will get response data as a first argument.

```<code>$.ajax({
    type: "POST",
    url: "controller/Action",
    data: "",
    success: function (response) {
        console.log(response.success);
    }
})
</code>```

Body:
I am trying to return two json objects.But i am able to receive only one. Am i doing wrong? Success is just showing 'success' as string when i try to alert this but otherwise in firebug it has value=true
.So, it must show true which is its value and not the variable instead.

I am returning below in which data is receiving but success is not
showing its value. How should i extract the value of success in
my $.ajax funtion..

 return Json(new { data = obj, success = isSuccess });

$.ajax({
            type: "POST",
            url: "controller/Action",
            data: "",
            success: function (data, success) {
                debugger;
                alert(success);

            },

Body:
You will get response data as a first argument.

$.ajax({
    type: "POST",
    url: "controller/Action",
    data: "",
    success: function (response) {
        console.log(response.success);
    }
})


答:
Try this one :  </p>

```<code>for(int i = 0; i < values.length; i++){
            for(int j = 0; j < values[i].length; j++){// replaced j in (i < values[i].length) by i in (j < values[i].length)
                if (values[i][j] == 0){//if empty
                    for(int next = 1; next <= 9; next++){
</code>```

Title: ArrayIndexOutOfBoundsException iterating over 2D arrays in Java

Body:
Try this one :

for(int i = 0; i < values.length; i++){
            for(int j = 0; j < values[i].length; j++){// replaced j in (i < values[i].length) by i in (j < values[i].length)
                if (values[i][j] == 0){//if empty
                    for(int next = 1; next <= 9; next++){


问:
move a row in google spreadsheet based on todays date
I'm trying to move a row of data from one sheet to another in the same spreadsheet based on a value of today's date.

In column "A", I have a date. I want to move the row if the date entered in column "A" is older than today's date. (it's a flight schedule for aircraft and I want to move flights that have already occured onto a sheet called "Past Flights".) The name of the active sheet is "Flight Schedule".

After the row is moved, I want it to delete off the "Flight Schedule" sheet. I know where to add scripts, but have no idea how to make this happen.

Here is what I have tried. I think on line "If (data.link >1..." data.link isn't the right one to use. But I can't find something for indicating older than todays date.

```<code>function approveRequests() {
 var ss = SpreadsheetApp.getActiveSpreadsheet()
 sheet = ss.getActiveSheet(),
 sheetName = sheet.getName(),
 data = sheet.getDataRange().getValues();
 if (sheetName == "Flight Shedule") {
  var range = sheet.getActiveRange(),
  startRow = range.getRowIndex(),
  numRows = range.getNumRows(),
  numCols = range.getNumColumns()
  if (numCols == 9) {
   if (data.length > 1) {
    var values = range.getValues(),
    nextSheet = ss.getSheetByName("Past Flight"),
    lastRow = nextSheet.getLastRow();
nextSheet.getRange(lastRow+1,1,numRows,3).setValues(values);
sheet.deleteRows(startRow,numRows);
   }
  }
 }
}
</code>```

Any help would be huge!

Thanks!

答:
Ok, I will go in with some general tips based on your current code first.

In your function you do a sheet = ss.getActiveSheet() which is redundant because you already have SpreadsheetApp.getActiveSpreadsheet().Also I would recommend to avoid this

```<code>var ss = SpreadsheetApp.getActiveSpreadsheet()
 sheet = ss.getActiveSheet(),
 sheetName = sheet.getName(),
 data = sheet.getDataRange().getValues();
</code>```

in favour of this:

```<code>var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var sheetName = sheet.getName();
var data = sheet.getDataRange().getValues();
</code>```

which is much more easy to read and change without making mistakes.

data.length has nothing to do with current date, it will simply be the length of the array. So if you select 1 row of data, it will be 1, if you select 2 rows it will be 2 etc. .getValues() will return an array where data[row][col]. What you are looking for is getting the value of the flight time, converting it into a date object (not a google specific thing, just general javascript). Then use var now = new Date() and compare the two.

I would also recommend to re-think your if statements. There are a lot of better ways to grab the row data than selecting the row manually and then running the function. You can save a lot of lines of code should you decide to actually make this run automatically, because as it is, it will run only when called manually.

Body:
I'm trying to move a row of data from one sheet to another in the same spreadsheet based on a value of today's date.

In column "A", I have a date. I want to move the row if the date entered in column "A" is older than today's date. (it's a flight schedule for aircraft and I want to move flights that have already occured onto a sheet called "Past Flights".) The name of the active sheet is "Flight Schedule".

After the row is moved, I want it to delete off the "Flight Schedule" sheet. I know where to add scripts, but have no idea how to make this happen.

Here is what I have tried. I think on line "If (data.link >1..." data.link isn't the right one to use. But I can't find something for indicating older than todays date.

function approveRequests() {
 var ss = SpreadsheetApp.getActiveSpreadsheet()
 sheet = ss.getActiveSheet(),
 sheetName = sheet.getName(),
 data = sheet.getDataRange().getValues();
 if (sheetName == "Flight Shedule") {
  var range = sheet.getActiveRange(),
  startRow = range.getRowIndex(),
  numRows = range.getNumRows(),
  numCols = range.getNumColumns()
  if (numCols == 9) {
   if (data.length > 1) {
    var values = range.getValues(),
    nextSheet = ss.getSheetByName("Past Flight"),
    lastRow = nextSheet.getLastRow();
nextSheet.getRange(lastRow+1,1,numRows,3).setValues(values);
sheet.deleteRows(startRow,numRows);
   }
  }
 }
}

Any help would be huge!

Thanks!

Body:
Ok, I will go in with some general tips based on your current code first.

In your function you do a sheet = ss.getActiveSheet() which is redundant because you already have SpreadsheetApp.getActiveSpreadsheet().Also I would recommend to avoid this

var ss = SpreadsheetApp.getActiveSpreadsheet()
 sheet = ss.getActiveSheet(),
 sheetName = sheet.getName(),
 data = sheet.getDataRange().getValues();

in favour of this:

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var sheetName = sheet.getName();
var data = sheet.getDataRange().getValues();

which is much more easy to read and change without making mistakes.

data.length has nothing to do with current date, it will simply be the length of the array. So if you select 1 row of data, it will be 1, if you select 2 rows it will be 2 etc. .getValues() will return an array where data[row][col]. What you are looking for is getting the value of the flight time, converting it into a date object (not a google specific thing, just general javascript). Then use var now = new Date() and compare the two.

I would also recommend to re-think your if statements. There are a lot of better ways to grab the row data than selecting the row manually and then running the function. You can save a lot of lines of code should you decide to actually make this run automatically, because as it is, it will run only when called manually.


问:
Java comparing two arrays and checking if the First array is consecutive of the Second
Long story short beginner programer here practicing with java. Right now I'm taking two arrays and I want to find out if int arrayA (7,14,21,28) is consecutive to int ArrayB meaning does arrayB have (7,14,21,28) consecutively within the array. If it is the boolean returns true if not it shall simply return false. Here is an example of my code.</p>

```<code> public class Harrison7aTest
 {
 public static void main(String [] args)
 {
  int[] arrayA = {7,14,21,28};
  int[] arrayB = {1,3,5,7,14,21,28,32};

 boolean result = false;

  for(int A = 0; A < arrayA.length - 1; A++)
  {
     for(int B = 0; B < arrayB.length - 1; B++)
     {

     }

  }

}
}
</code>```

答:
If you want to use the method would you would likely use in production as a Java engineer, then checkout the duplicate link given by @RC. or the answer by @Raman.  For the purposes of your assignment, if you just want to answer the question using a single loop, then consider my answer.  You can iterate once over the arrayB and check that the sequence of numbers contained within arrayA occurs, without interruption.

```<code>public static boolean containsConsecutive(int[] a, int[] b) {
    int aIndex = 0;
    for (int i=0; i < arrayB.length; i++) {
        if (aIndex != 0 && arrayB[i] != arrayA[aIndex]) {
            break;
        }
        else if (arrayB[i] == arrayA[aIndex]) {
            ++aIndex;
        }
    }

    return aIndex == arrayA.length;
}

public static void main(String[] args) {
    int[] a = {7,14,21,28,32};
    int[] b = {1,3,5,7,14,21,28,32};
    // true
    System.out.println(containsConsecutive(a, b));
    a = {7,14,21,28,32};
    b = {1,3,5,7,8,9,10,14,21,28,32};
    // false - sequence not in order
    System.out.println(containsConsecutive(a, b));
    a = {7,14,21,28,32,35};
    b = {1,3,5,7,14,21,28,32};
    // false - entire sequence in a not contained within b
    System.out.println(containsConsecutive(a, b));
}
</code>```

Body:
Long story short beginner programer here practicing with java. Right now I'm taking two arrays and I want to find out if int arrayA (7,14,21,28) is consecutive to int ArrayB meaning does arrayB have (7,14,21,28) consecutively within the array. If it is the boolean returns true if not it shall simply return false. Here is an example of my code.

 public class Harrison7aTest
 {
 public static void main(String [] args)
 {
  int[] arrayA = {7,14,21,28};
  int[] arrayB = {1,3,5,7,14,21,28,32};

 boolean result = false;

  for(int A = 0; A < arrayA.length - 1; A++)
  {
     for(int B = 0; B < arrayB.length - 1; B++)
     {

     }

  }

}
}

Body:
If you want to use the method would you would likely use in production as a Java engineer, then checkout the duplicate link given by @RC. or the answer by @Raman.  For the purposes of your assignment, if you just want to answer the question using a single loop, then consider my answer.  You can iterate once over the arrayB and check that the sequence of numbers contained within arrayA occurs, without interruption.

public static boolean containsConsecutive(int[] a, int[] b) {
    int aIndex = 0;
    for (int i=0; i < arrayB.length; i++) {
        if (aIndex != 0 && arrayB[i] != arrayA[aIndex]) {
            break;
        }
        else if (arrayB[i] == arrayA[aIndex]) {
            ++aIndex;
        }
    }

    return aIndex == arrayA.length;
}

public static void main(String[] args) {
    int[] a = {7,14,21,28,32};
    int[] b = {1,3,5,7,14,21,28,32};
    // true
    System.out.println(containsConsecutive(a, b));
    a = {7,14,21,28,32};
    b = {1,3,5,7,8,9,10,14,21,28,32};
    // false - sequence not in order
    System.out.println(containsConsecutive(a, b));
    a = {7,14,21,28,32,35};
    b = {1,3,5,7,14,21,28,32};
    // false - entire sequence in a not contained within b
    System.out.println(containsConsecutive(a, b));
}


问:
how to call angularjs function which is appended in div
```<code>$scope.showtbleoption =  function(id)
{
    console.log(id);
    $("#showoption").empty();
    $("#showoption").append('<button class="btn btn-info" ng-click="editrc(id)">');
};
</code>```

how to call editrc() function in angularjs controller ?

答:
Appending raw DOM with jQuery would make angular directive compile. You have to use $compile service, by which you will be $compile that DOM first & then inject that DOM in DOM tree. $compile is API function(returns function) which ask for DOM, then you can again call that function by passing $scope to evaluate against particular context. $compile API method will take care of compiling all directives on DOM & update bindings.

In below case id value wouldn't be available inside $scope directly, you could either store it in a scope variable or pass it by string concatenation.

```<code>var compiledDom=$compile('<button class="btn btn-info" ng-click="editrc('+id+')">')($scope);
$("#showoption").append(compiledDom);
</code>```

Body:
$scope.showtbleoption =  function(id)
{
    console.log(id);
    $("#showoption").empty();
    $("#showoption").append('<button class="btn btn-info" ng-click="editrc(id)">');
};

how to call editrc() function in angularjs controller ?

Body:
Appending raw DOM with jQuery would make angular directive compile. You have to use $compile service, by which you will be $compile that DOM first & then inject that DOM in DOM tree. $compile is API function(returns function) which ask for DOM, then you can again call that function by passing $scope to evaluate against particular context. $compile API method will take care of compiling all directives on DOM & update bindings.

In below case id value wouldn't be available inside $scope directly, you could either store it in a scope variable or pass it by string concatenation.

var compiledDom=$compile('<button class="btn btn-info" ng-click="editrc('+id+')">')($scope);
$("#showoption").append(compiledDom);


问:
C# Avoiding Duplicated Logic
Suppose I had a base class A, with subclasses B, C and D. I have a class, MyClass which contains an overload for each of them. I want a counter to increment any time one of these methods is invoked from anywhere other than inside MyClass. This can be accomplished with a few simple helper methods:

```<code>public class MyClass
{
   int counter;

   public doSomethingExternal(B b) {counter++; doSomething(b);}
   public doSomethingExternal(C c) {counter++; doSomething(c);}
   public doSomethingExternal(D d) {counter++; doSomething(d);}

   private doSomething(B b) {...}
   private doSomething(C c) {...}
   private doSomething(D d) {...}
}
</code>```

This really bothers the dev in me. Is there no way better way we can write those helper methods so that we don't have duplicated logic for every subclass? The solution I envision is something like:

```<code>// Magically, we know which type we are and call the correct doSomething
public doSomethingExternal(A a) {counter++; doSomething(a);}
</code>```

I think this kind of generalization could be accomplished with Reflection, but I have heard that reflection is generally slow and can be complicated to understand. I am curious if there is a more conventional pattern I am overlooking that solves this logic-duplication issue.

答:
Another approach using dynamic

```<code>public class MyClass
{
    int counter;

    public doSomethingExternal(A value) // A is base class
    {
        counter++;
        dynamic dynamicValue = value;
        doSomething(dynamicValue); // Correct overload will be used based on actual type
    }

    private doSomething(B b) {...}
    private doSomething(C c) {...}
    private doSomething(D d) {...}
}
</code>```

Leaving argument of doSomethingExternal to be a base class, will prevent passing other types to the method.

Title: C# Avoiding Duplicated Logic

Body:
Suppose I had a base class A, with subclasses B, C and D. I have a class, MyClass which contains an overload for each of them. I want a counter to increment any time one of these methods is invoked from anywhere other than inside MyClass. This can be accomplished with a few simple helper methods:

public class MyClass
{
   int counter;

   public doSomethingExternal(B b) {counter++; doSomething(b);}
   public doSomethingExternal(C c) {counter++; doSomething(c);}
   public doSomethingExternal(D d) {counter++; doSomething(d);}

   private doSomething(B b) {...}
   private doSomething(C c) {...}
   private doSomething(D d) {...}
}

This really bothers the dev in me. Is there no way better way we can write those helper methods so that we don't have duplicated logic for every subclass? The solution I envision is something like:

// Magically, we know which type we are and call the correct doSomething
public doSomethingExternal(A a) {counter++; doSomething(a);}

I think this kind of generalization could be accomplished with Reflection, but I have heard that reflection is generally slow and can be complicated to understand. I am curious if there is a more conventional pattern I am overlooking that solves this logic-duplication issue.

Body:
Another approach using dynamic

public class MyClass
{
    int counter;

    public doSomethingExternal(A value) // A is base class
    {
        counter++;
        dynamic dynamicValue = value;
        doSomething(dynamicValue); // Correct overload will be used based on actual type
    }

    private doSomething(B b) {...}
    private doSomething(C c) {...}
    private doSomething(D d) {...}
}

Leaving argument of doSomethingExternal to be a base class, will prevent passing other types to the method.


问:
How can i create a Multi-Dimensional array as the following in php?
Hi guys i am  trying to create a multi dimensional array as the format bellow but i am struggling to do so, any help would be appreciated. Thank you.

```<code>    $movies = array();
    $sql = "SELECT u.username AS Username, group_concat(v.title) AS Video_title, group_concat(r.rate) AS Rating
    FROM `rating` AS r
    JOIN `uploads` AS v ON r.video_id = v.vid_id
    JOIN `users` as u ON u.user_id = r.rater_id
    GROUP by Username" ;

    $query = mysqli_query($conn, $sql);

    while($result = mysqli_fetch_assoc($query)){
    $movies[] = $result;
    }

    foreach($movies as $k => $v){
    unset($movies[$k]);
    $movies[$v['Username']] = $v;
    }
    foreach($movies as $k => $v){
    unset($movies[$k]['Username']);
    }

    print_r($movies);
</code>```

This is what i am currently getting:

```<code>     [user1] => Array ( [Video_title] => Snakes on the Plane,
                                         Superman Returns,
                                         The Night Listner,
                                         Lady in the Water,
                                         Just my Luck,
                                         You me and Dupree
                         [Rating] => 3.5,
                                     3.5,
                                     3,
                                     2.5,
                                     3,
                                     2.5
                     ) )
</code>```

But i am aiming to output it in the following format:

```<code> 'user1' =>
          array('Lady in the Water' => 2.5,
                'Snakes on a Plane' => 3.5,
                'Just My Luck' => 3.0,
                'Superman Returns' => 3.5,
                'You, Me and Dupree' => 2.5,
                'The Night Listener' => 3.0
               )
</code>```

答:
You have to do it like below:-

```<code>  $movies = array();
    $sql = "SELECT u.username AS Username, group_concat(v.title) AS Video_title, group_concat(r.rate) AS Rating
    FROM `rating` AS r
    JOIN `uploads` AS v ON r.video_id = v.vid_id
    JOIN `users` as u ON u.user_id = r.rater_id
    GROUP by Username" ;
    $query = mysqli_query($conn, $sql);

    while($result = mysqli_fetch_assoc($query)){
        $movies[] = $result;
    }

    $new_movies = array(); // a new array variable

    foreach($movies as $k => $v){
        $array_keys = explode(',',$v['Video_title']); // explode Video_title string into array
        $trimmed_array_key=array_map('trim',$array_keys); // trim all spaces from each value of $trimmed_array_key array
        $array_values = explode(',',$v['Rating']); // explode Rating array
        $trimmed_array_values=array_map('trim',$array_values);//remove all spaces from $trimmed_array_values array
        $new_movies[$v['Username']] = array_combine($trimmed_array_key,$trimmed_array_values); // combine $trimmed_array_key array and $trimmed_array_values array and assign to corresponding user
    }

    echo "<pre/>";print_r($new_movies); // print new array
</code>```

Note:-

This line:-$trimmed_array_key=array_map('trim',$array_keys);

Will do something like below:-

https://eval.in/766605

reference:- http://php.net/manual/en/function.array-combine.php

Body:
Hi guys i am  trying to create a multi dimensional array as the format bellow but i am struggling to do so, any help would be appreciated. Thank you.

    $movies = array();
    $sql = "SELECT u.username AS Username, group_concat(v.title) AS Video_title, group_concat(r.rate) AS Rating
    FROM `rating` AS r
    JOIN `uploads` AS v ON r.video_id = v.vid_id
    JOIN `users` as u ON u.user_id = r.rater_id
    GROUP by Username" ;

    $query = mysqli_query($conn, $sql);

    while($result = mysqli_fetch_assoc($query)){
    $movies[] = $result;
    }

    foreach($movies as $k => $v){
    unset($movies[$k]);
    $movies[$v['Username']] = $v;
    }
    foreach($movies as $k => $v){
    unset($movies[$k]['Username']);
    }

    print_r($movies);

This is what i am currently getting:

     [user1] => Array ( [Video_title] => Snakes on the Plane,
                                         Superman Returns,
                                         The Night Listner,
                                         Lady in the Water,
                                         Just my Luck,
                                         You me and Dupree
                         [Rating] => 3.5,
                                     3.5,
                                     3,
                                     2.5,
                                     3,
                                     2.5
                     ) )

But i am aiming to output it in the following format:

 'user1' =>
          array('Lady in the Water' => 2.5,
                'Snakes on a Plane' => 3.5,
                'Just My Luck' => 3.0,
                'Superman Returns' => 3.5,
                'You, Me and Dupree' => 2.5,
                'The Night Listener' => 3.0
               )

Body:
You have to do it like below:-

  $movies = array();
    $sql = "SELECT u.username AS Username, group_concat(v.title) AS Video_title, group_concat(r.rate) AS Rating
    FROM `rating` AS r
    JOIN `uploads` AS v ON r.video_id = v.vid_id
    JOIN `users` as u ON u.user_id = r.rater_id
    GROUP by Username" ;
    $query = mysqli_query($conn, $sql);

    while($result = mysqli_fetch_assoc($query)){
        $movies[] = $result;
    }

    $new_movies = array(); // a new array variable

    foreach($movies as $k => $v){
        $array_keys = explode(',',$v['Video_title']); // explode Video_title string into array
        $trimmed_array_key=array_map('trim',$array_keys); // trim all spaces from each value of $trimmed_array_key array
        $array_values = explode(',',$v['Rating']); // explode Rating array
        $trimmed_array_values=array_map('trim',$array_values);//remove all spaces from $trimmed_array_values array
        $new_movies[$v['Username']] = array_combine($trimmed_array_key,$trimmed_array_values); // combine $trimmed_array_key array and $trimmed_array_values array and assign to corresponding user
    }

    echo "<pre/>";print_r($new_movies); // print new array

Note:-

This line:-$trimmed_array_key=array_map('trim',$array_keys);

Will do something like below:-

https://eval.in/766605

reference:- http://php.net/manual/en/function.array-combine.php


答:
Instead of appending using jQuery, use $compile service to bind it to dom. Like this:

```<code>$scope.domEle = $compile('<button class="btn btn-info" ng-click="editrc(id)">')
</code>```

and in HTML call like this:

```<code>{{ domeEle }}
</code>```

And in controller define editrc function like this:

```<code>$scope.editrc = function(val){

}
</code>```

Title: how to call angularjs function which is appended in div

Body:
Instead of appending using jQuery, use $compile service to bind it to dom. Like this:

$scope.domEle = $compile('<button class="btn btn-info" ng-click="editrc(id)">')

and in HTML call like this:

{{ domeEle }}

And in controller define editrc function like this:

$scope.editrc = function(val){

}


问:
How to add full height for a element inside an element in CSS or Angularjs Dinamically
Idea is do not use vertical or horizontal scroll bar in body section. I have a div which is having css like this:

```<code>display: flex;
height: 100%;
</code>```

I want inside div height to be fully responsive. The height should be auto adjusted based on the height of the device. for inside div we can have scroll bar no problem based on the data.

Hope you guys understood my question, please help.

答:
as you don't want scroll on the body but inside your main div.you can achieve using following css and html.

```<code><div class="main">
  <div class="content">
    // you content goes here...
  </div>
</div>
</code>```

and the css for .main class and for .content class are as follows.

```<code>.main{
  position: absolute;
  top:0;
  bottom:0;
  left:0;
  right:0;
}

.content{
  position:absolute;
  top:0;
  bottom:0;
  left:0;
  right:0;
  overflow: auto;
}
</code>```

here is the demo https://codepen.io/anon/pen/MpLZqd

i hope this will help.

Body:
Idea is do not use vertical or horizontal scroll bar in body section. I have a div which is having css like this:

display: flex;
height: 100%;

I want inside div height to be fully responsive. The height should be auto adjusted based on the height of the device. for inside div we can have scroll bar no problem based on the data.

Hope you guys understood my question, please help.

Body:
as you don't want scroll on the body but inside your main div.you can achieve using following css and html.

<div class="main">
  <div class="content">
    // you content goes here...
  </div>
</div>

and the css for .main class and for .content class are as follows.

.main{
  position: absolute;
  top:0;
  bottom:0;
  left:0;
  right:0;
}

.content{
  position:absolute;
  top:0;
  bottom:0;
  left:0;
  right:0;
  overflow: auto;
}

here is the demo https://codepen.io/anon/pen/MpLZqd

i hope this will help.


问:
When should I use h:outputLink instead of h:commandLink?
When should I use an <h:outputLink> instead of an <h:commandLink>?

I understand that a commandLink generates an HTTP post; I'm guessing that outputLink will generate HTTP gets. That said, most of the JSF tutorial material I've read uses commandLink (almost?) exclusively.

Context: I am implementing a wee little demo project that shows a header link to a user page, much like Stack Overflow's...

...and I am not sure if commandLink (perhaps using ?faces-redirect=true for bookmarkability) or outputLink is the right choice.

答:
The <h:outputLink> renders a fullworthy HTML  element with the proper URL in the href attribute which fires a bookmarkable GET request. It cannot directly invoke a managed bean action method.

<h:outputLink value="destination.xhtml">link text</h:outputLink>
```
<hr />
<p>The <code><h:commandLink></code> renders a HTML <code><a></code> element with an <code>onclick</code> script which submits a (hidden) POST form and can invoke a managed bean action method. It's also required to be placed inside a <code><h:form></code>.</p>
<pre class="lang-xml prettyprint-override"><code><h:form>
    <h:commandLink value="link text" action="destination" />
</h:form>
</code>```

The ?faces-redirect=true parameter on the <h:commandLink>, which triggers a redirect after the POST (as per the Post-Redirect-Get pattern), only improves bookmarkability of the target page when the link is actually clicked (the URL won't be "one behind" anymore), but it doesn't change the href of the  element to be a fullworthy URL. It still remains #.

<h:form>
    <h:commandLink value="link text" action="destination?faces-redirect=true" />
</h:form>
```
<hr />
<p>Since JSF 2.0, there's also the <code><h:link></code> which can take a view ID (a navigation case outcome) instead of an URL. It will generate a HTML <code><a></code> element as well with the proper URL in <code>href</code>.</p>
<pre class="lang-xml prettyprint-override"><code><h:link value="link text" outcome="destination" />
</code>```

So, if it's for pure and bookmarkable page-to-page navigation like the SO username link, then use <h:outputLink> or <h:link>. That's also better for SEO since bots usually doesn't cipher POST forms nor JS code. Also, UX will be improved as the pages are now bookmarkable and the URL is not "one behind" anymore.

When necessary, you can do the preprocessing job in the constructor or @PostConstruct of a @RequestScoped or @ViewScoped @ManagedBean which is attached to the destination page in question. You can make use of @ManagedProperty or <f:viewParam> to set GET parameters as bean properties.

See also:

ViewParam vs @ManagedProperty(value = "#{param.id}")

What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?

Bookmarkability via View Parameters feature

How to navigate in JSF? How to make URL reflect current page (and not previous one)

Body:
The <h:outputLink> renders a fullworthy HTML <a> element with the proper URL in the href attribute which fires a bookmarkable GET request. It cannot directly invoke a managed bean action method.

<h:outputLink value="destination.xhtml">link text</h:outputLink>

The <h:commandLink> renders a HTML <a> element with an onclick script which submits a (hidden) POST form and can invoke a managed bean action method. It's also required to be placed inside a <h:form>.

<h:form>
    <h:commandLink value="link text" action="destination" />
</h:form>

The ?faces-redirect=true parameter on the <h:commandLink>, which triggers a redirect after the POST (as per the Post-Redirect-Get pattern), only improves bookmarkability of the target page when the link is actually clicked (the URL won't be "one behind" anymore), but it doesn't change the href of the <a> element to be a fullworthy URL. It still remains #.

<h:form>
    <h:commandLink value="link text" action="destination?faces-redirect=true" />
</h:form>

Since JSF 2.0, there's also the <h:link> which can take a view ID (a navigation case outcome) instead of an URL. It will generate a HTML <a> element as well with the proper URL in href.

<h:link value="link text" outcome="destination" />

So, if it's for pure and bookmarkable page-to-page navigation like the SO username link, then use <h:outputLink> or <h:link>. That's also better for SEO since bots usually doesn't cipher POST forms nor JS code. Also, UX will be improved as the pages are now bookmarkable and the URL is not "one behind" anymore.

When necessary, you can do the preprocessing job in the constructor or @PostConstruct of a @RequestScoped or @ViewScoped @ManagedBean which is attached to the destination page in question. You can make use of @ManagedProperty or <f:viewParam> to set GET parameters as bean properties.

See also:

ViewParam vs @ManagedProperty(value = "#{param.id}")

What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?

Bookmarkability via View Parameters feature

How to navigate in JSF? How to make URL reflect current page (and not previous one)


问:
javah: Error: cannot access android.support.v7.app.AppCompatActivity?
I know there are similar questions here already, but none of them seem to help. I'm using Ubuntu 16.04

I'm trying to create a JNI file and folder in Android Studio, following this tutorial: https://www.youtube.com/watch?v=kFtxo7rr2HQ but no matter what I do I keep getting errors. I've got it to a point where it says:

```<code>    Error: cannot access android.support.v7.app.AppCompatActivity
      class file for android.support.v7.app.AppCompatActivity not found
</code>```

Here is the command I am giving it:

```<code>  javah -d jni -classpath ~/Android/Sdk/platforms/android-21/android.jar:../../build/intermediates/classes/debug com.example.ndktest.MainActivity
</code>```

I have tried adding these two libraries, figuring that this would resolve my issue, but no luck:

```<code>    javah -d jni -classpath ~/Android/Sdk/platforms/android-21/android.jar:~/android-support-v7-appcompat-master/libs/android-support-v7-appcompat.jar:~/android-support-v7-appcompat-master/libs/android-support-v4.jar:../../build/intermediates/classes/debug com.example.ndktest.MainActivity
</code>```

This gives me the same error. I'm at a loss for what I can try next to make this work. Eventually my task is to integrate an application into an android build rom, but I need to understand Android.mk files first, and for that I need to understand how to use the NDK to use preexisting C++ code. Can anyone help?

答:
The simplest way to solve this problem is change the AppCompatActivity to Activity, then you are good to go.

You are quit careful, since you change the semicolon to colon already. I make a mistake for that.

Body:
I know there are similar questions here already, but none of them seem to help. I'm using Ubuntu 16.04

I'm trying to create a JNI file and folder in Android Studio, following this tutorial: https://www.youtube.com/watch?v=kFtxo7rr2HQ but no matter what I do I keep getting errors. I've got it to a point where it says:

    Error: cannot access android.support.v7.app.AppCompatActivity
      class file for android.support.v7.app.AppCompatActivity not found

Here is the command I am giving it:

  javah -d jni -classpath ~/Android/Sdk/platforms/android-21/android.jar:../../build/intermediates/classes/debug com.example.ndktest.MainActivity

I have tried adding these two libraries, figuring that this would resolve my issue, but no luck:

    javah -d jni -classpath ~/Android/Sdk/platforms/android-21/android.jar:~/android-support-v7-appcompat-master/libs/android-support-v7-appcompat.jar:~/android-support-v7-appcompat-master/libs/android-support-v4.jar:../../build/intermediates/classes/debug com.example.ndktest.MainActivity

This gives me the same error. I'm at a loss for what I can try next to make this work. Eventually my task is to integrate an application into an android build rom, but I need to understand Android.mk files first, and for that I need to understand how to use the NDK to use preexisting C++ code. Can anyone help?


问:
how to host webapplication and webapi in single solution
I created a solution with two webapplication project. One is asp.net mvc and second one is web api. Now I want to publish. Kindly suggest me how to publish my webapplication and webapi</p>

答:
Process 1 :

You don't need to create separate project for Web API and MVC application in a single solution. You can create a MVC application and add an WebApiConfig.cs (route for api) file in App_Start folder. Write the route for API,(you just need to copy your route from Web API project and paste here). Now you can add/keep your all Api controllers in Controller folder which must be inherited from ApiController. That's it!

Process 2 :

But if you want to keep in separate project in a single solution,

then right click on your solution -> click on properties -> It will open property page. Here select the Multiple Startup projects radio button -> Then you can set both MVC and Web API application as start in action column -> Click on Apply -> Then Ok.

Suppose your Domain name is example.com. Then you can publish your MVC application there. And create a sub-domain, for example, myapi.example.com, and publish your API there. Then enable CORS on API project.

I would recommend to go with Process 1.

If you want to know more about how to publish both project from a single solution, please check this link


问:
Removing lead zeroes from an array
I seem to be having issues removing leading zeroes from an array that is created by the user. For example, the program I am writing will ask the user to input a mathematical expression (input received as a string):

Eg : 1234 + 1234

Before going into creating a function to solve this problem, I can't seem to get my array to ignore the leading zeroes. This is because I am switching the user input from string to integer and then positioning these values at the end of the array (constant size is 20). Below is how I convert from string to an integer array.

```<code>void stringToInt(int arr[], string value1, int SIZE){
    for (int i = 0; i < SIZE; i++){
         if (arr[i] < 0)
             arr[i] = 0;
         arr[SIZE - 1 - i] = value1[value1.length() - 1 - i] - 48;
}
</code>```

This is how I tried to remove zeroes:

```<code>void removeLeadZeroes(int arr[], string value1, int SIZE){
    bool print = true;
    int carry = 0;
    for (int i = 0; i < (SIZE - 1); i++){
        if (arr[i] == 0
            print = false;
        if (print)
            cout << arr[i];
    }
}
</code>```

答:
There is a better way for converting strings to integers. There is a buildin function called atoi() in C++. You will have to use stdlib.h header file for this. Converting character array to integer using this function will automatically remove unwanted values in the array.

```<code>#include <iostream>
#include <stdlib.h>
using namespace std;

int main() {

    //The character array
    char a[3];

    //The integer variable
    int b;
    gets(a);

    //Converts to integer
    b=atoi(a);

    //To prove that value is an integer and
    //mathematical operations can be done on it
    cout<<b+2;
    return 0;
}
</code>```

Hope it helped. Ask if you need any help.

Title: Removing lead zeroes from an array

Body:
I seem to be having issues removing leading zeroes from an array that is created by the user. For example, the program I am writing will ask the user to input a mathematical expression (input received as a string):

Eg : 1234 + 1234

Before going into creating a function to solve this problem, I can't seem to get my array to ignore the leading zeroes. This is because I am switching the user input from string to integer and then positioning these values at the end of the array (constant size is 20). Below is how I convert from string to an integer array.

void stringToInt(int arr[], string value1, int SIZE){
    for (int i = 0; i < SIZE; i++){
         if (arr[i] < 0)
             arr[i] = 0;
         arr[SIZE - 1 - i] = value1[value1.length() - 1 - i] - 48;
}

This is how I tried to remove zeroes:

void removeLeadZeroes(int arr[], string value1, int SIZE){
    bool print = true;
    int carry = 0;
    for (int i = 0; i < (SIZE - 1); i++){
        if (arr[i] == 0
            print = false;
        if (print)
            cout << arr[i];
    }
}

Body:
There is a better way for converting strings to integers. There is a buildin function called atoi() in C++. You will have to use stdlib.h header file for this. Converting character array to integer using this function will automatically remove unwanted values in the array.

#include <iostream>
#include <stdlib.h>
using namespace std;

int main() {

    //The character array
    char a[3];

    //The integer variable
    int b;
    gets(a);

    //Converts to integer
    b=atoi(a);

    //To prove that value is an integer and
    //mathematical operations can be done on it
    cout<<b+2;
    return 0;
}

Hope it helped. Ask if you need any help.


问:
editing the contents of an array list
how can you edit the contents of an array list using a value generated by the user using the scanner class.

many thanks

答:
```<code>List<String> lst = new ArrayList<String>();
lst.add("a");
lst.add("b");
lst.add("c");

//now modifying contents
lst.set(1, "z");
</code>```

Title: editing the contents of an array list