问:
Multiple submit buttons with values passed from buttons
The way I have structured the form is that there are multiple "Test Connection" submit buttons plus a "Save" submit button to save all the credentials and urls for each test connection. I have seen some suggested solutions but I don't feel like doing an ajax or javascript. So I'm wondering if this is possible. And by the way, I would like to pass values to the controller via the submit buttons as enum values and receive that enum in my controller.

I could easily make multiple ActionResults but it just feels so convoluted for me and if I have to change something in the test connection, I would have to change all. So I would like to have only one ActionResult method for TestConnection plus one Save ActionResult all within the same form.

When I click the Save button, all the credentials are sent to the controller as the ApplicationSettings model.

When I click the Test Connection button, I still receive the ApplicationSettings model plus the DatabaseSystems enum and depending on the enum received form the button, I would do the necessary connection.

Below are the code snippets but I just can't make them work.

Approaches tried:
1.  Blank form action, submit buttons has name as "Save" and "TestConnection" accordingly. - Save works. TestConnection does not work saying The resource cannot be found.
2.  Form action pointed to "TestConnection", TestConnection button names set as
"database" while value set as @DatabaseSystems.xxx, Save button set as "action:Save", ActionResult method for Save added [MultipleButton(Name = "action", Argument = "Save")] - TestConnection works, Save does not work saying ambiguous request.

I can't seem to figure out the config to make them both work. :(

View

```<code>@using Models.Enums
@model MyApp.Data.ApplicationSettings

@Html.AntiForgeryToken()
@using (Html.BeginForm())
{
<div class="row">
    <div class="col-md-2">
        @Html.EditorFor(model => model.con1_un, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con1_un) } })
    </div>
    <div class="col-md-2">
        @Html.EditorFor(model => model.con1_pw, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con1_pw) } })
    </div>
    <div class="col-md-7">
        @Html.EditorFor(model => model.con1_url, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con1_url), @rows = "1", @style = "max-width:520px !important" } })
    </div>
    <div class="col-md-1 pull-right">
        <button type="submit" class="btn btn-warning pull-right" name="database" value="@DatabaseSystems.System1" data-toggle="collapse" data-target="#loading"><span class="glyphicon glyphicon-link"></span>  Test Connection</button>
    </div>
</div>
<div class="row">
    <div class="col-md-2">
        @Html.EditorFor(model => model.con2_un, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con2_un) } })
    </div>
    <div class="col-md-2">
        @Html.EditorFor(model => model.con2_pw, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con2_pw) } })
    </div>
    <div class="col-md-7">
        @Html.EditorFor(model => model.con2_url, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con2_url), @rows = "1", @style = "max-width:520px !important" } })
    </div>
    <div class="col-md-1 pull-right">
        <button type="submit" class="btn btn-warning pull-right" name="database" value="@DatabaseSystems.System2" data-toggle="collapse" data-target="#loading"><span class="glyphicon glyphicon-link"></span>  Test Connection</button>
    </div>
</div>

<div class="row">
    <div class="col-md-2">
        @Html.EditorFor(model => model.con3_un, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con3_un) } })
    </div>
    <div class="col-md-2">
        @Html.EditorFor(model => model.con3_pw, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con3_pw) } })
    </div>
    <div class="col-md-7">
        @Html.EditorFor(model => model.con3_url, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con3_url), @rows = "1", @style = "max-width:520px !important" } })
    </div>
    <div class="col-md-1 pull-right">
        <button type="submit" class="btn btn-warning pull-right" name="database" value="@DatabaseSystems.System3" data-toggle="collapse" data-target="#loading"><span class="glyphicon glyphicon-link"></span>  Test Connection</button>
    </div>
</div>

... and many more test connections for different systems

<button type="submit" class="btn btn-success pull-right" name="Save" data-toggle="collapse" data-target="#loading"><span class="glyphicon glyphicon-floppy-disk"></span> Save</button>
}
</code>```

Controller

```<code>[HttpPost]
ActionResult TestConnection(ApplicationSettings model, DatabaseSystems database)
{
    // depending on the DatabaseSystems enum passed, then I'll do the necessary connection check.
{
[HttpPost]
ActionResult Save(ApplicationSettings model)
{
    // Save credentials entered in all the input fields above for con1, con2 & con3.
}
</code>```

Model

```<code>[Serializable]
public class ApplicationSettings
{
    public string con1_un { get; set; }
    public string con1_pw { get; set; }
    public string con1_url { get; set; }

    public string con2_un { get; set; }
    public string con2_pw { get; set; }
    public string con2_url { get; set; }

    public string con3_un { get; set; }
    public string con3_pw { get; set; }
    public string con3_url { get; set; }

    ... and many more systems
}
</code>```

Enum

```<code>public enum DatabaseSystems
{
    System1,
    System2,
    System3,
    ... and many more systems
}
</code>```

答:
Finally got it. Though @Stephen Muecke did not really provide a direct solution, I should say he made me reconsider using formaction again so I still have to thank him. Thanks mate! Below is how I solved it:

View

```<code>@using Models.Enums
@model MyApp.Data.ApplicationSettings

@Html.AntiForgeryToken()
@using (Html.BeginForm())
{
    ...
    <button type="submit" class="btn btn-warning pull-right" name="database" value="@DatabaseSystems.System1" formaction="Admin/TestConnection" data-toggle="collapse" data-target="#loading"><span class="glyphicon glyphicon-link"></span>  Test Connection</button>
    ...
    <button type="submit" class="btn btn-warning pull-right" name="database" value="@DatabaseSystems.System2" formaction="Admin/TestConnection" data-toggle="collapse" data-target="#loading"><span class="glyphicon glyphicon-link"></span>  Test Connection</button>
}
</code>```

Controller

```<code>public ActionResult TestConnection(ApplicationSettings model, DatabaseSystems database)
{
    // at the end, instead of putting return View() or return("Index", model), I used below code
    return Redirect("/[ControllerName]");
{
</code>```

... this way, formaction will do the calling of the ActionResult method for me while keeping the name attribute of the button free for other purposes such as passing it as a parameter to my TestConnection method.

Body:
The way I have structured the form is that there are multiple "Test Connection" submit buttons plus a "Save" submit button to save all the credentials and urls for each test connection. I have seen some suggested solutions but I don't feel like doing an ajax or javascript. So I'm wondering if this is possible. And by the way, I would like to pass values to the controller via the submit buttons as enum values and receive that enum in my controller.

I could easily make multiple ActionResults but it just feels so convoluted for me and if I have to change something in the test connection, I would have to change all. So I would like to have only one ActionResult method for TestConnection plus one Save ActionResult all within the same form.

When I click the Save button, all the credentials are sent to the controller as the ApplicationSettings model.

When I click the Test Connection button, I still receive the ApplicationSettings model plus the DatabaseSystems enum and depending on the enum received form the button, I would do the necessary connection.

Below are the code snippets but I just can't make them work.

Approaches tried:
1.  Blank form action, submit buttons has name as "Save" and "TestConnection" accordingly. - Save works. TestConnection does not work saying The resource cannot be found.
2.  Form action pointed to "TestConnection", TestConnection button names set as
"database" while value set as @DatabaseSystems.xxx, Save button set as "action:Save", ActionResult method for Save added [MultipleButton(Name = "action", Argument = "Save")] - TestConnection works, Save does not work saying ambiguous request.

I can't seem to figure out the config to make them both work. :(

View

@using Models.Enums
@model MyApp.Data.ApplicationSettings

@Html.AntiForgeryToken()
@using (Html.BeginForm())
{

        @Html.EditorFor(model => model.con1_un, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con1_un) } })

        @Html.EditorFor(model => model.con1_pw, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con1_pw) } })

        @Html.EditorFor(model => model.con1_url, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con1_url), @rows = "1", @style = "max-width:520px !important" } })

        <button type="submit" class="btn btn-warning pull-right" name="database" value="@DatabaseSystems.System1" data-toggle="collapse" data-target="#loading">  Test Connection</button>

        @Html.EditorFor(model => model.con2_un, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con2_un) } })

        @Html.EditorFor(model => model.con2_pw, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con2_pw) } })

        @Html.EditorFor(model => model.con2_url, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con2_url), @rows = "1", @style = "max-width:520px !important" } })

        <button type="submit" class="btn btn-warning pull-right" name="database" value="@DatabaseSystems.System2" data-toggle="collapse" data-target="#loading">  Test Connection</button>

        @Html.EditorFor(model => model.con3_un, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con3_un) } })

        @Html.EditorFor(model => model.con3_pw, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con3_pw) } })

        @Html.EditorFor(model => model.con3_url, new { htmlAttributes = new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.con3_url), @rows = "1", @style = "max-width:520px !important" } })

        <button type="submit" class="btn btn-warning pull-right" name="database" value="@DatabaseSystems.System3" data-toggle="collapse" data-target="#loading">  Test Connection</button>

... and many more test connections for different systems

<button type="submit" class="btn btn-success pull-right" name="Save" data-toggle="collapse" data-target="#loading"> Save</button>
}

Controller

