问:
How can i parse only the numbers from the string?
I want that in Rect.rectangles under the transform property instead to have the string "matrix(0.87142591,0.49052715,-0.49052715,0.87142591,0,0)" to have 2 properties like transform and transform1 and each one will have a number for example: transform "0.12345678"
         transform1 "1.12345678"

```<code>private void Parse()
    {
        XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");

        Rect.rectangles = document.Descendants().Where(x => x.Name.LocalName == "rect").Select(x => new Rect()
        {
            style = Rect.GetStyle((string)x.Attribute("style")),
            id = (string)x.Attribute("id"),
            width = (double)x.Attribute("width"),
            height = (double)x.Attribute("width"),
            x = (double?)x.Attribute("width"),
            y = (double?)x.Attribute("width"),
            transform = x.Attribute("transform".Substring(18, 43)) == null ? "" : (string)x.Attribute("transform".Substring(18, 43))
        }).ToList();
    }
</code>```

And the Rect class:

```<code>public class Rect
    {
        public static List<Rect> rectangles { get; set; }
        public Dictionary<string, string> style { get; set; }
        public string id { get; set; }
        public double width { get; set; }
        public double height { get; set; }
        public double? x { get; set; }
        public double? y { get; set; }
        public string transform { get; set; }

        public static Dictionary<string, string> GetStyle(string styles)
        {
            string pattern = @"(?'name'[^:]+):(?'value'.*)";
            string[] splitArray = styles.Split(new char[] { ';' });
            Dictionary<string, string> style = splitArray.Select(x => Regex.Match(x, pattern))
                .GroupBy(x => x.Groups["name"].Value, y => y.Groups["value"].Value)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
            return style;
        }
    }
</code>```

I'm trying to use substring but getting out of range exception.

ArgumentOutOfRangeException: Cannot exceed length of string

On the line:

```<code>transform = x.Attribute("transform".Substring(18, 43)) == null ? "" : (string)x.Attribute("transform".Substring(18, 43))
</code>```

The string is:

transform="matrix(0.40438612,-0.91458836,0.92071162,0.39024365,0,0)"

And i want to get only the first two numbers: 0.40438612,-0.91458836

Update:

I found also a way to do it using foreach:

```<code>private void Parse()
    {
        XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");

        Rect.rectangles = document.Descendants().Where(x => x.Name.LocalName == "rect").Select(x => new Rect()
        {
            style = Rect.GetStyle((string)x.Attribute("style")),
            id = (string)x.Attribute("id"),
            width = (double)x.Attribute("width"),
            height = (double)x.Attribute("width"),
            x = (double?)x.Attribute("width"),
            y = (double?)x.Attribute("width"),
            transform = x.Attribute("transform") == null ? "" : (string)x.Attribute("transform")
        }).ToList();
        string t = null;
        foreach(Rect rect in Rect.rectangles)
        {
            if (rect.transform != null && rect.transform != "")
            {
                t = rect.transform.Substring(7, 21);
            }
        }
    }
</code>```

But i don't want to do it after the new Rect() {
I want to do the first two numbers extraction on the line:

```<code>transform = x.Attribute("transform") == null ? "" : (string)x.Attribute("transform")
</code>```

The reason is that i have in the bottom of the code a class:

```<code>public class Rect
    {
        public static List<Rect> rectangles { get; set; }
        public Dictionary<string, string> style { get; set; }
        public string id { get; set; }
        public double width { get; set; }
        public double height { get; set; }
        public double? x { get; set; }
        public double? y { get; set; }
        public string transform { get; set; }

        public static Dictionary<string, string> GetStyle(string styles)
        {
            string pattern = @"(?'name'[^:]+):(?'value'.*)";
            string[] splitArray = styles.Split(new char[] { ';' });
            Dictionary<string, string> style = splitArray.Select(x => Regex.Match(x, pattern))
                .GroupBy(x => x.Groups["name"].Value, y => y.Groups["value"].Value)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
            return style;
        }
    }
</code>```

And i want that the property transform to hold/contain the two numbers already.

And another small problem how can i extract the first two numbers if for example one of the numbers have -(minus) in the start for example if transform contain the string: "matrix(0.40438612,-0.91458836,0.92071162,0.39024365,0,0)"

If one of the two numbers have minus in the start or both of them have minus in the start the Substring(7, 21) will not work. I need somehow to get in any case the first two numbers. But the main issue is how to extract the numbers directly from the attribute already.

答:
Here is the best answer</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            Rect.rectangles = doc.Descendants().Where(x => x.Name.LocalName == "rect").Select(x => new Rect()
            {
                style = Rect.GetStyle((string)x.Attribute("style")),
                id = (string)x.Attribute("id"),
                width = (double)x.Attribute("width"),
                height = (double)x.Attribute("width"),
                x = (double?)x.Attribute("width"),
                y = (double?)x.Attribute("width"),
                transform = x.Attribute("transform") == null ? null : (object)Rect.GetTransform((string)x.Attribute("transform"))
            }).ToList();

        }
    }
    public class Rect
    {
        public static List<Rect> rectangles { get; set; }
        public Dictionary<string, string> style { get; set; }
        public string id { get; set; }
        public double width { get; set; }
        public double height { get; set; }
        public double? x { get; set; }
        public double? y { get; set; }
        public object transform { get; set; }

        public static Dictionary<string, string> GetStyle(string styles)
        {
            string pattern = @"(?'name'[^:]+):(?'value'.*)";
            string[] splitArray = styles.Split(new char[] { ';' });
            Dictionary<string, string> style = splitArray.Select(x => Regex.Match(x, pattern))
                .GroupBy(x => x.Groups["name"].Value, y => y.Groups["value"].Value)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
            return style;
        }
        public static KeyValuePair<double, double> GetTransform(string matrix)
        {
            string pattern = @"[-+]?\d+\.\d+";
            MatchCollection matches = Regex.Matches(matrix, pattern);
            KeyValuePair<double, double> kp = new KeyValuePair<double, double>(
                double.Parse(matches[0].Value),
                double.Parse(matches[0].Value)
                );

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

Body:
I want that in Rect.rectangles under the transform property instead to have the string "matrix(0.87142591,0.49052715,-0.49052715,0.87142591,0,0)" to have 2 properties like transform and transform1 and each one will have a number for example: transform "0.12345678"
         transform1 "1.12345678"

private void Parse()
    {
        XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");

        Rect.rectangles = document.Descendants().Where(x => x.Name.LocalName == "rect").Select(x => new Rect()
        {
            style = Rect.GetStyle((string)x.Attribute("style")),
            id = (string)x.Attribute("id"),
            width = (double)x.Attribute("width"),
            height = (double)x.Attribute("width"),
            x = (double?)x.Attribute("width"),
            y = (double?)x.Attribute("width"),
            transform = x.Attribute("transform".Substring(18, 43)) == null ? "" : (string)x.Attribute("transform".Substring(18, 43))
        }).ToList();
    }

And the Rect class:

public class Rect
    {
        public static List<Rect> rectangles { get; set; }
        public Dictionary<string, string> style { get; set; }
        public string id { get; set; }
        public double width { get; set; }
        public double height { get; set; }
        public double? x { get; set; }
        public double? y { get; set; }
        public string transform { get; set; }

        public static Dictionary<string, string> GetStyle(string styles)
        {
            string pattern = @"(?'name'[^:]+):(?'value'.*)";
            string[] splitArray = styles.Split(new char[] { ';' });
            Dictionary<string, string> style = splitArray.Select(x => Regex.Match(x, pattern))
                .GroupBy(x => x.Groups["name"].Value, y => y.Groups["value"].Value)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
            return style;
        }
    }

I'm trying to use substring but getting out of range exception.

ArgumentOutOfRangeException: Cannot exceed length of string

On the line:

transform = x.Attribute("transform".Substring(18, 43)) == null ? "" : (string)x.Attribute("transform".Substring(18, 43))

The string is:

transform="matrix(0.40438612,-0.91458836,0.92071162,0.39024365,0,0)"

And i want to get only the first two numbers: 0.40438612,-0.91458836

Update:

I found also a way to do it using foreach:

private void Parse()
    {
        XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");

        Rect.rectangles = document.Descendants().Where(x => x.Name.LocalName == "rect").Select(x => new Rect()
        {
            style = Rect.GetStyle((string)x.Attribute("style")),
            id = (string)x.Attribute("id"),
            width = (double)x.Attribute("width"),
            height = (double)x.Attribute("width"),
            x = (double?)x.Attribute("width"),
            y = (double?)x.Attribute("width"),
            transform = x.Attribute("transform") == null ? "" : (string)x.Attribute("transform")
        }).ToList();
        string t = null;
        foreach(Rect rect in Rect.rectangles)
        {
            if (rect.transform != null && rect.transform != "")
            {
                t = rect.transform.Substring(7, 21);
            }
        }
    }

But i don't want to do it after the new Rect() {
I want to do the first two numbers extraction on the line:

transform = x.Attribute("transform") == null ? "" : (string)x.Attribute("transform")

The reason is that i have in the bottom of the code a class:

public class Rect
    {
        public static List<Rect> rectangles { get; set; }
        public Dictionary<string, string> style { get; set; }
        public string id { get; set; }
        public double width { get; set; }
        public double height { get; set; }
        public double? x { get; set; }
        public double? y { get; set; }
        public string transform { get; set; }

        public static Dictionary<string, string> GetStyle(string styles)
        {
            string pattern = @"(?'name'[^:]+):(?'value'.*)";
            string[] splitArray = styles.Split(new char[] { ';' });
            Dictionary<string, string> style = splitArray.Select(x => Regex.Match(x, pattern))
                .GroupBy(x => x.Groups["name"].Value, y => y.Groups["value"].Value)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
            return style;
        }
    }

And i want that the property transform to hold/contain the two numbers already.

And another small problem how can i extract the first two numbers if for example one of the numbers have -(minus) in the start for example if transform contain the string: "matrix(0.40438612,-0.91458836,0.92071162,0.39024365,0,0)"

If one of the two numbers have minus in the start or both of them have minus in the start the Substring(7, 21) will not work. I need somehow to get in any case the first two numbers. But the main issue is how to extract the numbers directly from the attribute already.

Body:
Here is the best answer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            Rect.rectangles = doc.Descendants().Where(x => x.Name.LocalName == "rect").Select(x => new Rect()
            {
                style = Rect.GetStyle((string)x.Attribute("style")),
                id = (string)x.Attribute("id"),
                width = (double)x.Attribute("width"),
                height = (double)x.Attribute("width"),
                x = (double?)x.Attribute("width"),
                y = (double?)x.Attribute("width"),
                transform = x.Attribute("transform") == null ? null : (object)Rect.GetTransform((string)x.Attribute("transform"))
            }).ToList();

        }
    }
    public class Rect
    {
        public static List<Rect> rectangles { get; set; }
        public Dictionary<string, string> style { get; set; }
        public string id { get; set; }
        public double width { get; set; }
        public double height { get; set; }
        public double? x { get; set; }
        public double? y { get; set; }
        public object transform { get; set; }

        public static Dictionary<string, string> GetStyle(string styles)
        {
            string pattern = @"(?'name'[^:]+):(?'value'.*)";
            string[] splitArray = styles.Split(new char[] { ';' });
            Dictionary<string, string> style = splitArray.Select(x => Regex.Match(x, pattern))
                .GroupBy(x => x.Groups["name"].Value, y => y.Groups["value"].Value)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
            return style;
        }
        public static KeyValuePair<double, double> GetTransform(string matrix)
        {
            string pattern = @"[-+]?\d+\.\d+";
            MatchCollection matches = Regex.Matches(matrix, pattern);
            KeyValuePair<double, double> kp = new KeyValuePair<double, double>(
                double.Parse(matches[0].Value),
                double.Parse(matches[0].Value)
                );

            return kp;
        }
    }
}


来源: stackexchange

问:
Change image of specific clicked element
I would like to toggle the src of the specific image element clicked. But, only for that image. In other words, only toggle the one clicked. If clicked again then change back. How can I do this with jQuery or JavaScript. The code can be seen here: https://codepen.io/centem/pen/NgKEmG

```<code><!--
When image clicked change image to:
https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png
-->

<ul class="list-unstyled">

<li>Username<span class="pull-right">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png"></span><span class="pull-right">
<img src="http://pngimg.com/uploads/firefox/firefox_PNG16.png"></span><span class="pull-right">
<img src="https://ma.ttias.be/wp-content/uploads/2015/07/internet-explorer-logo.png"></span></li>

<li>Username<span class="pull-right">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png"></span><span class="pull-right">
<img src="http://pngimg.com/uploads/firefox/firefox_PNG16.png"></span><span class="pull-right">
<img src="https://ma.ttias.be/wp-content/uploads/2015/07/internet-explorer-logo.png"></span></li></li>

<li>Username<span class="pull-right">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png"></span><span class="pull-right">
<img src="http://pngimg.com/uploads/firefox/firefox_PNG16.png"></span><span class="pull-right">
<img src="https://ma.ttias.be/wp-content/uploads/2015/07/internet-explorer-logo.png"></span></li></li>

</ul>
</code>```

Here is my jquery:

```<code>    function handler( event ) {
  var target = $( event.target );
  if ( target.is( "img" ) ) {
    target.src().toggle(
"https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png");
  }
}
</code>```

Thank you.

答:
add an ID to your image and then try this:

```<code>$(function() {
    $("#yourImage").onClick(function() {
            $(this).attr("src", "https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png");
        });
});
</code>```

Alternatively, you can change the image depending on the source like this:

```<code>$(function() {
        $("img").onClick(function() {
                if ($(this).attr("src") == "OriginalSource")
                    $(this).attr("src", "https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png");
            });
    });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to toggle the src of the specific image element clicked. But, only for that image. In other words, only toggle the one clicked. If clicked again then change back. How can I do this with jQuery or JavaScript. The code can be seen here: https://codepen.io/centem/pen/NgKEmG

Username

Username

Username

Here is my jquery:

    function handler( event ) {
  var target = $( event.target );
  if ( target.is( "img" ) ) {
    target.src().toggle(
"https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png");
  }
}

Thank you.

Body:
add an ID to your image and then try this:

$(function() {
    $("#yourImage").onClick(function() {
            $(this).attr("src", "https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png");
        });
});

Alternatively, you can change the image depending on the source like this:

$(function() {
        $("img").onClick(function() {
                if ($(this).attr("src") == "OriginalSource")
                    $(this).attr("src", "https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png");
            });
    });


问:
Generating slides in Beamer from R Markdown if condition is met
When creating a beamer presentation from R Markdown (with R studio), I sometimes need to create extra slides that contain additional information.

I’m wondering how do I create a new slide only if a condition is met?

答:
```<code>---
title: "Untitled"
output: beamer_presentation
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

## R Markdown

Some Text

```{r, results='asis'}
if(TRUE){

  cat("## Conditional Slide")
  cat('\n')
  cat("First Conditional Slide")

}
```

```{r, results='asis'}
if(FALSE){

  cat("## Conditional Slide")
  cat('\n')
  cat("Second Conditional Slide")

}
```
</code>```


问:
Why are Cognito custom attributes not received in Lambda
I am using a "Cognito User Pool authorizer" (no "AWS_IAM" option, no custom coded authorizer) to call Lambda methods as HTTPS via API Gateway.

On Lambda, I set a custom user attribute custom:partnerId via adminUpdateUserAttributes under some circumstances.

I can verify that it has been set correctly via the Cognito User Pools AWS console.

On the iOS client, I can also successfully get all user attributes (including the custom one) as described in my answer at How to get Cognito user pool "sub" attribute on iOS

The problem is this:

I do not receive this custom attribute in Lambda as
event.requestContext.authorizer.claims['custom:partnerId'] with the next API requests

until I force the user to sign in explicitly again (with username/password) on the iOS client.

After this explicit sign in, I then receive the custom attribute included in the authorizer.claims parameters as expected.

I don't know whether this is a API Gateway problem (since I assume it is fetching the Cognito user via the HTTP "Authorization" header), a problem with the iOS Cognito SDK, or a problem with Lambda itself.

答: Cognito User Pool Authorizer in API gateway uses the Id token issued by Cognito. This Id token is valid for 1 hour and automatically gets refreshed by the iOS SDK by calling Cognito refresh API internally. After refresh, the Id Token will have the latest values. Refresh method is not available in high level SDK since it is implicitly called by SDK. But you can use low level SDK and directly call refresh API, this will give you the latest Id Token. (I am a developer from Cognito team and will take this as a feature request to allow ability to refresh from high level SDK.)</p>


问:
Can i publish android studio project on iphone app store?
I am still a beginner and I really don't know much and am working on my first app on android studio.
So is it possible to publish android studio project on iPhone App Store? If not is there any other way to do that?</p>

答:
There is no way to do it as both have platform specific. So use their respective platform so audience can reach easily.

Mixing up of different platform caused confusion so follow each website rules.


问:
I want the hyperlink to be in a different place
I am looking to put the hyperlink in a different place. How can I move the google.com link to another place on the page?</p>

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>Randy's first html web page !</title>
<style type="text/css">
body
{background-image:url('Koala.gif');}
h1
{
text-align:center;
font-size:500%;
}
h2
{
text-align:center;
font-size:250%;
}
p
{
text-align:center;
font-size:200%;
color:#00fff0;
}
div
{
background-color:#efffff;
}
a
{
text-align:center;
}
th
{
background-color:green;
}
tr
{
background-color:green;
}
table
{
width: 200px;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<h1> Hello Professor</h1>
<h2> By: Randy White</h2>
<P> It's getting better as the term goes on.</P>
<P>Week 2</P>
<P><img src="Hydrangeas.jpg" width="150" height="100" alt="Hydrangeas.jpg"></P>
<table border="1">
<tr>
<th>Month</th>
<th>Day</th>
<th>Year</th>
 </tr>
<tr>
<td>December</td>
<td>13</td>
<td>2010</td>
 </tr>
 </table>
 <a href="http://www.google.com">Visit Google!</a>
</body>
</html>
</code>```

答:
Your html is missing an opening  tag!

add "text-align:center;" to your css for the body tag.

ContentLicense: CC BY-SA 2.5

Body:
I am looking to put the hyperlink in a different place. How can I move the google.com link to another place on the page?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">

<title>Randy's first html web page !</title>

 Hello Professor

 By: Randy White

 It's getting better as the term goes on.

Week 2

Month
Day
Year

December
13
2010

 Visit Google!

Body:
Your html is missing an opening < body> tag!

add "text-align:center;" to your css for the body tag.


答:
You can add click event on img that exist in ul and toggle src of them by saving in data attribute. For toggling you need to save main src of image that can be saved as data-src (or anything else), And you need a flag for state of image like data-clicked (or anything else).