[HttpPost]
ActionResult TestConnection(ApplicationSettings model, DatabaseSystems database)
{
    // depending on the DatabaseSystems enum passed, then I'll do the necessary connection check.
{
[HttpPost]
ActionResult Save(ApplicationSettings model)
{
    // Save credentials entered in all the input fields above for con1, con2 & con3.
}

Model

[Serializable]
public class ApplicationSettings
{
    public string con1_un { get; set; }
    public string con1_pw { get; set; }
    public string con1_url { get; set; }

    public string con2_un { get; set; }
    public string con2_pw { get; set; }
    public string con2_url { get; set; }

    public string con3_un { get; set; }
    public string con3_pw { get; set; }
    public string con3_url { get; set; }

    ... and many more systems
}

Enum

public enum DatabaseSystems
{
    System1,
    System2,
    System3,
    ... and many more systems
}

Body:
Finally got it. Though @Stephen Muecke did not really provide a direct solution, I should say he made me reconsider using formaction again so I still have to thank him. Thanks mate! Below is how I solved it:

View

@using Models.Enums
@model MyApp.Data.ApplicationSettings

@Html.AntiForgeryToken()
@using (Html.BeginForm())
{
    ...
    <button type="submit" class="btn btn-warning pull-right" name="database" value="@DatabaseSystems.System1" formaction="Admin/TestConnection" data-toggle="collapse" data-target="#loading"><span class="glyphicon glyphicon-link"></span>  Test Connection</button>
    ...
    <button type="submit" class="btn btn-warning pull-right" name="database" value="@DatabaseSystems.System2" formaction="Admin/TestConnection" data-toggle="collapse" data-target="#loading"><span class="glyphicon glyphicon-link"></span>  Test Connection</button>
}

Controller

public ActionResult TestConnection(ApplicationSettings model, DatabaseSystems database)
{
    // at the end, instead of putting return View() or return("Index", model), I used below code
    return Redirect("/[ControllerName]");
{

... this way, formaction will do the calling of the ActionResult method for me while keeping the name attribute of the button free for other purposes such as passing it as a parameter to my TestConnection method.


来源: stackexchange

问:
HTML is it possible to set second class inherit the main id?
Is it possible for me to set the second class to inherit the main class ID?

Codepen: https://codepen.io/jayvicious/pen/EXardz

.productholder {
  width: 50%;
  display: inline-block;
}

#content2p {
  padding-top: 19px;
  padding-bottom: 40px;
  margin-left: 6cm;
  width: auto;
}

.bookingFormHeader {
  display: inline-flex;
  background-color: lightgrey;
  width: 300px;
  border: 25px solid green;
  padding: 25px;
  margin: 25px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="content2p">

  <img class="productholder" src="http://via.placeholder.com/662x442.png">
  <p class="bookingFormHeader">Test Test</p>

</div></code>```

Explanation :-

I've set a container with the id content2p . Here i want to put two class side by side. The first class productholder is working fine. My only issue would be bookingFormHeader . It's indenting to the bottom, i want to make it same line as below example output:

The booking is actually a form with border box :

I've tried many ways by changing the display to the following :-

inline-block
 flex
 table
 inline-table

Yet i've got no luck , is there any element I'm missing??
Appreciate in advance.

答:
You also use class inside id

```<code><style>
#id
{
****some style
}
.class
{
**codes
}
</code>```

html like this

```<code><div id="id>
<div class="class"
</div>
</div>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is it possible for me to set the second class to inherit the main class ID?

Codepen: https://codepen.io/jayvicious/pen/EXardz

.productholder {
  width: 50%;
  display: inline-block;
}

#content2p {
  padding-top: 19px;
  padding-bottom: 40px;
  margin-left: 6cm;
  width: auto;
}

.bookingFormHeader {
  display: inline-flex;
  background-color: lightgrey;
  width: 300px;
  border: 25px solid green;
  padding: 25px;
  margin: 25px;
}

Test Test

Explanation :-

I've set a container with the id content2p . Here i want to put two class side by side. The first class productholder is working fine. My only issue would be bookingFormHeader . It's indenting to the bottom, i want to make it same line as below example output:

The booking is actually a form with border box :

I've tried many ways by changing the display to the following :-

inline-block
 flex
 table
 inline-table

Yet i've got no luck , is there any element I'm missing??
Appreciate in advance.

Body:
You also use class inside id

<style>
#id
{
****some style
}
.class
{
**codes
}

html like this

<div id="id>
<div class="class"
</div>
</div>


问:
How can you add a substring inside an if statement?
There is 3 category type (New Permit, Permit to Operate and Renewal) they have a reference number like 'R-662017-01' if the first letter is R its RENEWAL while for New permit its P and N for permit to operate.

how can you substring or do that in an if statement? please help :(

答:
you can try this code snippet:</p>

```<code>string input='R-662017-01';
string sub = input.Substring(0, 1);
if(sub=="R")
{
//do RENEWAL  code here
}
else if(sub=="P")
{
//do New permit code here
}
else if(sub=="N")
{
//do Permit to Operate  code here
}
</code>```

Body:
you can try this code snippet:

string input='R-662017-01';
string sub = input.Substring(0, 1);
if(sub=="R")
{
//do RENEWAL  code here
}
else if(sub=="P")
{
//do New permit code here
}
else if(sub=="N")
{
//do Permit to Operate  code here
}


问:
How to best iterate through Request.Form and matching Session key
How do I best iterate through Request.Form and match a Session key? I'm building a shopping cart.

I have a unique id as a Session key, and a whole number for the value of that key. When a Form key's value gets updated, I want the session value to update too.

Let's say we originally set Session.Contents["id-101"] = 1, then my page sends a form with Request.Form["id-101"] = 4; I want Session.Contents to update the Value to 4.

This doesn't work because I'm not accessing the value of the form item, I think...

```<code>foreach (string item in Request.Form)
{
  if (item == Session.Contents[item])
  {
     Session.Contents[item] == Request.Form[item];
     break;
  }
}
</code>```

答:
This is how you can do that </p>

```<code>List<int> listValues = new List<int>();
foreach (string key in Request.Form.AllKeys)
{
    if (key.StartsWith("List"))
    {
        listValues.Add(Convert.ToInt32(Request.Form[key]));
    }
}
</code>```

Body:
How do I best iterate through Request.Form and match a Session key? I'm building a shopping cart.

I have a unique id as a Session key, and a whole number for the value of that key. When a Form key's value gets updated, I want the session value to update too.

Let's say we originally set Session.Contents["id-101"] = 1, then my page sends a form with Request.Form["id-101"] = 4; I want Session.Contents to update the Value to 4.

This doesn't work because I'm not accessing the value of the form item, I think...

foreach (string item in Request.Form)
{
  if (item == Session.Contents[item])
  {
     Session.Contents[item] == Request.Form[item];
     break;
  }
}

Body:
This is how you can do that

List<int> listValues = new List<int>();
foreach (string key in Request.Form.AllKeys)
{
    if (key.StartsWith("List"))
    {
        listValues.Add(Convert.ToInt32(Request.Form[key]));
    }
}


问:
How to replace using for loop in range(len) by using enumerate
Is there a simple way to use enumerate instead of for loop with range(len)? For example, here I loop to replace all values of each element in subarrays by the index of its subarray.

```<code>list = []
for i in range(len(nparray)):
    j = [i]*(len(nparray[i]))
    list.append(j)
</code>```

My nparray is np.array with 6 subarrays, and each subarray has different size.

答:
to use enumerator, first you need to declare two target vars because enumerator return a tuple.

Using your example in a comprehension list, it could be like this:

```<code>listR = [[idx]*(len(val)) for idx,val in enumerate(multiarray)]
</code>```

If you want to deep https://docs.python.org/2/library/functions.html#enumerate

I hope this help you.

Regards

Body:
Is there a simple way to use enumerate instead of for loop with range(len)? For example, here I loop to replace all values of each element in subarrays by the index of its subarray.

list = []
for i in range(len(nparray)):
    j = [i]*(len(nparray[i]))
    list.append(j)

My nparray is np.array with 6 subarrays, and each subarray has different size.

Body:
to use enumerator, first you need to declare two target vars because enumerator return a tuple.

Using your example in a comprehension list, it could be like this:

listR = [[idx]*(len(val)) for idx,val in enumerate(multiarray)]

If you want to deep https://docs.python.org/2/library/functions.html#enumerate

I hope this help you.

Regards


问:
how to create a setup file with launch condition
i don't have basic knowledge of .net

but i have assigned a work to create a setup file for a project which must satisfy the condition such the setup file must check the present of the .net and sql while installing if not it should automatically install it

so guide by step by step
for
1.registry key
2.prerequisites
3.launch condition

.net3.5 and sql server2005
using vs 2008

pls help me friends

答: This can be done easily using the Setup Project in VS.NET, here it is an example of how to add prerequisites </p>

ContentLicense: CC BY-SA 2.5


问:
Solution in Slick to Map a Future[Option] DB result to a value
I'm doing this in play framework to get the relation between a command and a execution table using slick.

```<code>class ExecutionsTable(tag: Tag) extends BaseTable[Execution](tag, "executions") {
    def name = column[String]("name")
    def execution = column[String]("execution")
    def commandId = column[Long]("command_id")
    def * = (id, name, execution, commandId) <> (Execution.tupled, Execution.unapply)
    def command = foreignKey("commands", commandId, commandsTableQ)(_.id)

    implicit val CommandToLong = MappedColumnType.base[Long, Command] (
      id => {
        val cmd = Await.result(new CommandsDAO().findById(id), 1 second)
        cmd.get
      },
      cmd => cmd.id
    )
</code>```

findById returns a Future[Option[Command]] I'm trying to use this method which I'm not sure is the best solution for this.

What would you recommend?

答:
Do you want to handle errors? If you do, I suggest you use a flatMap and then pattern match again to see if you function actually returns something. Here you go, Something along these lines : </p>

```<code>val x : Future[Option[String]] = Future(Option("1"))

val id = x.flatMap(optId => optId match {
  case Some(id) => id
  case None => throw new Exception("No ID.")
}
</code>```

Body:
I'm doing this in play framework to get the relation between a command and a execution table using slick.

class ExecutionsTable(tag: Tag) extends BaseTable[Execution](tag, "executions") {
    def name = column[String]("name")
    def execution = column[String]("execution")
    def commandId = column[Long]("command_id")
    def * = (id, name, execution, commandId) <> (Execution.tupled, Execution.unapply)
    def command = foreignKey("commands", commandId, commandsTableQ)(_.id)

    implicit val CommandToLong = MappedColumnType.base[Long, Command] (
      id => {
        val cmd = Await.result(new CommandsDAO().findById(id), 1 second)
        cmd.get
      },
      cmd => cmd.id
    )

findById returns a Future[Option[Command]] I'm trying to use this method which I'm not sure is the best solution for this.

What would you recommend?

Body:
Do you want to handle errors? If you do, I suggest you use a flatMap and then pattern match again to see if you function actually returns something. Here you go, Something along these lines :

val x : Future[Option[String]] = Future(Option("1"))

val id = x.flatMap(optId => optId match {
  case Some(id) => id
  case None => throw new Exception("No ID.")
}


问:
Get checksum of the source codes in Android library
I am developing an android library and I want to apply a tamper-detection mechanism to my code, since it calls some sensitive financial web services.

What I'm going to implement is to calculate the checksum of the apk ( or important parts of it), programmatically on the runtime, so I can prevent a repackaged or recompiled apk from being able to do any harm (tamper prevention).

What I have come up with so far, is to calculate the checksum of the applicationInfo.publicSourceDir. but I'm not sure what happens with the apps that have multiple dex files or multiple splitApks.

What is the most reliable way to calculate checksum based on the code-base of an application in Android, programmatically?

答:
Get the app signature which is tied to the certificate used to sign the APK

```<code>public static String getAppSignature(Context context) {
    try {
        for (Signature signature : context.getPackageManager().getPackageInfo(context.getPackageName(),
                PackageManager.GET_SIGNATURES).signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            return Base64.encodeToString(md.digest(), Base64.DEFAULT);
        }
    } catch (Exception e) { /* Do nothing */ }
    return null;
}
</code>```

This can be compared with a stored value to check if the signing certificate is the original or not.

Body:
Get the app signature which is tied to the certificate used to sign the APK

public static String getAppSignature(Context context) {
    try {
        for (Signature signature : context.getPackageManager().getPackageInfo(context.getPackageName(),
                PackageManager.GET_SIGNATURES).signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            return Base64.encodeToString(md.digest(), Base64.DEFAULT);
        }
    } catch (Exception e) { /* Do nothing */ }
    return null;
}

This can be compared with a stored value to check if the signing certificate is the original or not.


问:
How to fetch device's mobile number programmatically in Android?
This code is not working...It giving null...</p>

```<code>TelephonyManager tMgr = (TelephonyManager)HomeActivity.this.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();

Log.e("Mobile No. :",""+mPhoneNumber);
Toast.makeText(getApplicationContext(),mPhoneNumber,Toast.LENGTH_SHORT).show();
</code>```

答:
Here is the code for it:

```<code>TelephonyManager telemamanger = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String getSimSerialNumber = telemamanger.getSimSerialNumber();
String getSimNumber = telemamanger.getLine1Number();
</code>```

and you also have to add "READ_PHONE_STATE" permission in Androidmanifest.xml file.

and if you are testing the app on higher OS device then you also have to ask for the permission externally.

hope this will help you. :)

Body:
This code is not working...It giving null...

TelephonyManager tMgr = (TelephonyManager)HomeActivity.this.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();

Log.e("Mobile No. :",""+mPhoneNumber);
Toast.makeText(getApplicationContext(),mPhoneNumber,Toast.LENGTH_SHORT).show();

Body:
Here is the code for it:

TelephonyManager telemamanger = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String getSimSerialNumber = telemamanger.getSimSerialNumber();
String getSimNumber = telemamanger.getLine1Number();

and you also have to add "READ_PHONE_STATE" permission in Androidmanifest.xml file.

and if you are testing the app on higher OS device then you also have to ask for the permission externally.

hope this will help you. :)


问:
After converting a pdf to swf, how can I select text to highlight?
I have used a tool to convert a pdf to a swf but i need to be able to select and hightlight the pdf's contents. How would I do this using flex/action script?
Thank you!</p>

答: I think you could just use ordinar HTML page to display that pdf's content + iframe to display the page. It's really easy. Check this: Flex + HTML. Enjoy!</p>


问:
How to get Inno Setup to unzip a single file?
Is there a way to unzip just one file from a zip?
I'm using code based on response for  How to get Inno Setup to unzip a file it installed (all as part of the one installation process), works perfect for unzip but don't have an idea how can it unzip a single file: </p>

<pre class="lang-pascal prettyprint-override"><code>[Code]:

const
  NO_PROGRESS_BOX = 4;
  RESPOND_YES_TO_ALL = 16;

procedure UnZip(ZipPath, TargetPath: string);
var
  Shell: Variant;
  ZipFile: Variant;
  TargetFolder: Variant;
begin
  Shell := CreateOleObject('Shell.Application');

  ZipFile := Shell.NameSpace(ZipPath);
  if VarIsClear(ZipFile) then
    RaiseException(Format('ZIP file "%s" does not exist or cannot be opened', [ZipPath]));

  TargetFolder := Shell.NameSpace(TargetPath);
  if VarIsClear(TargetFolder) then
    RaiseException(Format('Target path "%s" does not exist', [TargetPath]));

  TargetFolder.CopyHere(ZipFile.Items, NO_PROGRESS_BOX or RESPOND_YES_TO_ALL);
end;
</code>```

答:
Use Folder.ParseName to retrieve a reference to a specific file in a ZIP archive "folder". Then pass that reference to Folder.CopyHere to extract it.

const
  NO_PROGRESS_BOX = 4;
  RESPOND_YES_TO_ALL = 16;

procedure UnZip(ZipPath, FileName, TargetPath: string);
var
  Shell: Variant;
  ZipFile: Variant;
  Item: Variant;
  TargetFolder: Variant;
begin
  Shell := CreateOleObject('Shell.Application');

  ZipFile := Shell.NameSpace(ZipPath);
  if VarIsClear(ZipFile) then
    RaiseException(Format('Cannot open ZIP file "%s" or does not exist', [ZipPath]));

  Item := ZipFile.ParseName(FileName);
  if VarIsClear(Item) then
    RaiseException(Format('Cannot find "%s" in "%s" ZIP file', [FileName, ZipPath]));

  TargetFolder := Shell.NameSpace(TargetPath);
  if VarIsClear(TargetFolder) then
    RaiseException(Format('Target path "%s" does not exist', [TargetPath]));

  TargetFolder.CopyHere(Item, NO_PROGRESS_BOX or RESPOND_YES_TO_ALL);
end;
```

Body:
Is there a way to unzip just one file from a zip?
I'm using code based on response for  How to get Inno Setup to unzip a file it installed (all as part of the one installation process), works perfect for unzip but don't have an idea how can it unzip a single file:

[Code]:

const
  NO_PROGRESS_BOX = 4;
  RESPOND_YES_TO_ALL = 16;

procedure UnZip(ZipPath, TargetPath: string);
var
  Shell: Variant;
  ZipFile: Variant;
  TargetFolder: Variant;
begin
  Shell := CreateOleObject('Shell.Application');

  ZipFile := Shell.NameSpace(ZipPath);
  if VarIsClear(ZipFile) then
    RaiseException(Format('ZIP file "%s" does not exist or cannot be opened', [ZipPath]));

  TargetFolder := Shell.NameSpace(TargetPath);
  if VarIsClear(TargetFolder) then
    RaiseException(Format('Target path "%s" does not exist', [TargetPath]));

  TargetFolder.CopyHere(ZipFile.Items, NO_PROGRESS_BOX or RESPOND_YES_TO_ALL);
end;

ContentLicense: CC BY-SA 4.0


答:
Try to pass the reference number "'R-662017-01" into a switch case statement where you substring this value and do something based on what is in the substring value</p>

```<code>string str = "R-662017-01";

        switch (str.Substring(0,1))
        {
            case "R":
                // Do somthing
                break;

            case "P":
                // Do somthing
                break;

            case "N":
                // Do somthing
                break;
</code>```

Title: How can you add a substring inside an if statement?

Body:
There is 3 category type (New Permit, Permit to Operate and Renewal) they have a reference number like 'R-662017-01' if the first letter is R its RENEWAL while for New permit its P and N for permit to operate.

how can you substring or do that in an if statement? please help :(

Body:
Try to pass the reference number "'R-662017-01" into a switch case statement where you substring this value and do something based on what is in the substring value

string str = "R-662017-01";

        switch (str.Substring(0,1))
        {
            case "R":
                // Do somthing
                break;

            case "P":
                // Do somthing
                break;

            case "N":
                // Do somthing
                break;


问:
Is Office 2003 interop supported on Windows server 2008 ..?
I am getting below error while trying to run an interop dependent program on Windows server 2008 its running fine on Win Server 2003 and XP:

System.Runtime.InteropServices.COMException (0x800A03EC): Exception from HRESULT: 0x800A03EC
   at Microsoft.Office.Interop.Excel.WorkbookClass.SaveAs(.......)

According to Microsoft, Windows Server 2008 is not in list of suppoerted OS.

http://www.microsoft.com/downloads/en/details.aspx?familyid=3c9a983a-ac14-4125-8ba0-d36d67e0f4ad&displaylang=en

System Requirements

Supported Operating Systems:Windows 2000 Service Pack 3;Windows Server 2003;Windows XP

Can anybody please confirm this.. has anyone tried it ..?

答:
Well, in general, running interop on any server is usually not a good idea, since Office is not made to be part of a server solution. However, assuming that you can't change that, it should be possible to get it to run, but I have seen a lot of problems having various issues but the solutions seems to be different for different people.

This stackoverflow question has some answers, some of which might help you (it's about Win7, but it should still be relevant I'd think).


问:
Spring Boot JS and HTML files and packing to WAR file
I developed a server with spring boot. It has also one HTML and one JS file.
After packing the project to WAR file and running it, I get the error that the HTML cannot approach to the JS file.

```<code>java.io.FileNotFoundException: Jar URL cannot be resolved to absolute file path because it does not reside in the file system: war:file:/C:/Users/USER/Documents/workspace-sts-3.8.4.RELEASE/blabla/target/blabla-0.0.1-SNAPSHOT.war*/storeFiles/app.js
</code>```

How can I fix that?

答:
Where are your resource files located, in src/main/webapp or in src/main/resources/static ?
There has been an issue on that topic.

Body:
I developed a server with spring boot. It has also one HTML and one JS file.
After packing the project to WAR file and running it, I get the error that the HTML cannot approach to the JS file.

java.io.FileNotFoundException: Jar URL cannot be resolved to absolute file path because it does not reside in the file system: war:file:/C:/Users/USER/Documents/workspace-sts-3.8.4.RELEASE/blabla/target/blabla-0.0.1-SNAPSHOT.war*/storeFiles/app.js

How can I fix that?


问:
handling form validation error in laravel 5.4 + vueJS
I have form create.vue like this:

```<code>    <template>
    <div>
        <div v-if="message" class="alert alert-success">
            {{ message }}
        </div>

        <form @submit.prevent="store" action="/user" method="post">
            <div :class="['form-group', errors.name ? 'has-error' : '']">
            <!--<div class="form-group">-->
            <label>Full name</label>
                <input v-model="state.name" type="text" class="form-control">
                <span v-if="errors.name" class="label label-danger">{{ errors.name[0] }}</span>
                <!--<span class="label label-danger">{{ errors(errors.name) }}</span>-->
            </div>

            <div :class="['form-group', errors.email ? 'has-error' : '']">
            <!--<div class="form-group">-->
                <label>Email</label>
                <input v-model="state.email" type="email" class="form-control">
                <span v-if="errors.email" class="label label-danger">{{ errors.email[0] }}</span>
                <!--<span class="label label-danger">{{ errors(errors.email) }}</span>-->
            </div>

            <div class="form-group">
                <button class="btn btn-primary">Submit</button>
                <!--<router-link :to="{ name: 'userIndex' }">Back to index</router-link>-->
            </div>
        </form>
    </div>
</template>

<script>
export default {
    data() {
        return {
            errors: [],
            user: [],
            state: {
                name: '',
                email: ''
            }
        }
    },

    methods: {
        store(e) {
            axios.post(e.target.action, this.state).then(response => {
                this.errors = [];

                this.state = {
                    name: '',
                    email: ''
                }

                this.message = 'User has been created.';
            }).catch(error => {
                if (! _.isEmpty(error.response)) {
                    if (error.response.status = 422) {
                        this.errors = error.response.data;
                    }
                }
            });
        }
    }
}
</script>
</code>```

And my controller:
UserCOntroller.php

```<code>public function store(Request $request)
     {
         $this->validate($request, [
             'name'  => 'required|string|max:50',
             'email' => 'required|email|unique:users,email',
         ]);

         $user = User::create([
             'name'     => $request->name,
             'email'    => $request->email,
             'password' => bcrypt(str_random()),
         ]);

         return response()->json($user);
     }
</code>```

When I type something similar to what ever existed(Unique), I get error text in console response, but not displaying in form like as usual. I get error in console like this:

```<code>{"email":["The email has already been taken."]}
</code>```

how to display in form?
What's wrong with my script?

any help ? thank you before..

答:
Hi I tried to replicate your script in my local. Works in me though. Can you try to debug object errors in catch. Send a sample result :)</p>

```<code>if (error.response.status = 422) {
    this.errors = error.response.data;
    console.log(this.errors);
}
</code>```

Body:
I have form create.vue like this:

    <template>

            {{ message }}

        <form @submit.prevent="store" action="/user" method="post">

            Full name
                <input v-model="state.name" type="text" class="form-control">
                {{ errors.name[0] }}

                Email
                <input v-model="state.email" type="email" class="form-control">
                {{ errors.email[0] }}

                <button class="btn btn-primary">Submit</button>

        </form>

</template>

And my controller:
UserCOntroller.php

public function store(Request $request)
     {
         $this->validate($request, [
             'name'  => 'required|string|max:50',
             'email' => 'required|email|unique:users,email',
         ]);

         $user = User::create([
             'name'     => $request->name,
             'email'    => $request->email,
             'password' => bcrypt(str_random()),
         ]);

         return response()->json($user);
     }

When I type something similar to what ever existed(Unique), I get error text in console response, but not displaying in form like as usual. I get error in console like this:

{"email":["The email has already been taken."]}

how to display in form?
What's wrong with my script?

any help ? thank you before..

Body:
Hi I tried to replicate your script in my local. Works in me though. Can you try to debug object errors in catch. Send a sample result :)

if (error.response.status = 422) {
    this.errors = error.response.data;
    console.log(this.errors);
}


问:
Understanding & making infinite bullets to shoot in Pygame
I'm learning python and also pygame, and I want to know why the bullets doesn't display, I tough that maybe the screen.update_screen() can be interfering but no, that's not the case, I need help to undertand how Bullets work in python because clearly my method is not working, I've seen many methods in other posts, and they use a limited ammount of bullets to shoot (don't know why, in my case I want infinite bullets) so what should I add to see the Bullets, I know that I need to add a remover for seing a "movement" in the display, but I don't know how, any help is appreciated.

```<code># -*- coding: utf-8 -*-
import pygame

class Screen(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        pygame.display.set_caption("Space Game")
        self.screen_width = 800
        self.screen_heigh = 600
        self.picture = pygame.image.load("screen.png")
        self.screen = pygame.display.set_mode((self.screen_width, self.screen_heigh))

    def update_screen(self):
        self.screen.blit(self.picture, (0, 0))

    def update_obj(self, object):
        self.screen.blit(object.picture, object.rect)

    def update_shoot(self, object):
        for y in range(object.rect.centery, 600, 10):
            self.screen.blit(object.picture, (object.rect.centerx, object.rect.centery + y))

class Ship(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.picture = pygame.image.load("ship.png")
        self.rect = self.picture.get_rect()
        self.rect.centerx = 400
        self.rect.centery = 500

class Bullet(pygame.sprite.Sprite):
    def __init__(self, object):
        pygame.sprite.Sprite.__init__(self)
        self.picture = pygame.image.load("shoot.png")
        self.rect = self.picture.get_rect()
        self.rect.centerx = object.rect.centerx
        self.rect.centery = (object.rect.centery + 25)

def main():
    pygame.init()
    done = False
    clock = pygame.time.Clock()
    screen = Screen()
    ship = Ship()
    bullet = Bullet(ship)

    while not done:
        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT]:
            ship.rect.centerx -= 5
        if keys[pygame.K_RIGHT]:
            ship.rect.centerx += 5
        if keys[pygame.K_UP]:
            ship.rect.centery -= 5
        if keys[pygame.K_DOWN]:
            ship.rect.centery += 5

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    done = True
                if event.key == pygame.K_SPACE:
                    print ("shoot")
                    #for some weird reason the bullet doesn't display
                    screen.update_shoot(bullet)

        screen.update_screen()
        screen.update_obj(ship)
        pygame.display.update()
        clock.tick(10)

    pygame.quit()

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

答:
To shoot bullets you usually create instances of a Bullet class and add them to a list, pygame.sprite.Group or another container. Then you iterate over this container and call the update method of the bullet in which its position is changed. To blit the images of the sprites/objects you iterate again over the container and just blit the images onto the screen. With sprite groups you can just call sprite_group.update() and sprite_group.draw(screen) instead of iterating yourself. BTW, pygame sprites have to have a self.image attribute not a self.picture in order to work with sprite groups (take a look at Program Arcade Games for more information).

I started to modify a few things in your example to show you how to use sprite groups, but then ended up changing your whole Screen class into a Game class (which I recommend to use in the future).

```<code>import sys
import pygame

class Game:

    def __init__(self):
        self.done = False
        self.screen_width = 800
        self.screen_height = 600
        self.image = pygame.Surface((800, 600))
        self.image.fill((30, 40, 50))
        self.screen = pygame.display.set_mode(
            (self.screen_width, self.screen_height))

        # all_sprites is used to update and draw all sprites together.
        self.all_sprites = pygame.sprite.Group()
        # You'll probably need a separate bullet_group
        # later for collision detection with enemies.
        self.bullet_group = pygame.sprite.Group()

        self.ship = Ship()
        self.all_sprites.add(self.ship)

        bullet = Bullet(self.ship)
        self.bullet_group.add(bullet)
        self.all_sprites.add(bullet)

    def handle_events(self):
        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT]:
            self.ship.rect.centerx -= 5
        if keys[pygame.K_RIGHT]:
            self.ship.rect.centerx += 5
        if keys[pygame.K_UP]:
            self.ship.rect.centery -= 5
        if keys[pygame.K_DOWN]:
            self.ship.rect.centery += 5

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.done = True
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    self.done = True
                if event.key == pygame.K_SPACE:
                    bullet = Bullet(self.ship)
                    self.bullet_group.add(bullet)
                    self.all_sprites.add(bullet)

    def update(self):
        # Calls `update` methods of all contained sprites.
        self.all_sprites.update()

    def draw(self):
        self.screen.blit(self.image, (0, 0))
        self.all_sprites.draw(self.screen)  # Draw the contained sprites.
        pygame.display.update()

class Ship(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((20, 30))
        self.image.fill((50, 170, 230))
        # A nicer way to set the start pos with `get_rect`.
        self.rect = self.image.get_rect(center=(400, 500))

class Bullet(pygame.sprite.Sprite):

    def __init__(self, ship):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((7, 7))
        self.image.fill((230, 140, 30))
        self.rect = self.image.get_rect()
        self.rect.centerx = ship.rect.centerx
        self.rect.centery = ship.rect.centery - 25

    def update(self):
        self.rect.y -= 5  # Move up 5 pixels per frame.

def main():
    pygame.init()
    pygame.display.set_caption('Space Game')
    clock = pygame.time.Clock()
    game = Game()

    while not game.done:
        game.handle_events()
        game.update()
        game.draw()
        clock.tick(30)

if __name__ == '__main__':
    main()
    pygame.quit()
    sys.exit()
</code>```

Body:
I'm learning python and also pygame, and I want to know why the bullets doesn't display, I tough that maybe the screen.update_screen() can be interfering but no, that's not the case, I need help to undertand how Bullets work in python because clearly my method is not working, I've seen many methods in other posts, and they use a limited ammount of bullets to shoot (don't know why, in my case I want infinite bullets) so what should I add to see the Bullets, I know that I need to add a remover for seing a "movement" in the display, but I don't know how, any help is appreciated.

# -*- coding: utf-8 -*-
import pygame

class Screen(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        pygame.display.set_caption("Space Game")
        self.screen_width = 800
        self.screen_heigh = 600
        self.picture = pygame.image.load("screen.png")
        self.screen = pygame.display.set_mode((self.screen_width, self.screen_heigh))

    def update_screen(self):
        self.screen.blit(self.picture, (0, 0))

    def update_obj(self, object):
        self.screen.blit(object.picture, object.rect)

    def update_shoot(self, object):
        for y in range(object.rect.centery, 600, 10):
            self.screen.blit(object.picture, (object.rect.centerx, object.rect.centery + y))

class Ship(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.picture = pygame.image.load("ship.png")
        self.rect = self.picture.get_rect()
        self.rect.centerx = 400
        self.rect.centery = 500

class Bullet(pygame.sprite.Sprite):
    def __init__(self, object):
        pygame.sprite.Sprite.__init__(self)
        self.picture = pygame.image.load("shoot.png")
        self.rect = self.picture.get_rect()
        self.rect.centerx = object.rect.centerx
        self.rect.centery = (object.rect.centery + 25)

def main():
    pygame.init()
    done = False
    clock = pygame.time.Clock()
    screen = Screen()
    ship = Ship()
    bullet = Bullet(ship)

    while not done:
        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT]:
            ship.rect.centerx -= 5
        if keys[pygame.K_RIGHT]:
            ship.rect.centerx += 5
        if keys[pygame.K_UP]:
            ship.rect.centery -= 5
        if keys[pygame.K_DOWN]:
            ship.rect.centery += 5

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    done = True
                if event.key == pygame.K_SPACE:
                    print ("shoot")
                    #for some weird reason the bullet doesn't display
                    screen.update_shoot(bullet)

        screen.update_screen()
        screen.update_obj(ship)
        pygame.display.update()
        clock.tick(10)

    pygame.quit()

if __name__ == "__main__":
    main()

Body:
To shoot bullets you usually create instances of a Bullet class and add them to a list, pygame.sprite.Group or another container. Then you iterate over this container and call the update method of the bullet in which its position is changed. To blit the images of the sprites/objects you iterate again over the container and just blit the images onto the screen. With sprite groups you can just call sprite_group.update() and sprite_group.draw(screen) instead of iterating yourself. BTW, pygame sprites have to have a self.image attribute not a self.picture in order to work with sprite groups (take a look at Program Arcade Games for more information).

I started to modify a few things in your example to show you how to use sprite groups, but then ended up changing your whole Screen class into a Game class (which I recommend to use in the future).

import sys
import pygame

class Game:

    def __init__(self):
        self.done = False
        self.screen_width = 800
        self.screen_height = 600
        self.image = pygame.Surface((800, 600))
        self.image.fill((30, 40, 50))
        self.screen = pygame.display.set_mode(
            (self.screen_width, self.screen_height))

        # all_sprites is used to update and draw all sprites together.
        self.all_sprites = pygame.sprite.Group()
        # You'll probably need a separate bullet_group
        # later for collision detection with enemies.
        self.bullet_group = pygame.sprite.Group()

        self.ship = Ship()
        self.all_sprites.add(self.ship)

        bullet = Bullet(self.ship)
        self.bullet_group.add(bullet)
        self.all_sprites.add(bullet)

    def handle_events(self):
        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT]:
            self.ship.rect.centerx -= 5
        if keys[pygame.K_RIGHT]:
            self.ship.rect.centerx += 5
        if keys[pygame.K_UP]:
            self.ship.rect.centery -= 5
        if keys[pygame.K_DOWN]:
            self.ship.rect.centery += 5

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.done = True
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    self.done = True
                if event.key == pygame.K_SPACE:
                    bullet = Bullet(self.ship)
                    self.bullet_group.add(bullet)
                    self.all_sprites.add(bullet)

    def update(self):
        # Calls `update` methods of all contained sprites.
        self.all_sprites.update()

    def draw(self):
        self.screen.blit(self.image, (0, 0))
        self.all_sprites.draw(self.screen)  # Draw the contained sprites.
        pygame.display.update()

class Ship(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((20, 30))
        self.image.fill((50, 170, 230))
        # A nicer way to set the start pos with `get_rect`.
        self.rect = self.image.get_rect(center=(400, 500))

class Bullet(pygame.sprite.Sprite):

    def __init__(self, ship):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((7, 7))
        self.image.fill((230, 140, 30))
        self.rect = self.image.get_rect()
        self.rect.centerx = ship.rect.centerx
        self.rect.centery = ship.rect.centery - 25

    def update(self):
        self.rect.y -= 5  # Move up 5 pixels per frame.

def main():
    pygame.init()
    pygame.display.set_caption('Space Game')
    clock = pygame.time.Clock()
    game = Game()

    while not game.done:
        game.handle_events()
        game.update()
        game.draw()
        clock.tick(30)

if __name__ == '__main__':
    main()
    pygame.quit()
    sys.exit()


问:
Place some nodes of the same network on GPU and others on CPU?
When defining a network in Caffe/Caffe2, can you place some of the nodes on the CPU and others on GPU? If so, how? </p>

<p>(If your answer pertains a specific version of Caffe, please specify which)</p>

答:
Generally speaking, the answer is NO: you cannot configure the device for each layer independently for the reasons Pooya Davoodi and Harsh Wardhan described.

However, if you look at specific layers, you might sometimes get the behavior you look for. For instance, if your solver is configured to run on GPU, but you have a layer in your net that does not have a GPU implementation, then this layer will run on the CPU (with all the overhead described in Harsh Wardhan's answer).

One such layer is a "Python" layer: This layer runs only on CPU and you may have your word2vec implementation there.

Alternatively, you may write your own layers without GPU implementation making sure they run only on CPU.

BTW, are you using caffe2? Are you okay with their PATENTS clause?!

UPDATE: it seems like fb decided to soften caffe2's license. Well done!

Body:
When defining a network in Caffe/Caffe2, can you place some of the nodes on the CPU and others on GPU? If so, how?

(If your answer pertains a specific version of Caffe, please specify which)


问:
Rails increase duration of flash[:error] message
What would be the easiest/best way to increase the display duration of an individual flash[:error] message in a Rails 4 application?

the code that does the message is in a controller and the pertinent section looks like this:

```<code>  else
    flash[:notice] = t(:no_new_media, source: @channel.external_source.capitalize)
    flash[:error] = @error['message'] if @error.present?
    redirect_to admin_channel_path(@channel)
  end
</code>```

I'd like to increase the display duration of the error message but I don't care either way about the notice

答:
I think you should create a new custom flash message type. More detail here.

```<code># app/controllers/application_controller.rb
class ApplicationController
    ...
  add_flash_types :error, :another_custom_type
end

# app/controllers/users_controller.rb
class UsersController < ApplicationController
  def create
    ...
    redirect_to home_path,
      another_custom_type: "An error message for the user"
  end
end
</code>```

Now in your view check flash[:another_custom_type].present? and set duration of message on the basis of that.

Body:
What would be the easiest/best way to increase the display duration of an individual flash[:error] message in a Rails 4 application?

the code that does the message is in a controller and the pertinent section looks like this:

  else
    flash[:notice] = t(:no_new_media, source: @channel.external_source.capitalize)
    flash[:error] = @error['message'] if @error.present?
    redirect_to admin_channel_path(@channel)
  end

I'd like to increase the display duration of the error message but I don't care either way about the notice

Body:
I think you should create a new custom flash message type. More detail here.

# app/controllers/application_controller.rb
class ApplicationController
    ...
  add_flash_types :error, :another_custom_type
end

# app/controllers/users_controller.rb
class UsersController < ApplicationController
  def create
    ...
    redirect_to home_path,
      another_custom_type: "An error message for the user"
  end
end

Now in your view check flash[:another_custom_type].present? and set duration of message on the basis of that.


问:
How to find elements in array that contain a given substring?
I have 3 strings, I would like to get only the equal strings of them, something like this:

```<code>$Var1 = "Sant";
$Array[] = "Hello Santa Claus";   // Name_1
$Array[] = "Santa Claus";         // Name_2
</code>```

I would like to get both of them because they match "Sant".

With my code I only get Name_2

```<code>$len = strlen($Var1);
foreach($Array as $name)
{
   if (  stristr($Var1, substr($name, 0, $len)))
   {
     echo $name;
   }
}
</code>```

I understand why I only get Name_2, but I don't know how to solve this situation.

答:
you can use strpos() function of php to identify if a string consist a substring or not as

```<code>$a = 'Sant';
foreach($Array as $name)
{
    if (strpos($name, $a) !== false) {
        echo $name;
    }
}
</code>```

Body:
I have 3 strings, I would like to get only the equal strings of them, something like this:

$Var1 = "Sant";
$Array[] = "Hello Santa Claus";   // Name_1
$Array[] = "Santa Claus";         // Name_2

I would like to get both of them because they match "Sant".

With my code I only get Name_2

$len = strlen($Var1);
foreach($Array as $name)
{
   if (  stristr($Var1, substr($name, 0, $len)))
   {
     echo $name;
   }
}

I understand why I only get Name_2, but I don't know how to solve this situation.

Body:
you can use strpos() function of php to identify if a string consist a substring or not as

$a = 'Sant';
foreach($Array as $name)
{
    if (strpos($name, $a) !== false) {
        echo $name;
    }
}


问:
Share cookies between subdomain and domain
I have two questions. I understand that if I specify the domain as .example.com (with the leading dot) in the cookie that all subdomains can share a cookie.

Can subdomain.example.com access a cookie created in example.com (without the www subdomain)?

Can example.com (without the www subdomain) access the cookie if created in subdomain.example.com?

答:
In both cases, yes, it can, and this is the default behaviour for both Internet Explorer and Edge.

The other answers add valuable insight, but they chiefly describe the behaviour in Chrome. It's important to note that the behaviour is completely different in Internet Explorer. CMBuckley's very helpful test script demonstrates that in (say) Chrome, the cookies are not shared between root and subdomains when no domain is specified.

However, the same test in Internet Explorer shows that they are shared. This Internet Explorer case is closer to the take-home description in CMBuckley's www-or-not-www link. I know this to be the case because we have a system that used different servicestack cookies on both the root and subdomain. It all worked fine until someone accessed it in Internet Explorer and the two systems fought over whose session cookie would win until we blew up the cache.


问:
Remove space of checkbox if it does not exist
I have a listView populated with the help of a CustomAdapter.

I make a test while retrieving the values from my db.

One of the rows if 'Homework'. If homework = 1, then I show a CheckBox in the beginning of the line of my listView. But if it's 0 , I dont show anything. But I'd like to move all the text after the checkbox to the left. in my list_row.xml I declared a checkbox, so if homework is 0, i just setVisibility to INVISIBLE on my checkbox.

I can't post images, so I'll give an example :

if homework is 1 , my listView is like this :

```<code>Checkbox - Date of creation - Title
</code>```

if Homework is 0, my row of the listview is like this :

```<code>         - Date of creation - Title
</code>```

So you can see that there will have an empty space if Homework is 0. How can I change that so it stays like this:

```<code>-Date of creation - Title
</code>```

Thank you !And tell me if you need the code my CustomAdapter please

@UPDATE-my customadapter

```<code>`public class CustomAdapterJalons extends SimpleCursorAdapter {

private Context mContext;
private Context appContext;
private int layout;
private Cursor cr;
private final LayoutInflater inflater;

public CustomAdapterJalons(Context context, int layout, Cursor c, String[] from, int[] to) {
    super(context, layout, c, from, to);
    this.layout = layout;
    this.mContext = context;
    this.inflater = LayoutInflater.from(context);
    this.cr = c;
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    return inflater.inflate(layout, null);
}

@Override
public void bindView(View view, final Context context, final Cursor cursor) {
    super.bindView(view, context, cursor);

    final int position = cursor.getPosition();

    cursor.moveToPosition(position);

    int devoir = cursor.getInt(3);
    int evaluation = cursor.getInt(4);
    int importance = cursor.getInt(5);
    int fait = cursor.getInt(10);
    final CheckBox cbdevoir = (CheckBox) view.findViewById(R.id.CBDevoir);
    final TextView couleur = (TextView)view.findViewById(R.id.TVCouleurImportance);

    if(importance==0)
    {
        couleur.setBackgroundColor(Color.parseColor("#ff8080"));
    }
    if(importance==1)
    {
        couleur.setBackgroundColor(Color.parseColor("#ff0000"));
    }
    if(importance==2)
    {
        couleur.setBackgroundColor(Color.parseColor("#4d0000"));
    }

    if (fait == 1) {
        cbdevoir.setChecked(true);
    } else {
        cbdevoir.setChecked(false);
    }

    cbdevoir.setVisibility(devoir ==1? View.VISIBLE: View.GONE);`
</code>```

my list_row.xml:

```<code>`<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:id="@+id/item_root"
android:weightSum="1">

<CheckBox
    android:id="@+id/CBDevoir"
    android:layout_width="30dp"
    android:layout_height="20dp"
    android:layout_marginLeft="1dp"
    android:layout_marginTop="-1dp"
    android:checked="false"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/text_branche_cours"
    android:layout_width="75dp"
    android:layout_height="16dp"
    android:layout_marginLeft="32dp"
    android:layout_marginTop="2dp"
    android:text="English"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/text_trait"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=" - "
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="-1dp"
    android:layout_marginLeft="106dp"
    app:layout_constraintLeft_toLeftOf="parent" />

<TextView
    android:id="@+id/text_designation"
    android:layout_width="150dp"
    android:layout_height="18dp"
    android:layout_marginLeft="122dp"
    android:layout_marginTop="2dp"
    android:ellipsize="end"
    android:maxLines="1"
    android:text="Reading"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/TVCouleurImportance"
    android:layout_width="25dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="281dp"
    android:layout_marginTop="-1dp"
    android:layout_weight="1"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
</code>```

`

答:
Depending on the type of view you're using you can always remove the view from the layout.

For example you could take a linear layout and call .removeView(View) to remove the checkbox entirely instead of just making it invisible. Just remember that if you're recycling views you'll want a way to add it back in later!

I recommend the viewholder pattern.

 https://developer.android.com/training/improving-layouts/smooth-scrolling.html

Body:
I have a listView populated with the help of a CustomAdapter.

I make a test while retrieving the values from my db.

One of the rows if 'Homework'. If homework = 1, then I show a CheckBox in the beginning of the line of my listView. But if it's 0 , I dont show anything. But I'd like to move all the text after the checkbox to the left. in my list_row.xml I declared a checkbox, so if homework is 0, i just setVisibility to INVISIBLE on my checkbox.

I can't post images, so I'll give an example :

if homework is 1 , my listView is like this :

Checkbox - Date of creation - Title

if Homework is 0, my row of the listview is like this :

         - Date of creation - Title

So you can see that there will have an empty space if Homework is 0. How can I change that so it stays like this:

-Date of creation - Title

Thank you !And tell me if you need the code my CustomAdapter please

@UPDATE-my customadapter

`public class CustomAdapterJalons extends SimpleCursorAdapter {

private Context mContext;
private Context appContext;
private int layout;
private Cursor cr;
private final LayoutInflater inflater;

public CustomAdapterJalons(Context context, int layout, Cursor c, String[] from, int[] to) {
    super(context, layout, c, from, to);
    this.layout = layout;
    this.mContext = context;
    this.inflater = LayoutInflater.from(context);
    this.cr = c;
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    return inflater.inflate(layout, null);
}

@Override
public void bindView(View view, final Context context, final Cursor cursor) {
    super.bindView(view, context, cursor);

    final int position = cursor.getPosition();

    cursor.moveToPosition(position);

    int devoir = cursor.getInt(3);
    int evaluation = cursor.getInt(4);
    int importance = cursor.getInt(5);
    int fait = cursor.getInt(10);
    final CheckBox cbdevoir = (CheckBox) view.findViewById(R.id.CBDevoir);
    final TextView couleur = (TextView)view.findViewById(R.id.TVCouleurImportance);

    if(importance==0)
    {
        couleur.setBackgroundColor(Color.parseColor("#ff8080"));
    }
    if(importance==1)
    {
        couleur.setBackgroundColor(Color.parseColor("#ff0000"));
    }
    if(importance==2)
    {
        couleur.setBackgroundColor(Color.parseColor("#4d0000"));
    }

    if (fait == 1) {
        cbdevoir.setChecked(true);
    } else {
        cbdevoir.setChecked(false);
    }

    cbdevoir.setVisibility(devoir ==1? View.VISIBLE: View.GONE);`

my list_row.xml:

`<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:id="@+id/item_root"
android:weightSum="1">

<CheckBox
    android:id="@+id/CBDevoir"
    android:layout_width="30dp"
    android:layout_height="20dp"
    android:layout_marginLeft="1dp"
    android:layout_marginTop="-1dp"
    android:checked="false"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/text_branche_cours"
    android:layout_width="75dp"
    android:layout_height="16dp"
    android:layout_marginLeft="32dp"
    android:layout_marginTop="2dp"
    android:text="English"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/text_trait"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=" - "
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="-1dp"
    android:layout_marginLeft="106dp"
    app:layout_constraintLeft_toLeftOf="parent" />

<TextView
    android:id="@+id/text_designation"
    android:layout_width="150dp"
    android:layout_height="18dp"
    android:layout_marginLeft="122dp"
    android:layout_marginTop="2dp"
    android:ellipsize="end"
    android:maxLines="1"
    android:text="Reading"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/TVCouleurImportance"
    android:layout_width="25dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="281dp"
    android:layout_marginTop="-1dp"
    android:layout_weight="1"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

`


问:
How to check if a database table exist in PDO?
Something like this:</p>

```<code>$connection->executeQuery('check table historial1 in database $connection->executeQuery('show tables')')
</code>```

答:
```<code> $sql = "SHOW TABLES 'Table_Name' ";
    if($this->is_connected)
    {
        $query = $this->pdo->query($sql);
        return $query->fetchAll(PDO::FETCH_COLUMN);
    }
    return FALSE;
</code>```

Body:
Something like this:

$connection->executeQuery('check table historial1 in database $connection->executeQuery('show tables')')


问:
Got string Url but the url have "\/".How to get each correct value in string like array type swift3
I got a string from server,but the url string looks strange, and it also like array type. I don't know how to get each value. Sorry I am beginner.Thanks.

```<code>let string:String = "[\"http:\/\/aaa.com\/user\/head\/111.jpg?1495612713419\",\"http:\/\/aaa.com\/user\/head\/222.jpg?1496215823622\",\"http:\/\/aaa.com\/user\/head\/333.jpg?1495251220764\",\"http:\/\/aaa.com\/user\/head\/444.jpg?1495773694237\",\"http:\/\/aaa.com\/user\/head\/555.jpg?1495597839001\"]"

let tempArr = string.components(separatedBy: ",")
var stringArr = Array<String>()

for a in tempArr {
    var b = a.replacingOccurrences(of: "\"", with: "")
    b = b.replacingOccurrences(of: "[", with: "")
    b = b.replacingOccurrences(of: "]", with: "")
    stringArr.append(b)
}
print(stringArr)
</code>```

print log

```<code>["http:\\/\\/aaa.com\\/user\\/head\\/111.jpg?1495612713419", "http:\\/\\/aaa.com\\/user\\/head\\/222.jpg?1496215823622", "http:\\/\\/aaa.com\\/user\\/head\\/333.jpg?1495251220764", "http:\\/\\/aaa.com\\/user\\/head\\/444.jpg?1495773694237", "http:\\/\\/aaa.com\\/user\\/head\\/555.jpg?1495597839001"]
</code>```

答:
The \ is added as escaping character while the string is encoded to JSON and it seems you are directly using the JSON string without decoding it first. How are you getting this result? are you using Alamofire?. Please let me know to help you further.

```<code> func fetchMyImages() {
    let url = "some url to call the image api"
    let request = Alamofire.request(url)
    request.validate().responseJSON { [unowned self] (response) in
        switch response.result {
        case .success(let result):
            self.doSomething(with: result) //the result is Any object
        case .failure(let error):
            print("Oh my Error: \(error)")
        }
    }
}
</code>```

This will give you the JSON decoded object and then you can cast it appropriately to Dictionary if it is Dictionary or Array if it is Array

Body:
I got a string from server,but the url string looks strange, and it also like array type. I don't know how to get each value. Sorry I am beginner.Thanks.

let string:String = "[\"http:\/\/aaa.com\/user\/head\/111.jpg?1495612713419\",\"http:\/\/aaa.com\/user\/head\/222.jpg?1496215823622\",\"http:\/\/aaa.com\/user\/head\/333.jpg?1495251220764\",\"http:\/\/aaa.com\/user\/head\/444.jpg?1495773694237\",\"http:\/\/aaa.com\/user\/head\/555.jpg?1495597839001\"]"

let tempArr = string.components(separatedBy: ",")
var stringArr = Array<String>()

for a in tempArr {
    var b = a.replacingOccurrences(of: "\"", with: "")
    b = b.replacingOccurrences(of: "[", with: "")
    b = b.replacingOccurrences(of: "]", with: "")
    stringArr.append(b)
}
print(stringArr)

print log

["http:\\/\\/aaa.com\\/user\\/head\\/111.jpg?1495612713419", "http:\\/\\/aaa.com\\/user\\/head\\/222.jpg?1496215823622", "http:\\/\\/aaa.com\\/user\\/head\\/333.jpg?1495251220764", "http:\\/\\/aaa.com\\/user\\/head\\/444.jpg?1495773694237", "http:\\/\\/aaa.com\\/user\\/head\\/555.jpg?1495597839001"]

Body:
The \ is added as escaping character while the string is encoded to JSON and it seems you are directly using the JSON string without decoding it first. How are you getting this result? are you using Alamofire?. Please let me know to help you further.

 func fetchMyImages() {
    let url = "some url to call the image api"
    let request = Alamofire.request(url)
    request.validate().responseJSON { [unowned self] (response) in
        switch response.result {
        case .success(let result):
            self.doSomething(with: result) //the result is Any object
        case .failure(let error):
            print("Oh my Error: \(error)")
        }
    }
}

This will give you the JSON decoded object and then you can cast it appropriately to Dictionary if it is Dictionary or Array if it is Array


问:
Terraform - should I use user_data or provisioner to bootstrap a resource?
It seems like I can use either user_data with a template file or a "remote-exec" provisioner with inline commands to bootstrap. So which one is considered more idiomatic?

答:
You should use user_data. The user data field is idiomatic because it's native to AWS, whereas the remote-exec provisioner is specific to Terraform, which is just one of many ways to call the AWS API.

Also, the user-data is viewable in the AWS console, and often an important part of using Auto Scaling Groups in AWS, where you want each EC2 Instance to execute the same config code when it launches. It's not possible to do that with Terraform's remote-exec provisioner.


问:
How to Sum the values of a field based on month and year?
Crystal Report

Report

The report shown have two fields month and year. How can I sum the values of Count field after every month?

答:
You can use Running Total Field that available at the field explorer

1) The name of the field. Let say {Table A.Count}

2) Choose SUM


问:
What is the quickest way to determine why an integration test failed?
I have the following:

```<code>  test "should update deal" do
    patch user_deal_url(@user, @deal), params: { deal: { name: @deal.name+'xxx' } }
    # p @response.body
    # p @deal.errors.full_messages
    assert_select ".alert", false   # should not have alert
    assert_redirected_to dashboard_url
    follow_redirect!
    assert_select ".alert", "Deal was successfully updated."
  end
</code>```

It only says:

```<code>Failure:
DealsControllerTest#test_should_update_deal [C:/Users/Chloe/workspace/test/controllers/deals_controller_test.rb:73]:
Expected response to be a <3XX: redirect>, but was a <200: OK>
</code>```

I thought I could print @deal.errors.full_messages but it's not the same @deal in the controller. I'm able to print the entire response body and copy it into Notepad++ and search for the error messages, but it's so tedious. I thought I can assert that .alert doesn't exist and it would tell me what it actually was. I added

```<code>assert_select "#error_explanation", false   # should not have error
</code>```

But that only told me that it exists, not why it failed.

```<code>Expected exactly 0 elements matching "#error_explanation", found 1..
Expected: 0
  Actual: 1
</code>```

So how do you quickly determine why a model is failing to save or update in a controller during testing?

Rails 5.0.2

Reference: http://guides.rubyonrails.org/testing.html

My solution causes subsequent assert_select statements to fail! Just having puts css_select('#error_explanation') makes the last assert_select fail, but commenting it out makes it succeed. Why?

I entered a Rails bug for that in the mean time: https://github.com/rails/rails/issues/29367

答:
I was able to put

```<code>    puts css_select('#error_explanation')
</code>```

right after the put/patch and it prints

```<code># Running:

<div id="error_explanation">
<h2>
2 errors
prohibited this deal from being saved:
</h2>
<ul>
<li>Size can't be blank</li>
<li>Size is not a number</li>
</ul>
</div>
F

Failure:
</code>```

I'm still looking for something better as leaving this line in causes subsequent assert_selects to fail!

Body:
I have the following:

  test "should update deal" do
    patch user_deal_url(@user, @deal), params: { deal: { name: @deal.name+'xxx' } }
    # p @response.body
    # p @deal.errors.full_messages
    assert_select ".alert", false   # should not have alert
    assert_redirected_to dashboard_url
    follow_redirect!
    assert_select ".alert", "Deal was successfully updated."
  end

It only says:

Failure:
DealsControllerTest#test_should_update_deal [C:/Users/Chloe/workspace/test/controllers/deals_controller_test.rb:73]:
Expected response to be a <3XX: redirect>, but was a <200: OK>

I thought I could print @deal.errors.full_messages but it's not the same @deal in the controller. I'm able to print the entire response body and copy it into Notepad++ and search for the error messages, but it's so tedious. I thought I can assert that .alert doesn't exist and it would tell me what it actually was. I added

assert_select "#error_explanation", false   # should not have error

But that only told me that it exists, not why it failed.

Expected exactly 0 elements matching "#error_explanation", found 1..
Expected: 0
  Actual: 1

So how do you quickly determine why a model is failing to save or update in a controller during testing?

Rails 5.0.2

Reference: http://guides.rubyonrails.org/testing.html

My solution causes subsequent assert_select statements to fail! Just having puts css_select('#error_explanation') makes the last assert_select fail, but commenting it out makes it succeed. Why?

I entered a Rails bug for that in the mean time: https://github.com/rails/rails/issues/29367

Body:
I was able to put

    puts css_select('#error_explanation')

right after the put/patch and it prints

# Running:

<div id="error_explanation">
<h2>
2 errors
prohibited this deal from being saved:
</h2>
<ul>
<li>Size can't be blank</li>
<li>Size is not a number</li>
</ul>
</div>
F

Failure:

I'm still looking for something better as leaving this line in causes subsequent assert_selects to fail!


问:
"Hello TensorFlow!" using the C API
For learning purposes, how to code this Python example using the TensorFlow C API ?

```<code>import tensorflow as tf
hello = tf.constant("hello TensorFlow!")
sess=tf.Session()
print(sess.run(hello))
</code>```

I have tried it this way:

```<code>#include <string.h>
#include <iostream.h>
#include "c_api.h"

int main( int argc, char ** argv )
{
  TF_Graph * graph = TF_NewGraph();
  TF_SessionOptions * options = TF_NewSessionOptions();
  TF_Status * status = TF_NewStatus();
  TF_Session * session = TF_NewSession( graph, options, status );
  char hello[] = "Hello TensorFlow!";
  TF_Tensor * tensor = TF_AllocateTensor( TF_STRING, 0, 0, 8 + TF_StringEncodedSize( strlen( hello ) ) );
  TF_OperationDescription * operationDescription = TF_NewOperation( graph, "Const", "hello" );
  TF_Operation * operation;
  struct TF_Output * output;

  TF_StringEncode( hello, strlen( hello ), 8 + ( char * ) TF_TensorData( tensor ), TF_StringEncodedSize( strlen( hello ) ), status );
  TF_SetAttrTensor( operationDescription, "value", tensor, status );
  TF_SetAttrType( operationDescription, "dtype", TF_TensorType( tensor ) );
  operation = TF_FinishOperation( operationDescription, status );

  output->oper = operation;
  output->index = 0;

  TF_SessionRun( session, 0,
                 0, 0, 0,  // Inputs
                 output, &tensor, 1,  // Outputs
                 &operation, 1,  // Operations
                 0, status );

  printf( "%i", TF_GetCode( status ) );

  TF_CloseSession( session, status );
  TF_DeleteSession( session, status );
  TF_DeleteStatus( status );
  TF_DeleteSessionOptions( options );

  return 0;
}
</code>```

I am testing it on Windows using the TensorFlow.dll from:
http://ci.tensorflow.org/view/Nightly/job/nightly-libtensorflow-windows/lastSuccessfulBuild/artifact/lib_package/libtensorflow-cpu-windows-x86_64.zip

The above code GPFs on the TF_SessionRun() call. Once we find a solution for that, how to retrieve the output ? Should a different tensor be used for the
output ? The above code reuses it in both the output and the operation.

many thanks

答:
TF_STRING tensors are encoded using the format described here. In your code, you accounted for space (8 bytes) to encode the one offset, but didn't actually initialize it. To do that, you'd want to add something like:

memset(TF_TensorData(tensor), 0, 8);

Before the call to TF_SetAttrTensor, as that will set the "offset" of the string element to 0 (which the where you're encoding the one string value).

To your second question: You aren't actually re-using the same tensor pointer. The comments for TF_SessionRun suggest that TF_SessionRun is allocating a new TF_Tensor object that the caller takes ownership of. So, in your code snippet, the tensor variable is being overwritten to point to a newly allocated tensor.

Hope that helps.

Title: "Hello TensorFlow!" using the C API

Body:
For learning purposes, how to code this Python example using the TensorFlow C API ?

import tensorflow as tf
hello = tf.constant("hello TensorFlow!")
sess=tf.Session()
print(sess.run(hello))

I have tried it this way:

#include <string.h>
#include <iostream.h>
#include "c_api.h"

int main( int argc, char ** argv )
{
  TF_Graph * graph = TF_NewGraph();
  TF_SessionOptions * options = TF_NewSessionOptions();
  TF_Status * status = TF_NewStatus();
  TF_Session * session = TF_NewSession( graph, options, status );
  char hello[] = "Hello TensorFlow!";
  TF_Tensor * tensor = TF_AllocateTensor( TF_STRING, 0, 0, 8 + TF_StringEncodedSize( strlen( hello ) ) );
  TF_OperationDescription * operationDescription = TF_NewOperation( graph, "Const", "hello" );
  TF_Operation * operation;
  struct TF_Output * output;

  TF_StringEncode( hello, strlen( hello ), 8 + ( char * ) TF_TensorData( tensor ), TF_StringEncodedSize( strlen( hello ) ), status );
  TF_SetAttrTensor( operationDescription, "value", tensor, status );
  TF_SetAttrType( operationDescription, "dtype", TF_TensorType( tensor ) );
  operation = TF_FinishOperation( operationDescription, status );

  output->oper = operation;
  output->index = 0;

  TF_SessionRun( session, 0,
                 0, 0, 0,  // Inputs
                 output, &tensor, 1,  // Outputs
                 &operation, 1,  // Operations
                 0, status );

  printf( "%i", TF_GetCode( status ) );

  TF_CloseSession( session, status );
  TF_DeleteSession( session, status );
  TF_DeleteStatus( status );
  TF_DeleteSessionOptions( options );

  return 0;
}

I am testing it on Windows using the TensorFlow.dll from:
http://ci.tensorflow.org/view/Nightly/job/nightly-libtensorflow-windows/lastSuccessfulBuild/artifact/lib_package/libtensorflow-cpu-windows-x86_64.zip

The above code GPFs on the TF_SessionRun() call. Once we find a solution for that, how to retrieve the output ? Should a different tensor be used for the
output ? The above code reuses it in both the output and the operation.

many thanks


答:
Use setVisibility(View.GONE)

When you set view to gone, it doesn't take any space for that layout, while setting it to invisible does.

Title: Remove space of checkbox if it does not exist


问:
How to add, edit and delete utterances in Lex
I have added a few utterances and have some build errors (i think) due to not adding spaces between two slot names. When I build I get an error:

How do i edit or delete the utterances or solve this error

答: What had to be done is set the version next to the intent name (1) to LATEST.</p>


问:
Request["key"] vs Request.Params["key"] vs Request.QueryString["key"]
Request["key"] vs Request.Params["key"] vs Request.QueryString["key"]

Which method do you seasoned programmers use? and why?

答:
As a kindly notice, If you set requestValidationMode="4.5" under web.config, both Request.QueryString[“key”] and Request[“key”] will use "lazy loading" behavior as design.

However, somehow Request.Params[“key”] will still trigger validation as the behavior of 4.0 .

This odd behavior really confuses me for a long time.


问:
How to check if not available methods are used if deployment target < base sdk?
I would like to know how you check that your code do not call not available methods when the deployment target is inferior to base SDK ?

It is possible to run the application on a device with the SDK equal to deployment target, but I search a way more 'automatic'. Any idea ?

Regards,
Quentin

答:
Are you looking for something like
 - (BOOL)respondsToSelector:(SEL)aSelector</p>


问:
Post two statements into database
I am trying to insert two statements into my sql database. But when I click on send I see that only the first statement is posted.

Does someone know whats wrong with my code and how I can solve it?

Here is my code:

```<code>$query1 = "INSERT INTO table1(firstname, lastname) VALUES (?, ?)";
$stmt1 = $db->prepare($query1);
$stmt1->execute(array($firstname, $lastname));

$query2 = "INSERT INTO table2(firstname, lastname) VALUES (?, ?)";
$stmt2 = $db->prepare($query2);
$stmt2->execute(array($firstname, $lastname));
</code>```

答:
you cannot always assume that your query would always work. There are many reasons for query failures. Whenever you execute a query, you must check to see if everything went OK. ALso turn on error reporting as well as checking your error logs. The issue should also be reported there

The below modification would help in filtering out the problem for the query failure

```<code><?php
   error_reporting(E_ALL);

    $query2 = "INSERT INTO table2(`firstname`, `lastname`) VALUES (?, ?)";
    $stmt2 = $db->prepare($query2);
    if($stmt2->execute(array($firstname, $lastname))){//check if it saved
      echo 'Saved';
    } else {
      echo 'Failed Because '.$stmt2->error;//Oops something happened
    }
</code>```

Title: Post two statements into database

Body:
I am trying to insert two statements into my sql database. But when I click on send I see that only the first statement is posted.

Does someone know whats wrong with my code and how I can solve it?

Here is my code:

$query1 = "INSERT INTO table1(firstname, lastname) VALUES (?, ?)";
$stmt1 = $db->prepare($query1);
$stmt1->execute(array($firstname, $lastname));

$query2 = "INSERT INTO table2(firstname, lastname) VALUES (?, ?)";
$stmt2 = $db->prepare($query2);
$stmt2->execute(array($firstname, $lastname));

Body:
you cannot always assume that your query would always work. There are many reasons for query failures. Whenever you execute a query, you must check to see if everything went OK. ALso turn on error reporting as well as checking your error logs. The issue should also be reported there

The below modification would help in filtering out the problem for the query failure

<?php
   error_reporting(E_ALL);

    $query2 = "INSERT INTO table2(`firstname`, `lastname`) VALUES (?, ?)";
    $stmt2 = $db->prepare($query2);
    if($stmt2->execute(array($firstname, $lastname))){//check if it saved
      echo 'Saved';
    } else {
      echo 'Failed Because '.$stmt2->error;//Oops something happened
    }


答:
Your code will work too like below:-

```<code>foreach ($Array as $name)
{
    if (stristr($name,$Var1)!==false)
    {
        echo $name;
        echo PHP_EOL;
    }
}
</code>```

Output:- https://eval.in/812376

You can use php strpos() function also for this purpose

```<code>foreach($Array as $name)
{
   if (  strpos($name,$Var1)!==false)
   {
     echo $name;
     echo PHP_EOL;
   }
}
</code>```

Output:-https://eval.in/812371

Note:- In Both function the first argument is the string in which you want to search the sub-string. And second argument is sub-string itself.

Title: How to find elements in array that contain a given substring?

Body:
Your code will work too like below:-

foreach ($Array as $name)
{
    if (stristr($name,$Var1)!==false)
    {
        echo $name;
        echo PHP_EOL;
    }
}

Output:- https://eval.in/812376

You can use php strpos() function also for this purpose

foreach($Array as $name)
{
   if (  strpos($name,$Var1)!==false)
   {
     echo $name;
     echo PHP_EOL;
   }
}

Output:-https://eval.in/812371

Note:- In Both function the first argument is the string in which you want to search the sub-string. And second argument is sub-string itself.


问:
Does terms-lookup-filter aggregation order in elasticsearch query affect the execution time (efficiency)?
I have following elasticsearch query with terms-lookup-filter aggregation. Both queries will give the same result. Both queries have same filter type only the difference is order (place) of terms-lookup-filter.

1.Here terms-lookup filter is in 2nd/last position of and filter aggregation.

```<code>  {
   "size": 0,
   "aggs": {
      "filterAggs": {
         "filter": {
            "and": {
               "filters": [
                  {
                     "range": {
                        "eligibleDates": {
                           "include_lower": true,
                           "include_upper": true,
                           "from": <fromDate>,
                           "to": <toDate>
                        }
                     }
                  },
                  {
                     "terms": {
                        "rollNo": {
                           "path": "student.rollNo",
                           "index": "<index_name>",
                           "id": "<record_id>",
                           "type": "<es Type>"
                        }
                     }
                  }
               ]
            }
         }
      }
   }
}
</code>```

2.Here terms-lookup filter is in 1st position of and filter aggregation.

```<code>{
   "size": 0,
   "aggs": {
      "filterAggs": {
         "filter": {
            "and": {
               "filters": [
                  {
                     "terms": {
                        "rollNo": {
                           "path": "student.rollNo",
                           "index": "<index_name>",
                           "id": "<record_id>",
                           "type": "<es Type>"
                        }
                     }
                  },
                  {
                     "range": {
                        "eligibleDates": {
                           "include_lower": true,
                           "include_upper": true,
                           "from": <fromDate>,
                           "to": <toDate>
                        }
                     }
                  }
               ]
            }
         }
      }
   }
}
</code>```

In my experiment/test, 1st query executes more efficiently (7 to 10 times faster) than the second one.
 Now my question is, Does terms-lookup-filter aggregation order in elasticsearch query affect the execution time (efficiency)?  How will the filter place order affect execution time?

答:
No It doesn't matter because elasticsearch would find the optimized execution order by specific algorithms.

I've seen in some articles they say you should order the filters/queries by some critera (e.g. which one is more filtery should go first) but after reading a very detailed and exact article found out they are not correct.
This is  great article about filter/query execution order in elasticsearch:

In which order are my Elasticsearch queries/filters executed?

If you want to optimize your query I will suggest you to read this:

Optimizing Elasticsearch Searches

For example you have range filter and it could be optimized using the Cache Granularity and Acceleration Filters part.

Body:
I have following elasticsearch query with terms-lookup-filter aggregation. Both queries will give the same result. Both queries have same filter type only the difference is order (place) of terms-lookup-filter.

1.Here terms-lookup filter is in 2nd/last position of and filter aggregation.

  {
   "size": 0,
   "aggs": {
      "filterAggs": {
         "filter": {
            "and": {
               "filters": [
                  {
                     "range": {
                        "eligibleDates": {
                           "include_lower": true,
                           "include_upper": true,
                           "from": <fromDate>,
                           "to": <toDate>
                        }
                     }
                  },
                  {
                     "terms": {
                        "rollNo": {
                           "path": "student.rollNo",
                           "index": "<index_name>",
                           "id": "<record_id>",
                           "type": "<es Type>"
                        }
                     }
                  }
               ]
            }
         }
      }
   }
}

2.Here terms-lookup filter is in 1st position of and filter aggregation.

{
   "size": 0,
   "aggs": {
      "filterAggs": {
         "filter": {
            "and": {
               "filters": [
                  {
                     "terms": {
                        "rollNo": {
                           "path": "student.rollNo",
                           "index": "<index_name>",
                           "id": "<record_id>",
                           "type": "<es Type>"
                        }
                     }
                  },
                  {
                     "range": {
                        "eligibleDates": {
                           "include_lower": true,
                           "include_upper": true,
                           "from": <fromDate>,
                           "to": <toDate>
                        }
                     }
                  }
               ]
            }
         }
      }
   }
}

In my experiment/test, 1st query executes more efficiently (7 to 10 times faster) than the second one.
 Now my question is, Does terms-lookup-filter aggregation order in elasticsearch query affect the execution time (efficiency)?  How will the filter place order affect execution time?


问:
Amazon S3: SDK or REST API
I have to use Amazon S3 to upload some static contents programmatically in Java.
When I started reading I found that the way to do is either through their SDK (wrapper over REST APIs) or using REST APIs. From Amazon's AWS website, found this:

"You can send requests to Amazon S3 using the REST API or the AWS SDK".

Wanted to understand that which approach is better. I think using SDK will definitely make programming easier, but what are the pros and cons of using SDK Vs Rest APIs directly.

For some reason, I found using REST API directly more difficult than SDK.
I was able to do basic things using SDk - create bucket, list objects, get object, invalidate cache etc.
But was having some hard time writing the code for REST API - especially generating the signature.

May be it will not matter much, if I ultimately use SDK, but I would still like to know how to do it using REST APIs. If anyone has some good code examples in Java on adding objects, get objects, get list etc, it would be very helpful.

Thanks!

答: In my own Opinion the API gives you room to do whatever you like.it also helps if you plan on changing a cloud service in the future but if the sdk approach is used, you will have to code again as your app will require a change and the SDK is embedded within your app. I know the response is late but it might help someone.</p>

Title: Amazon S3: SDK or REST API