$('ul.list-unstyled li img').on('click', function(){
  var clicked = $(this).data('clicked');
  if(clicked === '1') {
    $(this).attr('src', $(this).data('src'))
    $(this).data('clicked', '0')
  } else {
    $(this).data('src', $(this).attr('src'))
    $(this).attr('src', "https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png");
    $(this).data('clicked', '1')
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>  img {
   height: 25px;
      padding-right: 4px;
  }
  li {
   margin: 4px;
      clear: both;
  }
  li:nth-child(odd) {
   background: #f0f0f5;
  }</code>```

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

Username

Username

Username

```

Title: Change image of specific clicked element

Body:
You can add click event on img that exist in ul and toggle src of them by saving in data attribute. For toggling you need to save main src of image that can be saved as data-src (or anything else), And you need a flag for state of image like data-clicked (or anything else).

$('ul.list-unstyled li img').on('click', function(){
  var clicked = $(this).data('clicked');
  if(clicked === '1') {
    $(this).attr('src', $(this).data('src'))
    $(this).data('clicked', '0')
  } else {
    $(this).data('src', $(this).attr('src'))
    $(this).attr('src', "https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png");
    $(this).data('clicked', '1')
  }
})

  img {
   height: 25px;
      padding-right: 4px;
  }
  li {
   margin: 4px;
      clear: both;
  }
  li:nth-child(odd) {
   background: #f0f0f5;
  }

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--
When image clicked change image to:
https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png
-->

<ul class="list-unstyled">

<li>Username<span class="pull-right">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png"></span><span class="pull-right">
<img src="http://pngimg.com/uploads/firefox/firefox_PNG16.png"></span><span class="pull-right">
<img src="https://ma.ttias.be/wp-content/uploads/2015/07/internet-explorer-logo.png"></span></li>

<li>Username<span class="pull-right">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png"></span><span class="pull-right">
<img src="http://pngimg.com/uploads/firefox/firefox_PNG16.png"></span><span class="pull-right">
<img src="https://ma.ttias.be/wp-content/uploads/2015/07/internet-explorer-logo.png"></span></li></li>

<li>Username<span class="pull-right">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png"></span><span class="pull-right">
<img src="http://pngimg.com/uploads/firefox/firefox_PNG16.png"></span><span class="pull-right">
<img src="https://ma.ttias.be/wp-content/uploads/2015/07/internet-explorer-logo.png"></span></li></li>

</ul>


问:
how to set textfield placeholder value from localisable.string file in objective c.?
I can't set placeholder for textfield.I have to change it accoding to the language choosen for app,so that it should set from localizable string file.

I tried this code

```<code>_emailTextField.placeholder = NSLocalizedString(@"EMAIL_OR_MOBILE", nil);
</code>```

but it is not working.

答:
Your code is perfectly fine. Check that:

Your strings files is called Localizable.strings

It is copied into the application bundle. Check the 'Copy' build phahse, it should be listed there.

The key @"EMAIL_OR_MOBILE" is presented in all languages of the strings file.

Try cleaning the project.

For me it was the first one.

Edit: in the project info tab, under Localization, did you add your second language?

Body:
I can't set placeholder for textfield.I have to change it accoding to the language choosen for app,so that it should set from localizable string file.

I tried this code

_emailTextField.placeholder = NSLocalizedString(@"EMAIL_OR_MOBILE", nil);

but it is not working.


问:
Get all XML nodes of given XSD type
i would like to get all XML nodes of given XSD type.

For example (see code snippets below)

for XSD type ListA, it should find only 1 node - MyLists/MyListA

for XSD type ItemType, it should find 4 nodes - 2x MyLists/MyListA/ItemA and 2x MyLists/MyListB/ItemB, but not nodes inside MyLists/MyListC/, because they are type of CustomItemType (although they have same name - type is different).

Is there a java library, that can provide this functionality?

Or any ideas how to solve this manually? The XSD can be very complex, with imports other schemas, etc.
I was thinking about generate all possible xPaths to nodes with given type by traversing XSD schema (there will be no recursion) and then apply them on XML file and check if some nodes are found.

XSD example

```<code><xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'
           xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>

  <xs:complexType name="ListA">
    <xs:sequence>
      <xs:element name="ItemA" type="ItemType" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="ListB">
    <xs:sequence>
      <xs:element name="ItemB" type="ItemType" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="AnotherList">
    <xs:sequence>
      <xs:element name="ItemA" type="CustomItemType" maxOccurs="unbounded"/>
      <xs:element name="ItemB" type="CustomItemType" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="ItemType">
    <xs:sequence>
      <xs:element name="ID"  type="xs:string" />
      <xs:element name="Value" type="xs:string" />
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="CustomItemType">
    <xs:sequence>
      <xs:element name="ID"  type="xs:string" />
      <xs:element name="Value" type="xs:string" />
    </xs:sequence>
  </xs:complexType>

  <xs:element name="MyLists">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="MyListA" type="ListA" />
        <xs:element name="MyListB" type="ListB" />
        <xs:element name="MyListC" type="AnotherList" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>
</code>```

XML example

```<code><MyLists>
  <MyListA>
    <ItemA>
      <ID>1</ID>
      <Value>A1</Value>
    </ItemA>
    <ItemA>
      <ID>2</ID>
      <Value>A2</Value>
    </ItemA>
  </MyListA>
  <MyListB>
    <ItemB>
      <ID>1</ID>
      <Value>B1</Value>
    </ItemB>
    <ItemB>
      <ID>2</ID>
      <Value>B2</Value>
    </ItemB>
  </MyListB>
  <MyListC>
    <ItemA>
      <ID>1</ID>
      <Value>A1</Value>
    </ItemA>
    <ItemB>
      <ID>2</ID>
      <Value>B1</Value>
    </ItemB>
  </MyListC>
</MyLists>
</code>```

答: You can solve that with schema-aware XPath 2.0 or later or schema-aware XQuery 1.0 or later by using a test like //element(*, YourGlobalTypeName) (https://www.w3.org/TR/xpath20/#prod-xpath-ElementTest), so with your sample the test //element(*, ListA) returns one element and //element(*, ItemType) returns four elements. In the Java world schema-aware XPath 2.0/3.0/3.1 and XQuery 1.0/3.0/3.1 is supported by Saxon 9 EE, there are also various XQuery implementations like exist-db or basex but I am not sure whether they support schema-aware XQuery.

Title: Get all XML nodes of given XSD type

Body:
i would like to get all XML nodes of given XSD type.

For example (see code snippets below)

for XSD type ListA, it should find only 1 node - MyLists/MyListA

for XSD type ItemType, it should find 4 nodes - 2x MyLists/MyListA/ItemA and 2x MyLists/MyListB/ItemB, but not nodes inside MyLists/MyListC/, because they are type of CustomItemType (although they have same name - type is different).

Is there a java library, that can provide this functionality?

Or any ideas how to solve this manually? The XSD can be very complex, with imports other schemas, etc.
I was thinking about generate all possible xPaths to nodes with given type by traversing XSD schema (there will be no recursion) and then apply them on XML file and check if some nodes are found.

XSD example

<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'
           xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>

  <xs:complexType name="ListA">
    <xs:sequence>
      <xs:element name="ItemA" type="ItemType" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="ListB">
    <xs:sequence>
      <xs:element name="ItemB" type="ItemType" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="AnotherList">
    <xs:sequence>
      <xs:element name="ItemA" type="CustomItemType" maxOccurs="unbounded"/>
      <xs:element name="ItemB" type="CustomItemType" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="ItemType">
    <xs:sequence>
      <xs:element name="ID"  type="xs:string" />
      <xs:element name="Value" type="xs:string" />
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="CustomItemType">
    <xs:sequence>
      <xs:element name="ID"  type="xs:string" />
      <xs:element name="Value" type="xs:string" />
    </xs:sequence>
  </xs:complexType>

  <xs:element name="MyLists">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="MyListA" type="ListA" />
        <xs:element name="MyListB" type="ListB" />
        <xs:element name="MyListC" type="AnotherList" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

XML example

<MyLists>
  <MyListA>
    <ItemA>
      <ID>1</ID>
      <Value>A1</Value>
    </ItemA>
    <ItemA>
      <ID>2</ID>
      <Value>A2</Value>
    </ItemA>
  </MyListA>
  <MyListB>
    <ItemB>
      <ID>1</ID>
      <Value>B1</Value>
    </ItemB>
    <ItemB>
      <ID>2</ID>
      <Value>B2</Value>
    </ItemB>
  </MyListB>
  <MyListC>
    <ItemA>
      <ID>1</ID>
      <Value>A1</Value>
    </ItemA>
    <ItemB>
      <ID>2</ID>
      <Value>B1</Value>
    </ItemB>
  </MyListC>
</MyLists>


问:
Rails app deploy using delayed job serving seemingly deleted files
I have a rails 4.2.3 app running on an ubuntu server with nginx, postgres, and puma and I'm using Capistrano for deployments.

Users of my app can send bulk emails out using several different email templates I provide and making use of the Delayed_Job gem. Recently, I updated two of the email templates and I've found that occasionally (maybe 20 times out of 500) an old version of the email template is sent out rather than the current version. I've combed through my application code and I'm satisfied that the old version of the template no longer exists anywhere in the application.

What's more, users are able to edit the template by providing their own body text, and, when an old version of an email template is sent, it is sent with the correct body text that the user specifies. It's as if there's an old version of my app running on the server that occasionally commandeers the sending of an email.

Is it possible that somehow as I update my deployment using Capistrano, the old application process remains running and sometimes starts working off the delayed_job queue? Capistrano only keeps the 5 most recent versions of my application though, and none of them have the old email template that is being used. So if this was the case the old application process would need to be entirely kept in memory--so this doesn't seem possible.

Anyone have any ideas I can pursue? I'm stumped as to what could be causing this (or how this problem is even possible). Thanks so much for any help!

(PS: emails make use of the premailer gem, though I don't see how that could be involved)

答:
The answer to this question was yes, "Is it possible that somehow as I update my deployment using Capistrano, the old application process remains running and sometimes starts working off the delayed_job queue?"

I was very surprised to find that, when you start a delayed job process, it serializes / saves into memory everything it needs to complete its tasks. A.K.A it saves / creates a new instance of the whole application, for practical purposes. Old delayed job processes weren't being properly killed when I pushed changes to my app, so I had something like 20 delayed job processes going at once. For the most part, the most recent delayed job process would take over the queue. If it was busy, however, old processes would butt in and start working off jobs using an old version of my application.

To fix the problem I had to kill off the old delayed job processes and then update my Capistrano code to make sure it wouldn't happen again.

Big thanks to @Dharam for leading me down the correct path (it's taken me a while to post this answer)


问:
Checking if this is null
Does it ever make sense to check if this is null?

Say I have a class with a method; inside that method, I check this == NULL, and if it is, return an error code.

If this is null, then that means the object is deleted. Is the method even able to return anything?

Update: I forgot to mention that the method can be called from multiple threads and it may cause the object to be deleted while another thread is inside the method.

答:
I know this is a old question, however I thought I will share my experience with use of Lambda capture

```<code>#include <iostream>
#include <memory>

using std::unique_ptr;
using std::make_unique;
using std::cout;
using std::endl;

class foo {
public:
    foo(int no) : no_(no) {

    }

    template <typename Lambda>
    void lambda_func(Lambda&& l) {
        cout << "No is " << no_ << endl;
        l();
    }

private:
    int no_;
};

int main() {
    auto f = std::make_unique<foo>(10);

    f->lambda_func([f = std::move(f)] () mutable {
        cout << "lambda ==> " << endl;
        cout << "lambda <== " << endl;
    });

    return 0;
}
</code>```

This code segment faults

```<code>$ g++ -std=c++14  uniqueptr.cpp
$ ./a.out
Segmentation fault (core dumped)
</code>```

If I remove the std::cout statement from lambda_func The code runs to completion.

It seems like, this statement f->lambda_func([f = std::move(f)] () mutable { processes lambda captures before member function is invoked.

Title: Checking if this is null

LastEditorDisplayName: Roger Pate

Body:
I know this is a old question, however I thought I will share my experience with use of Lambda capture

#include <iostream>
#include <memory>

using std::unique_ptr;
using std::make_unique;
using std::cout;
using std::endl;

class foo {
public:
    foo(int no) : no_(no) {

    }

    template <typename Lambda>
    void lambda_func(Lambda&& l) {
        cout << "No is " << no_ << endl;
        l();
    }

private:
    int no_;
};

int main() {
    auto f = std::make_unique<foo>(10);

    f->lambda_func([f = std::move(f)] () mutable {
        cout << "lambda ==> " << endl;
        cout << "lambda <== " << endl;
    });

    return 0;
}

This code segment faults

$ g++ -std=c++14  uniqueptr.cpp
$ ./a.out
Segmentation fault (core dumped)

If I remove the std::cout statement from lambda_func The code runs to completion.

It seems like, this statement f->lambda_func([f = std::move(f)] () mutable { processes lambda captures before member function is invoked.


问:
How to nested parsing expression .NET C#
How to nested parsing expression ,I'm developing an ORM, who can help me with some ideas?</p>

```<code>var list = db.Queryable<Student>()
    .Where(it => it.Id.Equals(db.Queryable<School>()
    .Where(sc => sc.Id == it.Id&&sc.Name=="jack"))).ToList()
</code>```

答:
It's batter to use LINQ joins for this purpose.

Example:

1| LINQ query-syntax

```<code>var list = (from s in db.Student
          join sc in db.School on s.SchoolId equals sc.Id
          where sc.Name=="jack"
         select s).ToList() ;
</code>```

2| LINQ Extension method

```<code>var list = db.Student.Join(db.School,
                 s => s.SchoolId,
                 sc => sc.Id,
                 (s, sc) => new { s, sc })
           .Where(ss => ss.sc.Name=="jack")
           .Select(ss => ss.s).ToList();
</code>```

You can get more information about query-syntax and Extension method in this answer.

Body:
How to nested parsing expression ,I'm developing an ORM, who can help me with some ideas?

var list = db.Queryable<Student>()
    .Where(it => it.Id.Equals(db.Queryable<School>()
    .Where(sc => sc.Id == it.Id&&sc.Name=="jack"))).ToList()

Body:
It's batter to use LINQ joins for this purpose.

Example:

1| LINQ query-syntax

var list = (from s in db.Student
          join sc in db.School on s.SchoolId equals sc.Id
          where sc.Name=="jack"
         select s).ToList() ;

2| LINQ Extension method

var list = db.Student.Join(db.School,
                 s => s.SchoolId,
                 sc => sc.Id,
                 (s, sc) => new { s, sc })
           .Where(ss => ss.sc.Name=="jack")
           .Select(ss => ss.s).ToList();

You can get more information about query-syntax and Extension method in this answer.


问:
Sending "secret" data to individual players in Lance Game
I'm wondering if there is an easy way in lance-gg to send player specific data to each player only, rather than emitting all data to all players.

I wish to have create a poker game, and don't want the data around what each player is holding broadcast to all players and instead only have each player receive information regarding their own cards.

Is this easily achievable between the current GameEngine and ServerEngine?

Over the course of the game the following steps will need to occur:

"deal" cards to each player (emit cards to each player individually, and also broadcast an event to indicate the other clients should animate the player being dealt cards receiving them)

store and hold the dealt cards outside the other data to be updated

retrieve player cards should the player be disconnected and then reconnect during the hand

"reveal" cards (broadcast any revealed cards like the flop and the showdown cards to all players)

Player's cards also need to be stored on the server but not re-broadcast with each step.

答:
There is a low-level networking layer which can be used for client-server communication in Lance.

For example, if the server wants to send the event shakeItUp with data shakeData = { ... } to all clients, the game's serverEngine would call:

```<code>this.io.sockets.emit('shakeItUp', shakeData);
</code>```

To send events and data to specific players, the serverEngine class can do

```<code>for (let socketId of Object.keys(this.connectedPlayers)) {
    let player = this.connectedPlayers[socketId];
    let playerId = player.socket.playerId;

    let message = `hello player ${playerId}`;
    this.connectedPlayers[socketId].socket.emit('secret', message);
}
</code>```

The client listens to messages from the ClientEngine sub-class, after the connection is established:

```<code>// extend ClientEngine connect to add own events
connect() {
    return super.connect().then(() => {
        this.socket.on('secret', (e) => {
            console.log(`my secret: ${e}`);
        });
    });
}
</code>```

Body:
There is a low-level networking layer which can be used for client-server communication in Lance.

For example, if the server wants to send the event shakeItUp with data shakeData = { ... } to all clients, the game's serverEngine would call:

this.io.sockets.emit('shakeItUp', shakeData);

To send events and data to specific players, the serverEngine class can do

for (let socketId of Object.keys(this.connectedPlayers)) {
    let player = this.connectedPlayers[socketId];
    let playerId = player.socket.playerId;

    let message = `hello player ${playerId}`;
    this.connectedPlayers[socketId].socket.emit('secret', message);
}

The client listens to messages from the ClientEngine sub-class, after the connection is established:

// extend ClientEngine connect to add own events
connect() {
    return super.connect().then(() => {
        this.socket.on('secret', (e) => {
            console.log(`my secret: ${e}`);
        });
    });
}

ContentLicense: CC BY-SA 4.0


问:
Placing elements center in bootstrap?
I'm new to css and bootstrap and I'm trying to place an div content on center of my screen.

Currently I'm planning to do so:

```<code> <div className="container">
    <div className="row">
        <div className="col-sm-4 col-md-4"></div>
        <div className="col-sm-4 col-md-4">
            Center content here
        </div>
        <div className="col-sm-4 col-md-4"></div>
    </div>
</div>
</code>```

I could able to guess that column's are splitted into 12. So I'm just splitting up them by 4 for 3 div's.

I just want to understand whether we can get rid of two div's which just used for calculation purpose here:

```<code><div className="col-sm-4 col-md-4"></div>
<div className="col-sm-4 col-md-4"></div>
</code>```

Is there any better way?

答:
You can use native bootstrap classes that are available, for example:</p>

```<code>class="text-center"

class="pagination-centered"
</code>```

Title: Placing elements center in bootstrap?

Body:
I'm new to css and bootstrap and I'm trying to place an div content on center of my screen.

Currently I'm planning to do so:

            Center content here

I could able to guess that column's are splitted into 12. So I'm just splitting up them by 4 for 3 div's.

I just want to understand whether we can get rid of two div's which just used for calculation purpose here:

Is there any better way?

Body:
You can use native bootstrap classes that are available, for example:

class="text-center"

class="pagination-centered"


问:
Laravel Query Builder: How do I sort results by date - first with ascending order by future dates and then by descending order by past dates?
I have a model tasks with complete tasks with datetime in the past and upcoming tasks with datetime in the future.

While retrieving the tasks, I want to display the upcoming tasks arranged in ascending order (from now to the future) and tasks in the past in descending order (from now to the past).

```<code>public function getTasks()
{
        $futureTasks = Task::whereDate('datetime', '>', Carbon::now())->orderBy('datetime', 'asc')->get();
        $pastTasks   = Task::whereDate('datetime', '<', Carbon::now())->orderBy('datetime', 'desc')->get();
        $tasks       = array_merge($futureTasks, $pastTasks);
        $response    = ['tasks' => $tasks];
        // return...
}
</code>```

I'm getting the following error:

array_merge(): Argument #1 is not an array

If I reverse the order of arguments for array_push function, I still get the same error.

```<code> public function getTasks()
{
        $futureTasks = Task::whereDate('datetime', '>', Carbon::now())->orderBy('datetime', 'asc')->get();
        $pastTasks   = Task::whereDate('datetime', '<', Carbon::now())->orderBy('datetime', 'desc')->get();
        $tasks       = array_merge($pastTasks, $futureTasks);
        $response    = ['tasks' => $tasks];
        // return...
}
</code>```

And If I retrieve only the futureTasks or pastTasks without array_merge, I get the desired output.

```<code>public function getTasks()
{
        $futureTasks = Task::whereDate('datetime', '>', Carbon::now())->orderBy('datetime', 'asc')->get();

        $response    = ['tasks' => $futureTasks];
        // return...
}
</code>```

What am I doing wrong here? Thanks a lot for your time.

答:
Both the results are a collection. You can use the collection merge method.

```<code>public function getTasks()
{
    $futureTasks = Task::whereDate('datetime', '>', Carbon::now())
        ->orderBy('datetime', 'asc')
        ->get();

    $pastTasks = Task::whereDate('datetime', '<', Carbon::now())
        ->orderBy('datetime', 'desc')
        ->get();

    $tasks = $futureTasks->merge($pastTasks);
    $response = compact('tasks');
    // return...
}
</code>```

Since you're using the whereDate condition, you're missing all the data from the present date based on your queries. You might want to check that.

Body:
I have a model tasks with complete tasks with datetime in the past and upcoming tasks with datetime in the future.

While retrieving the tasks, I want to display the upcoming tasks arranged in ascending order (from now to the future) and tasks in the past in descending order (from now to the past).

public function getTasks()
{
        $futureTasks = Task::whereDate('datetime', '>', Carbon::now())->orderBy('datetime', 'asc')->get();
        $pastTasks   = Task::whereDate('datetime', '<', Carbon::now())->orderBy('datetime', 'desc')->get();
        $tasks       = array_merge($futureTasks, $pastTasks);
        $response    = ['tasks' => $tasks];
        // return...
}

I'm getting the following error:

array_merge(): Argument #1 is not an array

If I reverse the order of arguments for array_push function, I still get the same error.

 public function getTasks()
{
        $futureTasks = Task::whereDate('datetime', '>', Carbon::now())->orderBy('datetime', 'asc')->get();
        $pastTasks   = Task::whereDate('datetime', '<', Carbon::now())->orderBy('datetime', 'desc')->get();
        $tasks       = array_merge($pastTasks, $futureTasks);
        $response    = ['tasks' => $tasks];
        // return...
}

And If I retrieve only the futureTasks or pastTasks without array_merge, I get the desired output.

public function getTasks()
{
        $futureTasks = Task::whereDate('datetime', '>', Carbon::now())->orderBy('datetime', 'asc')->get();

        $response    = ['tasks' => $futureTasks];
        // return...
}

What am I doing wrong here? Thanks a lot for your time.

Body:
Both the results are a collection. You can use the collection merge method.

public function getTasks()
{
    $futureTasks = Task::whereDate('datetime', '>', Carbon::now())
        ->orderBy('datetime', 'asc')
        ->get();

    $pastTasks = Task::whereDate('datetime', '<', Carbon::now())
        ->orderBy('datetime', 'desc')
        ->get();

    $tasks = $futureTasks->merge($pastTasks);
    $response = compact('tasks');
    // return...
}

Since you're using the whereDate condition, you're missing all the data from the present date based on your queries. You might want to check that.


问:
why is the submit button leading to other tab?
I am trying to display a dummy message on top of "To:" read only inout box after clicking a Send Mail button in mail tab as shown below.
But what's happening is instead of displaying message, it opens "FAQ" tab. Can you suggest me on how can I display a message on top of input box without going to FAQ tab. Thank you.

Here is the codepen

```<code> $("#frmDemo").submit(function(e) {
  e.preventDefault();
  var name = $("#name").val();
  var comment = $("#comment").val();
  if(name == "" || comment == "" ) {
  $("#error_message").show().html("All Fields are Required");
  } else {
 $("#error_message").html("").hide();
$.ajax({
  type: "POST",
  url: "post-form.php",
  data: "name="+name+"&comment="+comment,
  success: function(data){
    $('#success_message').fadeIn().html(data);
    setTimeout(function() {
      $('#success_message').fadeOut("slow");
    }, 2000 );

  }
});
}
});
</code>```

答:
try something like this :</p>

```<code>$("form#frmDemo").submit(function(e) {

  let t = $(this);
  let name = t.find("#name").val();
  let comment = t.find("#comment").val();
  let errorMsg = t.find("#error_message");
  let successMsg = t.find("#success_message");

  if(name == "" || comment == "" ) {

    errorMsg.html("All Fields are Required").show();

  } else {

    errorMsg.html("").hide();

    $.ajax({
      type: "POST",
      url: "post-form.php",
      data: "name="+name+"&comment="+comment,
      success: function(data){
        successMsg.fadeIn().html(data);
        setTimeout(function() {
          successMsg.fadeOut("slow");
        }, 2000 );

      }
    });

  }

  e.preventDefault();
});
</code>```

Body:
I am trying to display a dummy message on top of "To:" read only inout box after clicking a Send Mail button in mail tab as shown below.
But what's happening is instead of displaying message, it opens "FAQ" tab. Can you suggest me on how can I display a message on top of input box without going to FAQ tab. Thank you.

Here is the codepen

 $("#frmDemo").submit(function(e) {
  e.preventDefault();
  var name = $("#name").val();
  var comment = $("#comment").val();
  if(name == "" || comment == "" ) {
  $("#error_message").show().html("All Fields are Required");
  } else {
 $("#error_message").html("").hide();
$.ajax({
  type: "POST",
  url: "post-form.php",
  data: "name="+name+"&comment="+comment,
  success: function(data){
    $('#success_message').fadeIn().html(data);
    setTimeout(function() {
      $('#success_message').fadeOut("slow");
    }, 2000 );

  }
});
}
});

Body:
try something like this :

$("form#frmDemo").submit(function(e) {

  let t = $(this);
  let name = t.find("#name").val();
  let comment = t.find("#comment").val();
  let errorMsg = t.find("#error_message");
  let successMsg = t.find("#success_message");

  if(name == "" || comment == "" ) {

    errorMsg.html("All Fields are Required").show();

  } else {

    errorMsg.html("").hide();

    $.ajax({
      type: "POST",
      url: "post-form.php",
      data: "name="+name+"&comment="+comment,
      success: function(data){
        successMsg.fadeIn().html(data);
        setTimeout(function() {
          successMsg.fadeOut("slow");
        }, 2000 );

      }
    });

  }

  e.preventDefault();
});


问:
nginx / php / php-fpm | Problem with storing cookies
Greetings.

I am right now in the middle of reinstalling my whole dedicated server. I went with

-Ubuntu Server 10.10

-PHP 5.3.3.1

-php-fpm

-nginx

Now, almost everything seems to work, though there remains one problem with the sessions. No matter what I do, the sessions doesn't seem to store themselves properly (and they did on the previous setup).

The base application is phpBB board. When I login, it's okay - though it appends additional SID parameter to all of the URLs.

forum/index.php?sid=f506ccd42065322f61cb56fc6df6557a

You can navigate around the forums without problem, though if you delete the SID parameter, you get logged out. I thought, that perhaps the sessions aren't stored in cookies, but in URLs, but php configuration seems fine.

The same occurs with phpMyAdmin - I also get logged out, when I delete the token parameter.

In the meantime, it seems the cookies are getting created anyway, it's like they aren't used, or are getting deleted immediately.

I am getting more and more frustrated with that, maybe someone has an idea on how to troubleshoot that? I will post any configuration files necessary.

I thought maybe it's the problem with suhosin (it wasn't installed on the previous setup), but I have no clue. The PHP config is out-of-the box atm, I only modified nginx config.

答:
Also, be mindful of the user and group of the processes, as this will effect the default permissions that the session files are created with. If set to default, it may create as root, and then not be able to be read the next time the session file is accessed.

Look for Unix user/group of processes in your php-fpm.conf
and set both user and group to php-fpm


问:
Reduce PythonRDD of lists into one list
Going to keep this short post, but happy to add more context / details if they are necessary. I have a PythonRDD that looks as follows:

```<code>print(myRDD)
PythonRDD[4] at RDD at PythonRDD.scala:43

print(myRDD.take(1))
[[0.305, 0.302, -0.005, 0.302]]

print(myRDD.collect())
[[0.305, 0.302, -0.005, 0.302],
 [0.294, 0.183, 0.084, 0.277],
 [0.184, 0.997, -1.123, 0.654]]
</code>```

Each of the 3 lists contains the 4 values for a 2x2 matrix. I would like to add these 3 matrices together, hence I would like to use some reduce function on myRDD such that the output is:

[[.783, 1.482, -1.044, 1.233]]
```

<p>Where .783 = .305 + .294 + .184, etc. I tried to do:</p>

```myRDD.reduce(lambda a, b: a + b)
```

However this did not give me what I desired. Any help appreciated! Thanks!

答:
In this case, the iteration inside the reduce() function, with lambda function a,b goes through the lines of your RDD, so:

First iteration:

a is the first line in your RDD

b is the second line in your RDD

Second iteration:

a is the result of the operation applied using the lambda function at the previous step

b is the third line of your RDD

And so on until the last line.

Therefore, since line is a list, if you want to sum the first element of your line with the first element of the following line, you have to do a[0] + b[0] , for the sum of the second elements a[1] + b[1] and so on.

Solution:

```<code>>>> finalList = myRDD.reduce(lambda a, b: [a[0]+b[0], a[1]+b[1], a[2]+b[2], a[3]+b[3]])
[0.7829999999999999, 1.482, -1.044, 1.233]
</code>```

Then, if you need to round the elements of your list, you can use the command round() in a list comprehension.

```<code>>>> myFormattedList = [round(elem,3) for elem in finalList]
>>> myFormattedList
[0.783, 1.482, -1.044, 1.233]
</code>```

Title: Reduce PythonRDD of lists into one list

Body:
Going to keep this short post, but happy to add more context / details if they are necessary. I have a PythonRDD that looks as follows:

print(myRDD)
PythonRDD[4] at RDD at PythonRDD.scala:43

print(myRDD.take(1))
[[0.305, 0.302, -0.005, 0.302]]

print(myRDD.collect())
[[0.305, 0.302, -0.005, 0.302],
 [0.294, 0.183, 0.084, 0.277],
 [0.184, 0.997, -1.123, 0.654]]

Each of the 3 lists contains the 4 values for a 2x2 matrix. I would like to add these 3 matrices together, hence I would like to use some reduce function on myRDD such that the output is:

[[.783, 1.482, -1.044, 1.233]]

Where .783 = .305 + .294 + .184, etc. I tried to do:

myRDD.reduce(lambda a, b: a + b)

However this did not give me what I desired. Any help appreciated! Thanks!

Body:
In this case, the iteration inside the reduce() function, with lambda function a,b goes through the lines of your RDD, so:

First iteration:

a is the first line in your RDD

b is the second line in your RDD

Second iteration:

a is the result of the operation applied using the lambda function at the previous step

b is the third line of your RDD

And so on until the last line.

Therefore, since line is a list, if you want to sum the first element of your line with the first element of the following line, you have to do a[0] + b[0] , for the sum of the second elements a[1] + b[1] and so on.

Solution:

>>> finalList = myRDD.reduce(lambda a, b: [a[0]+b[0], a[1]+b[1], a[2]+b[2], a[3]+b[3]])
[0.7829999999999999, 1.482, -1.044, 1.233]

Then, if you need to round the elements of your list, you can use the command round() in a list comprehension.

>>> myFormattedList = [round(elem,3) for elem in finalList]
>>> myFormattedList
[0.783, 1.482, -1.044, 1.233]


问:
Label Not In List and KeyError
I'm trying to get the value of a specific cell.

```<code>  main_id   name  code
  0    1345  Jones    32
  1    1543   Jack    62
  2    9874   Buck    86
  3    2456   Slim    94
</code>```

I want the cell that says code=94, as I already know the main_id but nothing else.

```<code>raw_data = {'main_id': ['1345', '1543', '9874', '2456'],
        'name': ['Jones', 'Jack', 'Buck', 'Slim'],
        'code': [32, 62, 86, 94]}

    df=pd.DataFrame(raw_data, columns = ['main_id', 'name', 'code'])

    v=df.loc[str(df['main_id']) == str(2456)]['code'].values
    print(df.loc['name'])
</code>```

The print(df.loc['name']) claims the label is not in index

And the v=df.loc[str(df['main_id']) == str(2456)]['code'].values says 'KeyError False'

答:
df.loc['name'] raises a KeyError because name is not in the index; it is in the columns. When you use loc, the first argument is for index. You can use df['name'] or df.loc[:, 'name'].

You can also pass boolean arrays to loc (both for index and columns). For example,

```<code>df.loc[df['main_id']=='2456']
Out:
   main_id  name    code
3  2456     Slim    94
</code>```

You can still select a particular column for this, too:

```<code>df.loc[df['main_id']=='2456', 'code']
Out:
3    94
Name: code, dtype: int64
</code>```

With boolean indexes, the returning object will always be a Series even if you have only one value. So you might want to access the underlying array and select the first value from there:

```<code>df.loc[df['main_id']=='2456', 'code'].values[0]
Out:
94
</code>```

But better way is to use the item method:

```<code>df.loc[df['main_id']=='2456', 'code'].item()
Out:
94
</code>```

This way, you'll get an error if the length of the returning Series is greater than 1 while values[0] does not check that.

Title: Label Not In List and KeyError

Body:
I'm trying to get the value of a specific cell.

  main_id   name  code
  0    1345  Jones    32
  1    1543   Jack    62
  2    9874   Buck    86
  3    2456   Slim    94

I want the cell that says code=94, as I already know the main_id but nothing else.

raw_data = {'main_id': ['1345', '1543', '9874', '2456'],
        'name': ['Jones', 'Jack', 'Buck', 'Slim'],
        'code': [32, 62, 86, 94]}

    df=pd.DataFrame(raw_data, columns = ['main_id', 'name', 'code'])

    v=df.loc[str(df['main_id']) == str(2456)]['code'].values
    print(df.loc['name'])

The print(df.loc['name']) claims the label is not in index

And the v=df.loc[str(df['main_id']) == str(2456)]['code'].values says 'KeyError False'

Body:
df.loc['name'] raises a KeyError because name is not in the index; it is in the columns. When you use loc, the first argument is for index. You can use df['name'] or df.loc[:, 'name'].

You can also pass boolean arrays to loc (both for index and columns). For example,

df.loc[df['main_id']=='2456']
Out:
   main_id  name    code
3  2456     Slim    94

You can still select a particular column for this, too:

df.loc[df['main_id']=='2456', 'code']
Out:
3    94
Name: code, dtype: int64

With boolean indexes, the returning object will always be a Series even if you have only one value. So you might want to access the underlying array and select the first value from there:

df.loc[df['main_id']=='2456', 'code'].values[0]
Out:
94

But better way is to use the item method:

df.loc[df['main_id']=='2456', 'code'].item()
Out:
94

This way, you'll get an error if the length of the returning Series is greater than 1 while values[0] does not check that.


问:
Code stuck in loop
I made a script that takes a picture, starts from the top left corner (a white pixel in the case of my test image), and proceeds to go through the image like a magic wand tool, selecting the pixels that are of a similar enough color.

But the script doesn't finish executing even after going through the loop more times than there are pixels in the image.

The test image is roughly 160K pixels. Tools.loadImage() is a self-written method. I've used it elsewhere, it most probably works. The following is not the entirety of my code, but the part that seemed relevant to the problem.

```<code>static int[][][] image;

public static void main(String[] args) {
    image = Tools.loadImage(path1);

    int height = image.length;
    int width = image[0].length;
    int[][][] newImage = new int[height][width][4];

    ArrayList<Integer> toCheck = new ArrayList<Integer>();
    ArrayList<Integer> checked = new ArrayList<Integer>();

    int[] baseColor = image[0][0];
    toCheck.add(0);

    while (!toCheck.isEmpty()) {
        i++;
        int coords = toCheck.get(0);
        int x = coords % width;
        int y = coords / width;

        if (check(x, y, baseColor, 128)) {
            coords = y * width + x - 1;
            if (x > 0 && !(checked.contains(coords) || toCheck.contains(coords))) {
                toCheck.add(coords);
            }
            coords = y * width + x + 1;
            if (x < width - 1 && !(checked.contains(coords) || toCheck.contains(coords))) {
                toCheck.add(coords);
            }
            coords = (y - 1) * width + x;
            if (y > 0 && !(checked.contains(coords) || toCheck.contains(coords))) {
                toCheck.add(coords);
            }
            coords = (y + 1) * width + x;
            if (y < height - 1 && !(checked.contains(coords) || toCheck.contains(coords))) {
                toCheck.add(coords);
            }
        }

        checked.add(coords);
        toCheck.remove(0);
    }
}

static boolean check(int x, int y, int[] color, int threshold) {
    for (int i = 0; i < 3; i++) {
        if (Math.abs(image[y][x][i] - color[i]) > threshold) {
            return false;
        }
    }
    return true;
}
</code>```

PS. If you feel like pointing out obvious ways to make this loop faster, that would be appreciated as well.

答:
The add to checked is in the wrong place.

```<code>while (!toCheck.isEmpty()) {
    i++;
    int coords = toCheck.get(0);
    checked.add(coords);        // important
    toCheck.remove(0);          // might as well do this here too
    int x = coords % width;
    int y = coords / width;
</code>```

coords is overwritted repeatedly in the loop, and thus the current pixel is not added but the last of the four neighbours. Thus some condition fails later and some wrong pixel is added toCheck.

Title: Code stuck in loop

Body:
I made a script that takes a picture, starts from the top left corner (a white pixel in the case of my test image), and proceeds to go through the image like a magic wand tool, selecting the pixels that are of a similar enough color.

But the script doesn't finish executing even after going through the loop more times than there are pixels in the image.

The test image is roughly 160K pixels. Tools.loadImage() is a self-written method. I've used it elsewhere, it most probably works. The following is not the entirety of my code, but the part that seemed relevant to the problem.

static int[][][] image;

public static void main(String[] args) {
    image = Tools.loadImage(path1);

    int height = image.length;
    int width = image[0].length;
    int[][][] newImage = new int[height][width][4];

    ArrayList<Integer> toCheck = new ArrayList<Integer>();
    ArrayList<Integer> checked = new ArrayList<Integer>();

    int[] baseColor = image[0][0];
    toCheck.add(0);

    while (!toCheck.isEmpty()) {
        i++;
        int coords = toCheck.get(0);
        int x = coords % width;
        int y = coords / width;

        if (check(x, y, baseColor, 128)) {
            coords = y * width + x - 1;
            if (x > 0 && !(checked.contains(coords) || toCheck.contains(coords))) {
                toCheck.add(coords);
            }
            coords = y * width + x + 1;
            if (x < width - 1 && !(checked.contains(coords) || toCheck.contains(coords))) {
                toCheck.add(coords);
            }
            coords = (y - 1) * width + x;
            if (y > 0 && !(checked.contains(coords) || toCheck.contains(coords))) {
                toCheck.add(coords);
            }
            coords = (y + 1) * width + x;
            if (y < height - 1 && !(checked.contains(coords) || toCheck.contains(coords))) {
                toCheck.add(coords);
            }
        }

        checked.add(coords);
        toCheck.remove(0);
    }
}

static boolean check(int x, int y, int[] color, int threshold) {
    for (int i = 0; i < 3; i++) {
        if (Math.abs(image[y][x][i] - color[i]) > threshold) {
            return false;
        }
    }
    return true;
}

PS. If you feel like pointing out obvious ways to make this loop faster, that would be appreciated as well.

Body:
The add to checked is in the wrong place.

while (!toCheck.isEmpty()) {
    i++;
    int coords = toCheck.get(0);
    checked.add(coords);        // important
    toCheck.remove(0);          // might as well do this here too
    int x = coords % width;
    int y = coords / width;

coords is overwritted repeatedly in the loop, and thus the current pixel is not added but the last of the four neighbours. Thus some condition fails later and some wrong pixel is added toCheck.


问:
Rebuild query which looking for specific string
I have products numbers which looks like below:

One example product (contain couple articles)

```<code>14.12312.1
14.12312.2
14.12312.3
14.12312.4
14.12312.5
</code>```

Other example product (contain couple articles)

```<code>003.23.1
003.23.66
003.23.44
003.23.77
003.23.5
</code>```

Important thing here is dots are separators:

```<code><producentNumber>.<specialnumber>.<articlevariation>
</code>```

Now i got query which could take first part of specific product for instance i can pass: 003.23. (with last dot) and then it gives me all starts with it so:

```<code>003.23.1
003.23.66
003.23.44
003.23.77
003.23.5
</code>```

This is the query which is doing that:

```<code>SELECT ID, Nummer FROM [Cenea].[dbo].[T_Artikel]
                  WHERE
                  SUBSTRING(Nummer, 0, LEN(Nummer) + 2 -  CHARINDEX('.', REVERSE(Nummer)))  IN
                  (
                                                                                '003.23.'
                  )
</code>```

However now is the change that within last part of the articles number could appears dots and not only the numbers so it means i can have like this:

```<code> 003.23.1
 003.23.66..dwqd
 003.23.4422.323.3
 003.23.77....f
 003.23.5
</code>```

So when i pass 003.23. i will get not all but just 003.23.1 in this case. The logic stays as it was first two dots are holding the base but after the second there could be anything. Question is how to rebuild my sql query to adapt the change to get alkl articles?

Hope everything is clear and please provide working code as i have to make change on production today.

答:
You can use LIKE to get all rows where Number starts with <some value>:

```<code>SELECT ID, Nummer FROM [Cenea].[dbo].[T_Artikel]
WHERE Number LIKE '003.23%'
</code>```

Body:
I have products numbers which looks like below:

One example product (contain couple articles)

14.12312.1
14.12312.2
14.12312.3
14.12312.4
14.12312.5

Other example product (contain couple articles)

003.23.1
003.23.66
003.23.44
003.23.77
003.23.5

Important thing here is dots are separators:

<producentNumber>.<specialnumber>.<articlevariation>

Now i got query which could take first part of specific product for instance i can pass: 003.23. (with last dot) and then it gives me all starts with it so:

003.23.1
003.23.66
003.23.44
003.23.77
003.23.5

This is the query which is doing that:

SELECT ID, Nummer FROM [Cenea].[dbo].[T_Artikel]
                  WHERE
                  SUBSTRING(Nummer, 0, LEN(Nummer) + 2 -  CHARINDEX('.', REVERSE(Nummer)))  IN
                  (
                                                                                '003.23.'
                  )

However now is the change that within last part of the articles number could appears dots and not only the numbers so it means i can have like this:

 003.23.1
 003.23.66..dwqd
 003.23.4422.323.3
 003.23.77....f
 003.23.5

So when i pass 003.23. i will get not all but just 003.23.1 in this case. The logic stays as it was first two dots are holding the base but after the second there could be anything. Question is how to rebuild my sql query to adapt the change to get alkl articles?

Hope everything is clear and please provide working code as i have to make change on production today.

Body:
You can use LIKE to get all rows where Number starts with <some value>:

SELECT ID, Nummer FROM [Cenea].[dbo].[T_Artikel]
WHERE Number LIKE '003.23%'


问:
SubType reference in Oracle
Please help, the question is at the bottom.

```<code>CREATE OR REPLACE TYPE NameType AS OBJECT
(firstName VARCHAR(20), middleName VARCHAR(20), lastName VARCHAR(20))
INSTANTIABLE
FINAL;

CREATE OR REPLACE TYPE ServicerType AS OBJECT
(servicerID INTEGER, servicerType VARCHAR(10))
INSTANTIABLE
FINAL;

CREATE OR REPLACE TYPE PersonType AS OBJECT
(personID INTEGER, name NameType, gender CHAR(1))
INSTANTIABLE
NOT FINAL;

CREATE OR REPLACE TYPE EmployeeType UNDER PersonType
(servicerRef REF ServicerType)
NOT INSTANTIABLE
NOT FINAL;

CREATE OR REPLACE TYPE FullTimeEmployeeType UNDER EmployeeType
(yearlySalary NUMBER(19,4))
INSTANTIABLE
FINAL;

CREATE TABLE Servicer OF ServicerType;
CREATE TABLE Person OF PersonType;

INSERT ALL
INTO Servicer values (ServicerType(100, 'Company')
SELECT * FROM dual

INSERT ALL
INTO Person VALUES (FullTimeEmployeeType(200,
    NameType('Bob', 'T', 'Builder'), 'M',
    (select ref(s) from servicer s where servicerid = 100), 56700))
SELECT * FROM dual
</code>```

Now I want to run this query:

```<code>select p.gender, p.name.firstName, p.name.lastName, p.yearlySalary from person p
</code>```

I got an error. I know that yearlySalary is in FullTimeEmployee which is a subtype of person, but I just don't know how to reference it.

答:
You need the TREAT function</p>

```<code>select p.gender, p.name.firstName, p.name.lastName,
        treat(value(p) as FullTimeEmployeeType).yearlySalary
from person p
/
</code>```

Title: SubType reference in Oracle

Body:
Please help, the question is at the bottom.

CREATE OR REPLACE TYPE NameType AS OBJECT
(firstName VARCHAR(20), middleName VARCHAR(20), lastName VARCHAR(20))
INSTANTIABLE
FINAL;

CREATE OR REPLACE TYPE ServicerType AS OBJECT
(servicerID INTEGER, servicerType VARCHAR(10))
INSTANTIABLE
FINAL;

CREATE OR REPLACE TYPE PersonType AS OBJECT
(personID INTEGER, name NameType, gender CHAR(1))
INSTANTIABLE
NOT FINAL;

CREATE OR REPLACE TYPE EmployeeType UNDER PersonType
(servicerRef REF ServicerType)
NOT INSTANTIABLE
NOT FINAL;

CREATE OR REPLACE TYPE FullTimeEmployeeType UNDER EmployeeType
(yearlySalary NUMBER(19,4))
INSTANTIABLE
FINAL;

CREATE TABLE Servicer OF ServicerType;
CREATE TABLE Person OF PersonType;

INSERT ALL
INTO Servicer values (ServicerType(100, 'Company')
SELECT * FROM dual

INSERT ALL
INTO Person VALUES (FullTimeEmployeeType(200,
    NameType('Bob', 'T', 'Builder'), 'M',
    (select ref(s) from servicer s where servicerid = 100), 56700))
SELECT * FROM dual

Now I want to run this query:

select p.gender, p.name.firstName, p.name.lastName, p.yearlySalary from person p

I got an error. I know that yearlySalary is in FullTimeEmployee which is a subtype of person, but I just don't know how to reference it.

Body:
You need the TREAT function

select p.gender, p.name.firstName, p.name.lastName,
        treat(value(p) as FullTimeEmployeeType).yearlySalary
from person p
/


问:
Rails create join table index name is too long
So I'm trying to create a join table between the tables users and looking_for_options.

This is my migration file:

```<code>class CreateJoinTableOptionsUsers < ActiveRecord::Migration[5.0]
  def change
    create_join_table :looking_for_options, :users do |t|
      t.index [:looking_for_option_id, :user_id]
      t.index [:user_id, :looking_for_option_id]
    end
  end
end
</code>```

But I'm getting this error:

Index name 'index_looking_for_options_users_on_looking_for_option_id_and_user_id' on table 'looking_for_options_users' is too long; the lim
  it is 64 characters

Knowing that for a join table, rails convention is Table_A_Name_Table_B_Name  and its columns follow a similar convention Table_A_id and Table_B_id.

How do I specify a shorter column name for the joint table so it doesn't break rails many-to-many associations?

Update:

I found that I can give just the index a different name instead. But will rails's many-to-many association actually utilize it?

```<code>class CreateJoinTableOptionsUsers < ActiveRecord::Migration[5.0]
  def change
    create_join_table :looking_for_options, :users do |t|
      t.index [:looking_for_option_id, :user_id], name: 'option_user'
      t.index [:user_id, :looking_for_option_id], name: 'user_option'
    end
  end
end
</code>```

答:
... will rails's many-to-many association actually utilize it?

The choice of whether to use the index or not is made by the database optimiser, and is not affected by Rails. You can name it what you like, within the constraints imposed by the database.

Body:
So I'm trying to create a join table between the tables users and looking_for_options.

This is my migration file:

class CreateJoinTableOptionsUsers < ActiveRecord::Migration[5.0]
  def change
    create_join_table :looking_for_options, :users do |t|
      t.index [:looking_for_option_id, :user_id]
      t.index [:user_id, :looking_for_option_id]
    end
  end
end

But I'm getting this error:

Index name 'index_looking_for_options_users_on_looking_for_option_id_and_user_id' on table 'looking_for_options_users' is too long; the lim
  it is 64 characters

Knowing that for a join table, rails convention is Table_A_Name_Table_B_Name  and its columns follow a similar convention Table_A_id and Table_B_id.

How do I specify a shorter column name for the joint table so it doesn't break rails many-to-many associations?

Update:

I found that I can give just the index a different name instead. But will rails's many-to-many association actually utilize it?

class CreateJoinTableOptionsUsers < ActiveRecord::Migration[5.0]
  def change
    create_join_table :looking_for_options, :users do |t|
      t.index [:looking_for_option_id, :user_id], name: 'option_user'
      t.index [:user_id, :looking_for_option_id], name: 'user_option'
    end
  end
end


问:
VB.NET - Delete excess white spaces between words in a sentence
I'm a programing student, so I've started with vb.net as my first language and I need some help.

I need to know how I delete excess white spaces between words in a sentence, only using these string functions: Trim, instr, char, mid, val and len.

I made a part of the code but it doesn't work, Thanks.
enter image description here

答:
Unless using those VB6 methods is a requirement, here's a one-line solution:

```<code>TextBox2.Text = String.Join(" ", TextBox1.Text.Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries))
</code>```

Online test: http://ideone.com/gBbi55

String.Split() splits a string on a specific character or substring (in this case a space) and creates an array of the string parts in-between. I.e: "Hello There" -> {"Hello", "There"}

StringSplitOptions.RemoveEmptyEntries removes any empty strings from the resulting split array. Double spaces will create empty strings when split, thus you'll get rid of them using this option.

String.Join() will create a string from an array and separate each array entry with the specified string (in this case a single space).

Body:
Unless using those VB6 methods is a requirement, here's a one-line solution:

TextBox2.Text = String.Join(" ", TextBox1.Text.Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries))

Online test: http://ideone.com/gBbi55

String.Split() splits a string on a specific character or substring (in this case a space) and creates an array of the string parts in-between. I.e: "Hello There" -> {"Hello", "There"}

StringSplitOptions.RemoveEmptyEntries removes any empty strings from the resulting split array. Double spaces will create empty strings when split, thus you'll get rid of them using this option.

String.Join() will create a string from an array and separate each array entry with the specified string (in this case a single space).


问:
unable to change width of image with bootstrap
I'm working on Carousel image slider with bootstrap. I'm unable to change the height of the image. If I try to change the height it's effecting for both height and width both. But I need to modify only width.

My code is like below :

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/
    bootstrap.min.css">

Carousel Example

        Previous

        Next

```

答:
Percent height is tricky because it depends on parent height, which in this case there are none, resulting in that your image height means nothing.

You can set a fixed height on the parent (not using percent) Or you can set a percent-based height on the parent, but then IT'S parent needs a fixed height. And the same is true all the way up to the html-element, which you can set a 100% height on and the browser will respect it, but it's a really ugly way of doing things.

There are ways around this of course. It also seems like you don't mind if the image is stretched, so that is another assumption I'm making. With that said I think the easiest option here is to use vw/vh units. They work almost as percent, but vw/vh is based on viewport width or height and not parent height. Thus:

```<code><img src="la.jpg" alt="Los Angeles" style="width:30vw; height:10vw">
</code>```

Of course, if you don't know the exact ratios, the image will be stretched. (use height: auto for a non-stretched image).

Here is various browser support for the vh/vw units.

If you want the image to appear cropped, you are better off using css background-image and background-size instead of a img element. (Your intentions are not obvious from your question.)

Body:
Percent height is tricky because it depends on parent height, which in this case there are none, resulting in that your image height means nothing.

You can set a fixed height on the parent (not using percent) Or you can set a percent-based height on the parent, but then IT'S parent needs a fixed height. And the same is true all the way up to the html-element, which you can set a 100% height on and the browser will respect it, but it's a really ugly way of doing things.

There are ways around this of course. It also seems like you don't mind if the image is stretched, so that is another assumption I'm making. With that said I think the easiest option here is to use vw/vh units. They work almost as percent, but vw/vh is based on viewport width or height and not parent height. Thus:

<img src="la.jpg" alt="Los Angeles" style="width:30vw; height:10vw">

Of course, if you don't know the exact ratios, the image will be stretched. (use height: auto for a non-stretched image).

Here is various browser support for the vh/vw units.

If you want the image to appear cropped, you are better off using css background-image and background-size instead of a img element. (Your intentions are not obvious from your question.)


问:
Change image of specific clicked element
I would like to toggle the src of the specific image element clicked. But, only for that image. In other words, only toggle the one clicked. If clicked again then change back. How can I do this with jQuery or JavaScript. The code can be seen here: https://codepen.io/centem/pen/NgKEmG

```<code><!--
When image clicked change image to:
https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png
-->

<ul class="list-unstyled">

<li>Username<span class="pull-right">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png"></span><span class="pull-right">
<img src="http://pngimg.com/uploads/firefox/firefox_PNG16.png"></span><span class="pull-right">
<img src="https://ma.ttias.be/wp-content/uploads/2015/07/internet-explorer-logo.png"></span></li>

<li>Username<span class="pull-right">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png"></span><span class="pull-right">
<img src="http://pngimg.com/uploads/firefox/firefox_PNG16.png"></span><span class="pull-right">
<img src="https://ma.ttias.be/wp-content/uploads/2015/07/internet-explorer-logo.png"></span></li></li>

<li>Username<span class="pull-right">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png"></span><span class="pull-right">
<img src="http://pngimg.com/uploads/firefox/firefox_PNG16.png"></span><span class="pull-right">
<img src="https://ma.ttias.be/wp-content/uploads/2015/07/internet-explorer-logo.png"></span></li></li>

</ul>
</code>```

Here is my jquery:

```<code>    function handler( event ) {
  var target = $( event.target );
  if ( target.is( "img" ) ) {
    target.src().toggle(
"https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png");
  }
}
</code>```

Thank you.

答:
What you need to use is jquery's attr() function
Give your image a class name then you can change the src in jQuery by:

```<code>$(".image1").attr("src","https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png");
</code>```

And to attach it to a click event

```<code>$(".image1").click(function(){
    $('.image1').attr('src','https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png');
});
</code>```

Body:
I would like to toggle the src of the specific image element clicked. But, only for that image. In other words, only toggle the one clicked. If clicked again then change back. How can I do this with jQuery or JavaScript. The code can be seen here: https://codepen.io/centem/pen/NgKEmG

Username

Username

Username

Here is my jquery:

    function handler( event ) {
  var target = $( event.target );
  if ( target.is( "img" ) ) {
    target.src().toggle(
"https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png");
  }
}

Thank you.

Body:
What you need to use is jquery's attr() function
Give your image a class name then you can change the src in jQuery by:

$(".image1").attr("src","https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png");

And to attach it to a click event

$(".image1").click(function(){
    $('.image1').attr('src','https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png');
});


问:
Retrieve Local Tomcat Path for File Access
Is there a way to retrieve the Tomcat local GWT directory in order to save a file?

In order to retrieve a file it's

```<code>new File(getClass().getResource(nameOfAFile).getPath());
</code>```

Therefore how would I retrieve path of the tomcat host in order to save a file 'hello.xml'?

答: In tomcat, you can use ServletContext.getRealPath() to get the path for a file in your webapp then you can do navigate to "../" to find tomcat dir. </p>

Body:
Is there a way to retrieve the Tomcat local GWT directory in order to save a file?

In order to retrieve a file it's

new File(getClass().getResource(nameOfAFile).getPath());

Therefore how would I retrieve path of the tomcat host in order to save a file 'hello.xml'?


问:
Image Rows in Constraint Layout
Using constraints in a ConstraintLayout, I have created a layout as following:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardCornerRadius="2dp"
    app:cardElevation="4dp"
    app:cardUseCompatPadding="true">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="4dp"
        >

        <ImageView
            android:id="@+id/post_photo"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dp"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter"
            app:srcCompat="@drawable/ic_photo"
            />

        <ImageButton
            android:id="@+id/create_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dp"
            app:layout_constraintTop_toBottomOf="@+id/post_photo"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toLeftOf="@+id/share_button"
            app:srcCompat="@drawable/ic_action_share"
            android:scaleType="fitCenter"
            />

        <ImageButton
            android:id="@+id/share_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dp"
            app:layout_constraintTop_toBottomOf="@+id/post_photo"
            app:layout_constraintLeft_toRightOf="@+id/create_button"
            app:layout_constraintRight_toRightOf="parent"
            app:srcCompat="@drawable/ic_action_share"
            android:scaleType="fitCenter"
            />

    </android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
</code>```

My problem is that lower ImageButtons are not shown whenever height of image in ImageView is more than its width. If we hardcode a height (some kind of sufficient) on ConstraintLayout then buttons can get some height depending on the height of ImageView. I believe that the problem is when View Bounds are adjusted for ImageView. How can I overcome this situation?

答:
wrap_content only asks the widget to measure itself, but won't limit its expansion against eventual constraints

add following attribute to your ImageView which is used when parent constraint layout set to wrap_content then there will be height measuring problem so overcome that

```<code>app:layout_constraintHeight_default="wrap"
</code>```

and also set ImageView height to 0dp

```<code> <ImageView
            android:id="@+id/post_photo"
            android:layout_width="0dp"
            app:layout_constraintHeight_default="wrap"
            android:layout_height="0dp"
            android:layout_marginTop="4dp"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter"
            app:srcCompat="@drawable/ic_photo"
            />
</code>```

for information same approach we can use in width problem
just replace width to 0dp and following property

```<code>app:layout_constraintWidth_default="wrap"
</code>```

Title: Image Rows in Constraint Layout

Body:
Using constraints in a ConstraintLayout, I have created a layout as following:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardCornerRadius="2dp"
    app:cardElevation="4dp"
    app:cardUseCompatPadding="true">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="4dp"
        >

        <ImageView
            android:id="@+id/post_photo"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dp"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter"
            app:srcCompat="@drawable/ic_photo"
            />

        <ImageButton
            android:id="@+id/create_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dp"
            app:layout_constraintTop_toBottomOf="@+id/post_photo"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toLeftOf="@+id/share_button"
            app:srcCompat="@drawable/ic_action_share"
            android:scaleType="fitCenter"
            />

        <ImageButton
            android:id="@+id/share_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dp"
            app:layout_constraintTop_toBottomOf="@+id/post_photo"
            app:layout_constraintLeft_toRightOf="@+id/create_button"
            app:layout_constraintRight_toRightOf="parent"
            app:srcCompat="@drawable/ic_action_share"
            android:scaleType="fitCenter"
            />

    </android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>

My problem is that lower ImageButtons are not shown whenever height of image in ImageView is more than its width. If we hardcode a height (some kind of sufficient) on ConstraintLayout then buttons can get some height depending on the height of ImageView. I believe that the problem is when View Bounds are adjusted for ImageView. How can I overcome this situation?

Body:
wrap_content only asks the widget to measure itself, but won't limit its expansion against eventual constraints

add following attribute to your ImageView which is used when parent constraint layout set to wrap_content then there will be height measuring problem so overcome that

app:layout_constraintHeight_default="wrap"

and also set ImageView height to 0dp

 <ImageView
            android:id="@+id/post_photo"
            android:layout_width="0dp"
            app:layout_constraintHeight_default="wrap"
            android:layout_height="0dp"
            android:layout_marginTop="4dp"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter"
            app:srcCompat="@drawable/ic_photo"
            />

for information same approach we can use in width problem
just replace width to 0dp and following property

app:layout_constraintWidth_default="wrap"


问:
How can I test if an object inherits or is a member of a generic class?
Suppose I have a class class C<T>.

I want to write a function f(_ a: Any) -> Bool, which returns true when a is a member of class inheriting from C (or is a C itself). I don't care about the specialization: passing C<Int>, C<Double>, C<Whatever> should all return true.

It seems like I should be able to just write a is C or a as? C != nil as the body of that function, however, these both don't compile in a playground; swiftc complains that "generic parameter 'T' could not be inferred in cast to 'C<_>'". If I write f inside of C as an instance method, C is implicitly C<T>, and so writing let c = C<Int>(); c.f(C<Double>()) returns false.

I can work around this by writing a protocol P, which C conforms to, and then test for that but I don't consider that a good solution; it's just a hack.

Is there any way to do this?

Here's all the code I wrote to try this:

```<code>class C<T> {
  func test(_ a: Any) -> (Bool, Bool) {
    return (type(of: a) == C.self, a is C)
  }
}

class D: C<Double> { }

let d = D()

func f(_ a: Any) -> Bool {
  return a is C // generic parameter 'T' could not be inferred in cast to 'C<_>'
}

d.test(C<Int>()) // false, false

// bad solution

protocol P { }

extension C: P { }

d is P // true
</code>```

答:
See how dump is declared

```<code>func dump<T, TargetStream where TargetStream : TextOutputStream>(_ value: T, to target: inout TargetStream, name: String? = default, indent: Int = default, maxDepth: Int = default, maxItems: Int = default) -> T
</code>```

And check what it produces

```<code>class C<T>{}
class D:C<Double>{}

let c = C<Void>()
let d = D()

dump(c)
dump(d)
</code>```

Yes, dump is part of Swift's standard library ... which use reflection (objects mirror) to produce its result.

UPDATE

I created cli project named dumptest with one file main.swift

```<code>//
//  main.swift
//  dumptest
//

class C<T>{}
class D:C<Double>{}
class E:D{}

let c = C<Void>()
let d = D()
let e = E()

var tc = ""
var td = ""
var te = ""

dump(c, to: &tc)
dump(d, to: &td)
dump(e, to: &te)

print("type info about c:", tc)
print("type info about d:", td)
print("type info about e:", te)
</code>```

running it the program reported

```<code>type info about c: - dumptest.C<()> #0

type info about d: - dumptest.D #0
  - super: dumptest.C<Swift.Double>

type info about e: - dumptest.E #0
  - super: dumptest.D
    - super: dumptest.C<Swift.Double>

Program ended with exit code: 0
</code>```

For parsing String variables check stackoverflow, or ask a new question ...

lets have

```<code>import Cocoa

let v = NSView()
dump(v)
</code>```

dump value v and we have

```<code>- <NSView: 0x100a022a0> #0
  - super: NSResponder
    - super: NSObject
Program ended with exit code: 0
</code>```

If you need something "more complex", you can play with
Mirror

Body:
Suppose I have a class class C<T>.

I want to write a function f(_ a: Any) -> Bool, which returns true when a is a member of class inheriting from C (or is a C itself). I don't care about the specialization: passing C<Int>, C<Double>, C<Whatever> should all return true.

It seems like I should be able to just write a is C or a as? C != nil as the body of that function, however, these both don't compile in a playground; swiftc complains that "generic parameter 'T' could not be inferred in cast to 'C<_>'". If I write f inside of C as an instance method, C is implicitly C<T>, and so writing let c = C<Int>(); c.f(C<Double>()) returns false.

I can work around this by writing a protocol P, which C conforms to, and then test for that but I don't consider that a good solution; it's just a hack.

Is there any way to do this?

Here's all the code I wrote to try this:

class C<T> {
  func test(_ a: Any) -> (Bool, Bool) {
    return (type(of: a) == C.self, a is C)
  }
}

class D: C<Double> { }

let d = D()

func f(_ a: Any) -> Bool {
  return a is C // generic parameter 'T' could not be inferred in cast to 'C<_>'
}

d.test(C<Int>()) // false, false

// bad solution

protocol P { }

extension C: P { }

d is P // true

Body:
See how dump is declared

func dump<T, TargetStream where TargetStream : TextOutputStream>(_ value: T, to target: inout TargetStream, name: String? = default, indent: Int = default, maxDepth: Int = default, maxItems: Int = default) -> T

And check what it produces

class C<T>{}
class D:C<Double>{}

let c = C<Void>()
let d = D()

dump(c)
dump(d)

Yes, dump is part of Swift's standard library ... which use reflection (objects mirror) to produce its result.

UPDATE

I created cli project named dumptest with one file main.swift

//
//  main.swift
//  dumptest
//

class C<T>{}
class D:C<Double>{}
class E:D{}

let c = C<Void>()
let d = D()
let e = E()

var tc = ""
var td = ""
var te = ""

dump(c, to: &tc)
dump(d, to: &td)
dump(e, to: &te)

print("type info about c:", tc)
print("type info about d:", td)
print("type info about e:", te)

running it the program reported

type info about c: - dumptest.C<()> #0

type info about d: - dumptest.D #0
  - super: dumptest.C<Swift.Double>

type info about e: - dumptest.E #0
  - super: dumptest.D
    - super: dumptest.C<Swift.Double>

Program ended with exit code: 0

For parsing String variables check stackoverflow, or ask a new question ...

lets have

import Cocoa

let v = NSView()
dump(v)

dump value v and we have

- <NSView: 0x100a022a0> #0
  - super: NSResponder
    - super: NSObject
Program ended with exit code: 0

If you need something "more complex", you can play with
Mirror