问:
node.js returning only specific data from a http request
I'm attempting to use the Destiny 2 API in a discord chatbot I have been writing. Right now I just want it to return my player id by sending a request to the address designated in the API. I can successfully do this but it returns more information than I need. How do I just return the 'membershipId'?

The body of this request returns:

```<code>{
    "Response": [
        {
            "membershipType": 4,
            "membershipId": "4611686018470641209",
            "displayName": "LazyBrain#2918"
        }
    ],
    "ErrorCode": 1,
    "ThrottleSeconds": 0,
    "ErrorStatus": "Success",
    "Message": "Ok",
    "MessageData": {}
}
</code>```

Code:

```<code>    case 'stats':
    let options = {
        url: HOST + '/SearchDestinyPlayer/4/LazyBrain%232918/',
        headers: {
            'X-API-Key': config.key
        }
    };

    request(options, function (err, res, body) {
        let json = JSON.stringify(JSON.parse(body)['Response']);
        console.log(json);
    });
</code>```

But with the above code I have narrowed it down to:

```<code>[
    {
        "membershipType": 4,
        "membershipId": "4611686018470641209",
        "displayName": "LazyBrain#2918"
    }
]
</code>```

I'm not entirely sure if I'm going about this the right way though.

答:
You can get it like this:

```<code>var raw = JSON.parse(body);
var membershipID = raw.Response[0].membershipId;
</code>```

Without minding the other JSON Data/Keys

Example:

var body = '{"Response":[{"membershipType":4,"membershipId":"4611686018470641209","displayName":"LazyBrain#2918"}],"ErrorCode":1,"ThrottleSeconds":0,"ErrorStatus":"Success","Message":"Ok","MessageData":{}}';

var raw = JSON.parse(body);
var membershipID = raw.Response[0].membershipId;

console.log(membershipID);```

Body:
I'm attempting to use the Destiny 2 API in a discord chatbot I have been writing. Right now I just want it to return my player id by sending a request to the address designated in the API. I can successfully do this but it returns more information than I need. How do I just return the 'membershipId'?

The body of this request returns:

{
    "Response": [
        {
            "membershipType": 4,
            "membershipId": "4611686018470641209",
            "displayName": "LazyBrain#2918"
        }
    ],
    "ErrorCode": 1,
    "ThrottleSeconds": 0,
    "ErrorStatus": "Success",
    "Message": "Ok",
    "MessageData": {}
}

Code:

    case 'stats':
    let options = {
        url: HOST + '/SearchDestinyPlayer/4/LazyBrain%232918/',
        headers: {
            'X-API-Key': config.key
        }
    };

    request(options, function (err, res, body) {
        let json = JSON.stringify(JSON.parse(body)['Response']);
        console.log(json);
    });

But with the above code I have narrowed it down to:

[
    {
        "membershipType": 4,
        "membershipId": "4611686018470641209",
        "displayName": "LazyBrain#2918"
    }
]

I'm not entirely sure if I'm going about this the right way though.

Body:
You can get it like this:

var raw = JSON.parse(body);
var membershipID = raw.Response[0].membershipId;

Without minding the other JSON Data/Keys

Example:

var body = '{"Response":[{"membershipType":4,"membershipId":"4611686018470641209","displayName":"LazyBrain#2918"}],"ErrorCode":1,"ThrottleSeconds":0,"ErrorStatus":"Success","Message":"Ok","MessageData":{}}';

var raw = JSON.parse(body);
var membershipID = raw.Response[0].membershipId;

console.log(membershipID);


来源: stackexchange

问:
Facebook Graph API - complete server side auth and API calls
I have an application, that runs on server. On that server is background task, that will post status update on few social networks (Facebook, Twitter, G+). It must be completely server-side.

In Twitter API I'm able to use OAuth header to authorize API request. OAuth HTTP header uses consumer key, consumer secret, access token and access token secret to create the header. With this I'm able to post/update/delete tweets with no user interaction.

How can I do this for Facebook? I found a solution to obtain a long-lived access_token (2 months), but we don't want to regenerate access_token every 60 days. We want to use it for manage our Facebook page - post status updates, but completely server-side.

Am I able to do this for Facebook? Thanks for answers.
PS: I searched stackoverflow hundred-times but with no solution for my problem.

Thanks.

答:
Pay attention to Access Tokens Expiration & Extentions.
The Page Access Token could be a good solution to only server side calls for testing and data analysis purposes.

Take your User Access Token from Graph API Tool

Extend your User Access Token

Call https://graph.facebook.com/v2.11/me/accounts with your user access token extended

*all calls are GET and this procedure does not use APP Access Token.

ContentLicense: CC BY-SA 3.0


问:
How to send a notification to another PC?
Is there a way i can send a notification/message to another PC in C/C++? I think something like net send, but i don't know if there is another way to send a notification/message. I created an application which will run on every PC, and i want, that if my application has finished it should send a notification to my PC, that it has finished running. I don't know if there is a solution for my question, but if yes, could someone tell me, how to do that?

Thanks,

kampi

答:
How about using sockets?

http://www.alhem.net/Sockets/tutorial/

ContentLicense: CC BY-SA 2.5


问:
Read CSV and create data frame
I would like to save the following commands in a shorter way so that each time I do not repeat the same actions.</p>

```<code>aa <- read_excel("C:/Users/Piotr/Desktop/aa.xlsx")
bb <- read_excel("C:/Users/Piotr/Desktop/bb.xlsx")

data=as.data.frame(aa[1:100,c(1, 18, 20, 22, 35, 39, 41, 44)])
row.names(data) <- data$Player
data=data[,-1]

data2=as.data.frame(bb[1:100,c(1, 18, 20, 22, 35, 39, 41, 44)])
row.names(data2) <- data2$Player
data2=data2[,-1]

data_sets <- c("data","data2")
</code>```

答:
As docendo suggested, just generalize your repeated steps into a function:</p>

```<code>clean_data <- function(x) {

data <- read_excel(paste0("C:/Users/Piotr/Desktop/", x, ".xlsx"))
data=as.data.frame(data[1:100,c(1, 18, 20, 22, 35, 39, 41, 44)])
  row.names(data) <- data$Player
  data=data[,-1]
return(data)
}

data_sets = c(clean_data("aa"), clean_data("bb"))
names(data_sets) = c("data", "data2")
</code>```

Title: Read CSV and create data frame

Body:
I would like to save the following commands in a shorter way so that each time I do not repeat the same actions.

aa <- read_excel("C:/Users/Piotr/Desktop/aa.xlsx")
bb <- read_excel("C:/Users/Piotr/Desktop/bb.xlsx")

data=as.data.frame(aa[1:100,c(1, 18, 20, 22, 35, 39, 41, 44)])
row.names(data) <- data$Player
data=data[,-1]

data2=as.data.frame(bb[1:100,c(1, 18, 20, 22, 35, 39, 41, 44)])
row.names(data2) <- data2$Player
data2=data2[,-1]

data_sets <- c("data","data2")

Body:
As docendo suggested, just generalize your repeated steps into a function:

clean_data <- function(x) {

data <- read_excel(paste0("C:/Users/Piotr/Desktop/", x, ".xlsx"))
data=as.data.frame(data[1:100,c(1, 18, 20, 22, 35, 39, 41, 44)])
  row.names(data) <- data$Player
  data=data[,-1]
return(data)
}

data_sets = c(clean_data("aa"), clean_data("bb"))
names(data_sets) = c("data", "data2")


问:
Wix adding folder as component into installer
i trying to put vsto vsto project into wix installer whom contain 3 files (exe, vsto and folder with application files)

The problem is that i can't put folder into installer , then i put .exe and .vsto files as a component into wix installer all ok , but then i try to put folder , i get an error :

```<code>"The Component/@Id attribute's value, 'Application Files', is not a legal identifier.  Identifier's may contain ASCII characters A-Z, a-z, digits, underscores (_), or periods (.).  Every identifier must begin with either a letter or an underscore. (CNDL0015)
</code>```

Here is my full code of product.wxs:

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
    <Product Id="*" Name="SetupProject1" Language="1033" Version="1.0.0.0" Manufacturer="test" UpgradeCode="dddf18f9-28e4-445c-92a1-734e5e774125">
        <Package InstallerVersion="200" Compressed="yes" InstallScope="perMachine" />

        <MajorUpgrade DowngradeErrorMessage="A newer version of [ProductName] is already installed." />
        <MediaTemplate />

        <Feature Id="ProductFeature" Title="SetupProject1" Level="1">
            <ComponentGroupRef Id="ProductComponents" />
        </Feature>
    </Product>
    <Fragment>
        <Directory Id="TARGETDIR" Name="SourceDir">
            <Directory Id="ProgramFilesFolder">
                <Directory Id="INSTALLFOLDER" Name="SetupProject1" />
            </Directory>
        </Directory>
  </Fragment>

    <Fragment>
        <ComponentGroup Id="ProductComponents" Directory="INSTALLFOLDER">
      <Component Id="setup.exe">
        <File Id="setup.exe" KeyPath="yes"
        Name="setup.exe" Source="$(var.AddinFiles)"></File>
      </Component>
      <Component Id="Com.VistaDraft.Distribution.Mvp.vsto">
          <File Id="Com.VistaDraft.Distribution.Mvp.vsto" KeyPath="yes"
                Name="Com.VistaDraft.Distribution.Mvp.vsto" Source="$(var.AddinFiles)"></File>
      </Component>
      <Component Id="Application Files">
          <File Id="Application Files" KeyPath="yes"
                Name="Application Files" Source="$(var.AddinFiles)"></File>
          </Component>
        </ComponentGroup>
    </Fragment>
</Wix>
</code>```

Maybe whom plz help with adding a folder into wix installer ?

答: The error you referenced tells you that Id attributes can only have a-z, A-Z, digits, underscores, and periods. The Id attribute you have used has a space in it.</p>

Body:
i trying to put vsto vsto project into wix installer whom contain 3 files (exe, vsto and folder with application files)

The problem is that i can't put folder into installer , then i put .exe and .vsto files as a component into wix installer all ok , but then i try to put folder , i get an error :

"The Component/@Id attribute's value, 'Application Files', is not a legal identifier.  Identifier's may contain ASCII characters A-Z, a-z, digits, underscores (_), or periods (.).  Every identifier must begin with either a letter or an underscore. (CNDL0015)

Here is my full code of product.wxs:

    <?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
    <Product Id="*" Name="SetupProject1" Language="1033" Version="1.0.0.0" Manufacturer="test" UpgradeCode="dddf18f9-28e4-445c-92a1-734e5e774125">
        <Package InstallerVersion="200" Compressed="yes" InstallScope="perMachine" />

        <MajorUpgrade DowngradeErrorMessage="A newer version of [ProductName] is already installed." />
        <MediaTemplate />

        <Feature Id="ProductFeature" Title="SetupProject1" Level="1">
            <ComponentGroupRef Id="ProductComponents" />
        </Feature>
    </Product>
    <Fragment>
        <Directory Id="TARGETDIR" Name="SourceDir">
            <Directory Id="ProgramFilesFolder">
                <Directory Id="INSTALLFOLDER" Name="SetupProject1" />
            </Directory>
        </Directory>
  </Fragment>

    <Fragment>
        <ComponentGroup Id="ProductComponents" Directory="INSTALLFOLDER">
      <Component Id="setup.exe">
        <File Id="setup.exe" KeyPath="yes"
        Name="setup.exe" Source="$(var.AddinFiles)"></File>
      </Component>
      <Component Id="Com.VistaDraft.Distribution.Mvp.vsto">
          <File Id="Com.VistaDraft.Distribution.Mvp.vsto" KeyPath="yes"
                Name="Com.VistaDraft.Distribution.Mvp.vsto" Source="$(var.AddinFiles)"></File>
      </Component>
      <Component Id="Application Files">
          <File Id="Application Files" KeyPath="yes"
                Name="Application Files" Source="$(var.AddinFiles)"></File>
          </Component>
        </ComponentGroup>
    </Fragment>
</Wix>

Maybe whom plz help with adding a folder into wix installer ?


问:
Java Beginner: How do I link one linked list to another?
If I have: linkedlist1= 1,2,3,4; and   linkedlist2= 5,6,7;

Am I able to attach linkedlist2 to the end of linkedlist1 in such a way if I invoke: linkedlist2.set(0,9999)  it changes to linkedlist2 = [999,6,7] and  linkedlist1 becomes [1,2,3,4,9999,7,8]; ?

Is that possible ? Or I do need another structure ?

The following code didn't work:

```<code> List<Double> l1 = new LinkedList<Double>(Arrays.asList(1.0,2.0));
 List<Double> l2 = new LinkedList<Double>(Arrays.asList(3.0,4.0));
 l1.addAll(l2);
 System.out.println(l1);
 l2.set(0, 9.0);
 System.out.println(l1);
</code>```

OUTPUT:

```<code> [1.0, 2.0, 3.0, 4.0]
 [1.0, 2.0, 3.0, 4.0]
</code>```

答:
This problem seems to be a nice application for the subList(int, int) method:

```<code>List<Double> l1 = new LinkedList<Double>(Arrays.asList(1.0, 2.0, 3.0, 4.0));
List<Double> l2 = l1.subList(2, 4);
</code>```

Alas, the JavaDoc of subList states:

The semantics of the list returned by
  this method become undefined if the
  backing list (i.e., this list) is
  structurally modified in any way other
  than via the returned list.
  (Structural modifications are those
  that change the size of this list, or
  otherwise perturb it in such a fashion
  that iterations in progress may yield
  incorrect results.)

So if you want to use a method like .add on l1, then you may be out of luck. In fact, for all fail-fast list classes derived from AbstractList (such as as LinkedList), subList should throw a ConcurrentModificationException after the parent list of a subList was structurally modified.

However, if you stay away from structural modifications in the parent list (or if you re-create the sub-list after such modifications), then everything will work as expected.

Body:
If I have: linkedlist1= 1,2,3,4; and   linkedlist2= 5,6,7;

Am I able to attach linkedlist2 to the end of linkedlist1 in such a way if I invoke: linkedlist2.set(0,9999)  it changes to linkedlist2 = [999,6,7] and  linkedlist1 becomes [1,2,3,4,9999,7,8]; ?

Is that possible ? Or I do need another structure ?

The following code didn't work:

 List<Double> l1 = new LinkedList<Double>(Arrays.asList(1.0,2.0));
 List<Double> l2 = new LinkedList<Double>(Arrays.asList(3.0,4.0));
 l1.addAll(l2);
 System.out.println(l1);
 l2.set(0, 9.0);
 System.out.println(l1);

OUTPUT:

 [1.0, 2.0, 3.0, 4.0]
 [1.0, 2.0, 3.0, 4.0]

Body:
This problem seems to be a nice application for the subList(int, int) method:

List<Double> l1 = new LinkedList<Double>(Arrays.asList(1.0, 2.0, 3.0, 4.0));
List<Double> l2 = l1.subList(2, 4);

Alas, the JavaDoc of subList states:

The semantics of the list returned by
  this method become undefined if the
  backing list (i.e., this list) is
  structurally modified in any way other
  than via the returned list.
  (Structural modifications are those
  that change the size of this list, or
  otherwise perturb it in such a fashion
  that iterations in progress may yield
  incorrect results.)

So if you want to use a method like .add on l1, then you may be out of luck. In fact, for all fail-fast list classes derived from AbstractList (such as as LinkedList), subList should throw a ConcurrentModificationException after the parent list of a subList was structurally modified.

However, if you stay away from structural modifications in the parent list (or if you re-create the sub-list after such modifications), then everything will work as expected.


问:
Color overlay on img tag with shape
I have a image with border radius, and want to add a color overlay over the image.

  img {
    border-bottom-left-radius: 60% 65%;
    border-bottom-right-radius: 35%;
    border-top-left-radius: 40px 200px;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="image-wrapper">
<img width="751" height="640" src="http://via.placeholder.com/751x640" class="" alt="">
</div></code>```

The image has a oval shape with border-radius

If I add a color with pseudo element on the div/container it doesn't overlay in a oval shape but the full container.

How to place a color overlay (just for the image) on a img tag with border radius?

答:
Put the border-radius on the parent element with overflow: hidden, then add your overlay effect:

```<code>.image-wrapper {
    display: inline-block;
    position: relative;
    border-bottom-left-radius: 60% 65%;
    border-bottom-right-radius: 35%;
    border-top-left-radius: 40px 200px;
    overflow: hidden;
}

.image-wrapper::after {
    content: '';
    display: block;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: rgba(0, 128, 255, 0.5);
}
</code>```

Title: Color overlay on img tag with shape

Body:
I have a image with border radius, and want to add a color overlay over the image.

  img {
    border-bottom-left-radius: 60% 65%;
    border-bottom-right-radius: 35%;
    border-top-left-radius: 40px 200px;
    }

The image has a oval shape with border-radius

If I add a color with pseudo element on the div/container it doesn't overlay in a oval shape but the full container.

How to place a color overlay (just for the image) on a img tag with border radius?

Body:
Put the border-radius on the parent element with overflow: hidden, then add your overlay effect:

.image-wrapper {
    display: inline-block;
    position: relative;
    border-bottom-left-radius: 60% 65%;
    border-bottom-right-radius: 35%;
    border-top-left-radius: 40px 200px;
    overflow: hidden;
}

.image-wrapper::after {
    content: '';
    display: block;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: rgba(0, 128, 255, 0.5);
}


问:
How to Append the elements value count
And i received a new task in jquery. I posted the code snippet until i tried.

$(document).on("click", ".add", function (e) {
    e.preventDefault();
    $.ajax({
        url: url,
        type: "post",
        data: postdata,
        success: function (data) {
            var count = $('#counts').children('li span').length;

        }
    })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>li{
  list-style-type: none;
}</code>```

5

6

8

2

<button class="add">
Add result
</button>

```

Here after really i have no idea to do. My question was

How to append the all span elements value count to .class element(When clicking the button). The span elements value may change dynamically.

Thanks in advance.

答:
I don't uderstand your ajax  call...

Anyway you have to create a total variable equal to 0 first after just loop in your span elements and add the result in your total...

$(document).on("click", ".add", function (e) {
    var total = 0;
    $(".counts li span").each(function(){
      total += parseInt($(this).text());
    });
    $(".result").text(total)
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>li{
  list-style-type: none;
}</code>```

5

6

8

2

<button class="add">
Add result
</button>

```

Title: How to Append the elements value count

Body:
And i received a new task in jquery. I posted the code snippet until i tried.

$(document).on("click", ".add", function (e) {
    e.preventDefault();
    $.ajax({
        url: url,
        type: "post",
        data: postdata,
        success: function (data) {
            var count = $('#counts').children('li span').length;

        }
    })
});

li{
  list-style-type: none;
}

5

6

8

2

<button class="add">
Add result
</button>

Here after really i have no idea to do. My question was

How to append the all span elements value count to .class element(When clicking the button). The span elements value may change dynamically.

Thanks in advance.

Body:
I don't uderstand your ajax  call...

Anyway you have to create a total variable equal to 0 first after just loop in your span elements and add the result in your total...

$(document).on("click", ".add", function (e) {
    var total = 0;
    $(".counts li span").each(function(){
      total += parseInt($(this).text());
    });
    $(".result").text(total)
});

li{
  list-style-type: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
<ul class="top-ul">
<li> </li>
<li><ul class="counts">
  <li><span>5</span></li>
  <li><span>6</span></li>
  </ul></li>
<li><ul class="counts">
  <li><span>8</span></li>
  <li><span>2</span></li>
  </ul></li>
</ul>
</div>

<button class="add">
Add result
</button>
<div>
<p class="result">
</p>
</div>


问:
Calculate phase angle in Optical flow
i want to an understanding about phase angle of optical flow. if I know about particular point Vx and Vy ( velocity), Then how can I calculate phase angle(radian) using the above parameters.

答:
Given a point, with optical flow value of Vx,Vy, the angle can be calculated as follows:</p>

```<code>angle = atan2(Vy, Vx);
</code>```

Title: Calculate phase angle in Optical flow

Body:
Given a point, with optical flow value of Vx,Vy, the angle can be calculated as follows:

angle = atan2(Vy, Vx);


问:
How to find large web site favicons or logo from host link?
Is there a free solution to get the large logo or favicon (about 100 x 100 px) from a website from the host link?

I found several tracks but nothing satisfactory:

Google S2 but I can not find a way to have a size larger than 32x32 or 64x64
http://www.google.com/s2/favicons?domain={URI.host}

In Google's Inbox, we find a "brand_avatar_url" which points to https://ci4.googleusercontent.com/ where we can choose the size but the link can not be found as a simple user or even via the API

Do you know a simple and free solution?

答:
From wikipedia :

such icon files can be 16×16, 32×32, 48×48, or 64×64 pixels in size, and 8-bit, 24-bit, or 32-bit in color depth

And now W3C :

However, the format for the image you have chosen must be 16x16 pixels or 32x32 pixels, using either 8-bit or 24-bit colors. The format of the image must be one of PNG (a W3C standard), GIF, or ICO.

That's perfectly normal not to find a hi-res version of the favicon...

The favicon logo is usually hosted on the website itself, the simplest solution would be to look directly into the code :

```<code><head>
    <title>Awesome Prods - Association de courts-métrages</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
    <link rel="icon" href="/icon/favicon.ico">
    <meta charset="utf-8">
    <meta name=viewport content="width=device-width, initial-scale=1">
    <meta name="description" content="Awesome Prods, association de création de courts-métrages.">
</head>
</code>```

The favicon is located in the <link rel="icon"> tag.

Body:
From wikipedia :

such icon files can be 16×16, 32×32, 48×48, or 64×64 pixels in size, and 8-bit, 24-bit, or 32-bit in color depth

And now W3C :

However, the format for the image you have chosen must be 16x16 pixels or 32x32 pixels, using either 8-bit or 24-bit colors. The format of the image must be one of PNG (a W3C standard), GIF, or ICO.

That's perfectly normal not to find a hi-res version of the favicon...

The favicon logo is usually hosted on the website itself, the simplest solution would be to look directly into the code :

<head>
    <title>Awesome Prods - Association de courts-métrages</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
    <link rel="icon" href="/icon/favicon.ico">
    <meta charset="utf-8">
    <meta name=viewport content="width=device-width, initial-scale=1">
    <meta name="description" content="Awesome Prods, association de création de courts-métrages.">
</head>

The favicon is located in the <link rel="icon"> tag.


问:
xcode simulate location gpx time duration?
Is it possible to put a time duration (e.g. 2:00pm - 4:30pm) for a gpx file to simulate location on an iOS device for a specific amount of time?

Here is what I have so far:

```<code><?xml version="1.0"?>
<gpx version="1.1" creator="Xcode">

    <wpt lat="41.7264" lon="-73.9339">
        <name>College</name>

    </wpt>

</gpx>
</code>```

If there isn't a way to put an allotted amount of time, is there a way to put a time duration such as 2.5 hrs ? Thanks.

Body:
Is it possible to put a time duration (e.g. 2:00pm - 4:30pm) for a gpx file to simulate location on an iOS device for a specific amount of time?

Here is what I have so far:

<?xml version="1.0"?>
<gpx version="1.1" creator="Xcode">

    <wpt lat="41.7264" lon="-73.9339">
        <name>College</name>

    </wpt>

</gpx>

If there isn't a way to put an allotted amount of time, is there a way to put a time duration such as 2.5 hrs ? Thanks.

Body:
add in wpt

<time>2014-09-24T14:55:37Z</time>


问:
Finding elements by class in Selenium
Okay, so I'm trying to find the 179 in:

```<code><span class="totalcount">179</span>
</code>```

However, for some reason:

```<code>maxpage = driver.find_element_by_class_name('totalcount')
</code>```

results in maxpage being set equal to:

```<code><selenium.webdriver.firefox.webelement.FirefoxWebElement (session="2c241847-ac56-4ed5-bb0e-73b473833ce4", element="9f837b6e-e78f-4fca-87b8-4efcb463e5a3")>
</code>```

But I want to get value equal to 179. Do you have any advice?

答: maxpage is instance of WebElement class. Use maxpage.text to get content.

Title: Finding elements by class in Selenium

Body:
Okay, so I'm trying to find the 179 in:

179

However, for some reason:

maxpage = driver.find_element_by_class_name('totalcount')

results in maxpage being set equal to:

<selenium.webdriver.firefox.webelement.FirefoxWebElement (session="2c241847-ac56-4ed5-bb0e-73b473833ce4", element="9f837b6e-e78f-4fca-87b8-4efcb463e5a3")>

But I want to get value equal to 179. Do you have any advice?


问:
Minimizing borderless dialog issue
I want to minimize the borderless modal dialog so it should stay in the taskbar. The problem is, the dialog minimized to the bottom of the screen:

Screenshot:

Code:

```<code>setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint);
setWindowModality(Qt::ApplicationModal);
this->setWindowState(Qt::WindowMinimized);
</code>```

Also, this dialog is not the main window, so I think it should minimize them both when clicking minimize in the dialog and the issue is present in another non borderless modal dialog.

Screenshot with minimized modal dialog with borders:

I use Qt 5.9.2 on Windows 10.  How to fix this issue? Thanks in advance.

答: So the issue has been fixed by removing parent or setting it to nullptr. Thanks to @Felix information, this is not a bug in Qt, it's default Windows behavior.

Title: Minimizing borderless dialog issue

Body:
I want to minimize the borderless modal dialog so it should stay in the taskbar. The problem is, the dialog minimized to the bottom of the screen:

Screenshot:

Code:

setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint);
setWindowModality(Qt::ApplicationModal);
this->setWindowState(Qt::WindowMinimized);

Also, this dialog is not the main window, so I think it should minimize them both when clicking minimize in the dialog and the issue is present in another non borderless modal dialog.

Screenshot with minimized modal dialog with borders:

I use Qt 5.9.2 on Windows 10.  How to fix this issue? Thanks in advance.


问:
Add new Column in table with jquery
Hi there I need your help, I have this blade on larevel :

```<code>                       <div class="row">
                        <div class="form-group col-sm-12">
                            <div class="col-xs-offset-12 col-xs-2">
                                <button type="button" class="btn btn-block btn-flat btn-primary btn-sm" id="add_column" title="@lang('buttons.add_new_option')">
                                    <i class="fa fa-plus"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                 <table class="optionsForm" style="width:100%">
                <tr>
                  <th>
                    </th>  @for($c = 1; $c<=4; $c++)
                      <th>
                        <input type="text" name="options{{ $c }}" value="{{ old('options.'.$c) }}"
                        class="form-control" placeholder="Column {{ $c }} ">
                    </th>
                    @endfor
                  </tr>

                  @for($r = 1; $r <=4; $r++)
                    <tr>
                        <td>
                          <input type="text" name="match{{ $r}}" value="{{ old('match.'.$r) }}"
                                 class="form-control" placeholder="Row {{ $r }} ">
                        <td>
                          <input type="radio" name="col_nr[{{ $r  }}]" value="1" class="col1">
                        </td>
                        <td>
                          <input type="radio" name="col_nr[{{ $r  }}]" value="2" class="col2">
                        </td>
                        <td>
                          <input type="radio" name="col_nr[{{ $r  }}]"  value="3" class="col3">
                        </td>
                        <td>
                          <input type="radio" name="col_nr[{{ $r  }}]" value="4" class="col4">
                        </td>
                        <input type="hidden" name="row_col_nr[{{$r}}]" value="0" class="row_col_nr{{ $r  }}">

                  </tr>
                @endfor
                <tr>
                </tr>
              </table>
         <div class="row">
                        <div class="form-group col-sm-12">
                            <div class=" col-xs-3">
                                <button type="button" class="btn btn-block btn-flat btn-primary btn-sm" id="add_option" title="@lang('buttons.add_new_option')">
                                    <i class="fa fa-plus"></i>
                                </button>
                            </div>
                        </div>
                    </div>
</code>```

The view is a like a table..
And on the other hand my js code is this which I am using two buttons add_option and add column since the add row it was easier I managed to solve that but with adding column I have a problem:

```<code><script>
var i = 4;
  var p = 1;
  $(document).ready(function () {
    $('#add_option').click(function () {
      i++;
      $('.optionsForm').append('<tr><td><input type="text" name="match'+ i +'" value="{{ old('match. + p +') }}"  class="form-control" placeholder="Row ' + i +' "><td><input type="radio" name="col_nr['+ i +']"  value="1" class="col1" ></td><td><input type="radio" name="col_nr['+ i +']" value="2" class="col1" ></td><td><input type="radio" name="col_nr['+ i +']"   value="3" class="col1" ></td><td><input type="radio" name="col_nr['+ i+']"value="4" class="col1" ></td></tr>');

    }
    );
    $(document).on('click', 'button[id=delete_option]', function () {
      console.log('test');
      if (i > 1) {
        var removeValue = $(this).val();
        $('#option' + removeValue).remove();
        --i;
      }
    }
    );
  }
  );
</script>
<script type="text/javascript">
    var i = 4;
  var p = 1;
  $(document).ready(function () {
    $('#add_column').click(function () {
      i++;
      $('.optionsForm ').append('<tr></tr><tr><th><input type="text" name="options'+ i +'" value="{{ old('options. + p +') }}"  class="form-control" placeholder="Col ' + i +' "></th></tr>');

    }
    );
    $(document).on('click', 'button[id=delete_option]', function () {
      console.log('test');
      if (i > 1) {
        var removeValue = $(this).val();
        $('#option' + removeValue).remove();
        --i;
      }
    }
    );
  }
  );
</script>
</code>```

For adding a new row it is working fine but with column I am having a problem, I cannot add the new column in the right place after the last one the radio inputs are not in the right place.. Can someone please help me.

答:
try this code as you would like

<!doctype html>

    <title>tiff.js demo</title>

Name

sdg

sdfg

sdgds

  <button type="button" data-id="5" class="get_attr" >Click Me</button>

```

also added row column value in respective cloumn

Title: Add new Column in table with jquery

Body:
Hi there I need your help, I have this blade on larevel :

                                <button type="button" class="btn btn-block btn-flat btn-primary btn-sm" id="add_column" title="@lang('buttons.add_new_option')">

                                </button>

                    	  @for($c = 1; $c<=4; $c++)

                        <input type="text" name="options{{ $c }}" value="{{ old('options.'.$c) }}"
                        class="form-control" placeholder="Column {{ $c }} ">

                    @endfor

                  @for($r = 1; $r <=4; $r++)

                          <input type="text" name="match{{ $r}}" value="{{ old('match.'.$r) }}"
                                 class="form-control" placeholder="Row {{ $r }} ">

                          <input type="radio" name="col_nr[{{ $r  }}]" value="1" class="col1">

                          <input type="radio" name="col_nr[{{ $r  }}]" value="2" class="col2">

                          <input type="radio" name="col_nr[{{ $r  }}]"  value="3" class="col3">

                          <input type="radio" name="col_nr[{{ $r  }}]" value="4" class="col4">

                        <input type="hidden" name="row_col_nr[{{$r}}]" value="0" class="row_col_nr{{ $r  }}">

                @endfor

                                <button type="button" class="btn btn-block btn-flat btn-primary btn-sm" id="add_option" title="@lang('buttons.add_new_option')">

                                </button>

The view is a like a table..
And on the other hand my js code is this which I am using two buttons add_option and add column since the add row it was easier I managed to solve that but with adding column I have a problem:

For adding a new row it is working fine but with column I am having a problem, I cannot add the new column in the right place after the last one the radio inputs are not in the right place.. Can someone please help me.

Body:
try this code as you would like

<!doctype html>
<html>
  <head>
    <title>tiff.js demo</title>
  </head>
  <body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript">
$(document).ready(function(){

$(".get_attr").click(function (){
 var trow;//=$('.optionsForm tr:first').html();
 trow='<th>Class</th>';
 $('.optionsForm tr:first').append(trow);
 var tdr={};//=$('.optionsForm tr:first').html();
 tdr=['<td>sdg</td>','<td>sdfg</td>','<td>sdgds</td>'];
 var rowleng=$('.optionsForm tbody tr').length;
 for(i=0;i<=rowleng;i++)
     {
   $('.optionsForm tbody tr').eq(i).append(tdr[i]);

  }
   });

});
    </script>
  </body>

<table border="1" class='optionsForm'>
  <thead><tr><th>Name</th></tr></thead>
  <tbody>
  <tr><td>sdg</td></tr>
  <tr><td>sdfg</td></tr>
  <tr><td>sdgds</td></tr>
  </tbody>

  </table>

  <button type="button" data-id="5" class="get_attr" >Click Me</button>

</html>

also added row column value in respective cloumn


问:
Is signed char overflow undefined within the range -255 to 255?
Is the following code undefined behavior according to GCC in C99 mode:</p>

```<code>signed char c = CHAR_MAX; // assume CHAR_MAX < INT_MAX
c = c + 1;
printf("%d", c);
</code>```

答:
signed char overflow does cause undefined behavior, but that is not what happens in the posted code.

With c = c + 1, the integer promotions are performed before the addition, so c is promoted to int in the expression on the right. Since 128 is less than INT_MAX, this addition occurs without incident. Note that char is typically narrower than int, but on rare systems char and int may be the same width. In either case a char is promoted to int in arithmetic expressions.

When the assignment to c is then made, if plain char is unsigned on the system in question, the result of the addition is less than UCHAR_MAX (which must be at least 255) and this value remains unchanged in the conversion and assignment to c.

If instead plain char is signed, the result of the addition is converted to a signed char value before assignment. Here, if the result of the addition can't be represented in a signed char the conversion "is implementation-defined, or an implementation-defined signal is raised," according to §6.3.1.3/3 of the Standard. SCHAR_MAX must be at least 127, and if this is the case then the behavior is implementation-defined for the values in the posted code when plain char is signed.

The behavior is not undefined for the code in question, but is implementation-defined.

Body:
Is the following code undefined behavior according to GCC in C99 mode:

signed char c = CHAR_MAX; // assume CHAR_MAX < INT_MAX
c = c + 1;
printf("%d", c);


问:
print numbers from 200 to 150 in reverse order and print numbers from 200 to 150 in a sequential order using while?
how to print numbers from 200 to 150 in reverse order and print numbers from 200 to 150 in a sequential order using single while loop?</p>

```<code>class test {
    public static void main(String[]args) {
        while(n>=150) {
            System.out.println(n);
            n--;
        }
        n=0;
        while(n<=150) {
            System.out.println(n);
            n++;
        }
    }
}
</code>```

答:
Here you go:</p>

```<code>public static void main(String[] args) {
    int n = 150;
    while(n <= 200) {
        System.out.println("Decreasing : " + (150 + (200 - n)));
        System.out.println("Increating : " + (n++));
    }
}
</code>```

Body:
how to print numbers from 200 to 150 in reverse order and print numbers from 200 to 150 in a sequential order using single while loop?

class test {
    public static void main(String[]args) {
        while(n>=150) {
            System.out.println(n);
            n--;
        }
        n=0;
        while(n<=150) {
            System.out.println(n);
            n++;
        }
    }
}

Body:
Here you go:

public static void main(String[] args) {
    int n = 150;
    while(n <= 200) {
        System.out.println("Decreasing : " + (150 + (200 - n)));
        System.out.println("Increating : " + (n++));
    }
}


问:
How to run another copy of python 3
I have tow copies of python 3 on my mac (running macOS Sierra, Mid 2012) one with pygame installed and one without.

If I try to run my game script I get an error message that there is no module named pygame

I use sublime text to edit my python files and want the terminal open to just hit the up arrow and Enter to run my scrip after I edited it.

答:
Virtual environments are a good practice in python development. Install virtualenv.

```<code>sudo pip install virtualenv
</code>```

Create new virtual environment then activate it and install all required packages. This approach will allow you to have specific packages for each project you're working on.

More about virtual environments here

Title: How to run another copy of python 3

Body:
Virtual environments are a good practice in python development. Install virtualenv.

sudo pip install virtualenv

Create new virtual environment then activate it and install all required packages. This approach will allow you to have specific packages for each project you're working on.

More about virtual environments here

ContentLicense: CC BY-SA 4.0


问:
setTitleImage and FileLocator
I am going to set title Image of jface dialog in the java plugin. When I write the below code, I have an error. The file cannot be found. What should I do?</p>

```<code>Bundle bundle = Platform.getBundle("Layout");
URL url = FileLocator.find(bundle, new Path("icon/c.png"), null);
image = new Image(Display.getDefault(), url.toString());
setTitleImage(image);
</code>```

答:
The URL returned by FileLocator.find uses a special 'protocol' value which is only understood by Eclipse and JFace code (something like bundleentry://84.fwk537066525/icon/c.png). SWT code such as Image does not understand the URL.

The best thing to do is create the Image from a JFace ImageDescriptor:

```<code>ImageDescriptor desc = ImageDescriptor.createFromURL(url);

Image image = desc.createImage();
</code>```

You can also use FileLocator.toFileURL but this may cause the plugin to be unpacked so should be avoided in this case where there is a better alternative.

Title: setTitleImage and FileLocator

Body:
I am going to set title Image of jface dialog in the java plugin. When I write the below code, I have an error. The file cannot be found. What should I do?

Bundle bundle = Platform.getBundle("Layout");
URL url = FileLocator.find(bundle, new Path("icon/c.png"), null);
image = new Image(Display.getDefault(), url.toString());
setTitleImage(image);

Body:
The URL returned by FileLocator.find uses a special 'protocol' value which is only understood by Eclipse and JFace code (something like bundleentry://84.fwk537066525/icon/c.png). SWT code such as Image does not understand the URL.

The best thing to do is create the Image from a JFace ImageDescriptor:

ImageDescriptor desc = ImageDescriptor.createFromURL(url);

Image image = desc.createImage();

You can also use FileLocator.toFileURL but this may cause the plugin to be unpacked so should be avoided in this case where there is a better alternative.


问:
ember-drag-sort: how to determine the new parent in the dragged list?
Originally asked by @andrewsyd on GitHub.

For a nested list, is there a way to determine in the dragEnd action which "sub-list" the item has been dropped into? (e.g. a class name, id etc)

In my scenario, I am sorting ember data records that can belong to each other (i.e. a nested, 'tree' structure). When I drag one nested record "into" another (making the dragged record a child of the second record), I need to update the parent attribute in ember-data. My question is, how do you pass some id of the second record (the new parent) to the dragEnd action?

Is this even possible?

答:
Solution 0: adjust your data model to convert the isParent attribute into a derived value rather than a source of truth

Having an isParent attribute that must be updated by hand is a flawed approach in the first place.

If you have the isParent state as an attribute and require the frontend to update it, then you have two sources of truth that can (and eventually will) go out of sync. Especially so given the fact that users can tamper with network requests to your API backend.

The isParent should be inferred from the amount of children. It could be a simple computed property:

```<code>{
  isParent: computed('children.[]', function () {
    return this.get('children.length') > 0
  }
}
</code>```

A similar approach can be used on the backend.

If you don't control the backend and still need to update the isParent attribute from the frontend side, I recommend that you hack your serializer to include the isParent computed property value into the payload during serialization.

Though I strongly believe you should go with this solution, I've researched a couple alternative solutions below.

Solution 1: use an observer to update the parent state automatically

In your model:

```<code>{
  updateParentState: Ember.observer('children.[]', function () {
   const isParent = this.get('children.length') > 0
    this.setProperties({isParent})
  })
}
</code>```

This will keep the isParent attribute synchronized with its children relationship whenever it's updated.

Here's a demo: https://ember-twiddle.com/f1c737d3bc106cb9cca071fd01fe334f?openFiles=models.item.js%2C

Note that if you automatically save your record(s) on drag end, you should wrap saving into Ember.run.next, so that saving happens after the observer fires.

Solution 2: access the old and new parent of the dragged item

Given that you have relationships set up like this:

```<code>export default Model.extend({
  isParent: attr('boolean'),
  parent: belongsTo('item', {inverse: 'children'}),
  children: hasMany('item', {inverse: 'parent'}),
})
</code>```

...you can access the old and new parent of the dragged item in the drag end action!

```<code>{
  actions : {
    dragEnd ({sourceList, sourceIndex, targetList, targetIndex}) {
      if (sourceList === targetList && sourceIndex === targetIndex) return

      const draggedItem = sourceList.objectAt(sourceIndex)
      const oldParent = draggedItem.get('parent')                     // <--

      sourceList.removeAt(sourceIndex)
      targetList.insertAt(targetIndex, draggedItem)

      const newParent = draggedItem.get('parent')                     // <--

      newParent.set('isParent', newParent.get('children.length') > 0) // <--
      oldParent.set('isParent', oldParent.get('children.length') > 0) // <--
    },
  }
}
</code>```

I've marked relevant lines with arrow comments.

See, you read the old parent from the dragged item before moving it. After you move the item, you read the new parent. This is possible because Ember Data performs relationship bookkeeping automatically.

Finally, you update the isParent state of both parents.

Demo: https://ember-twiddle.com/ab0bfdce6a1f5ad4bd0d1c9c45f642fe?openFiles=controllers.application.js%2Ctemplates.components.the-item.hbs

Body:
Solution 0: adjust your data model to convert the isParent attribute into a derived value rather than a source of truth

Having an isParent attribute that must be updated by hand is a flawed approach in the first place.

If you have the isParent state as an attribute and require the frontend to update it, then you have two sources of truth that can (and eventually will) go out of sync. Especially so given the fact that users can tamper with network requests to your API backend.

The isParent should be inferred from the amount of children. It could be a simple computed property:

{
  isParent: computed('children.[]', function () {
    return this.get('children.length') > 0
  }
}

A similar approach can be used on the backend.

If you don't control the backend and still need to update the isParent attribute from the frontend side, I recommend that you hack your serializer to include the isParent computed property value into the payload during serialization.

Though I strongly believe you should go with this solution, I've researched a couple alternative solutions below.

Solution 1: use an observer to update the parent state automatically

In your model:

{
  updateParentState: Ember.observer('children.[]', function () {
   const isParent = this.get('children.length') > 0
    this.setProperties({isParent})
  })
}

This will keep the isParent attribute synchronized with its children relationship whenever it's updated.

Here's a demo: https://ember-twiddle.com/f1c737d3bc106cb9cca071fd01fe334f?openFiles=models.item.js%2C

Note that if you automatically save your record(s) on drag end, you should wrap saving into Ember.run.next, so that saving happens after the observer fires.

Solution 2: access the old and new parent of the dragged item

Given that you have relationships set up like this:

export default Model.extend({
  isParent: attr('boolean'),
  parent: belongsTo('item', {inverse: 'children'}),
  children: hasMany('item', {inverse: 'parent'}),
})

...you can access the old and new parent of the dragged item in the drag end action!

{
  actions : {
    dragEnd ({sourceList, sourceIndex, targetList, targetIndex}) {
      if (sourceList === targetList && sourceIndex === targetIndex) return

      const draggedItem = sourceList.objectAt(sourceIndex)
      const oldParent = draggedItem.get('parent')                     // <--

      sourceList.removeAt(sourceIndex)
      targetList.insertAt(targetIndex, draggedItem)

      const newParent = draggedItem.get('parent')                     // <--

      newParent.set('isParent', newParent.get('children.length') > 0) // <--
      oldParent.set('isParent', oldParent.get('children.length') > 0) // <--
    },
  }
}

I've marked relevant lines with arrow comments.

See, you read the old parent from the dragged item before moving it. After you move the item, you read the new parent. This is possible because Ember Data performs relationship bookkeeping automatically.

Finally, you update the isParent state of both parents.

Demo: https://ember-twiddle.com/ab0bfdce6a1f5ad4bd0d1c9c45f642fe?openFiles=controllers.application.js%2Ctemplates.components.the-item.hbs


问:
Custom Date Format with jax-rs in apache cxf?
I have been googling to figure out how I can customize the Date format when I use jax-rs on apache CXF.  I looked at the codes, and it seems that it only support primitives, enum and a special hack that assume the type associated with @FormParam has a constructor with a single string parameter.  This force me to use String instead of Date if I want to use FormParam.  it is kind of ugly.  Is there a better way to do it?

```<code>@POST
@Path("/xxx")
public String addPackage(@FormParam("startDate") Date startDate)
    {
      ...
    }
</code>```

Thanks

答: starting from CXF 2.3.2 registering ParameterHandler will do it. It is also always possible to override the date value (passed as part of the query, etc) using RequestHandler filters for default Date(String) to work</p>

Body:
I have been googling to figure out how I can customize the Date format when I use jax-rs on apache CXF.  I looked at the codes, and it seems that it only support primitives, enum and a special hack that assume the type associated with @FormParam has a constructor with a single string parameter.  This force me to use String instead of Date if I want to use FormParam.  it is kind of ugly.  Is there a better way to do it?

@POST
@Path("/xxx")
public String addPackage(@FormParam("startDate") Date startDate)
    {
      ...
    }

Thanks


问:
Get list of objects with unique combination of id/values
I have this collection:

```<code>{
  Id: 5,
  postalcodes: {2000, 3000, 4000}
},
{
 Id: 5,
 postalcodes: { 2000, 5000 }
},
{
 Id: 6,
 postalcodes: { 2000, 7000 }
}
</code>```

I would like to get a list of objects containing an ID and postalcode. The ID may occur multiple times, but the postalcode should be unique PER id.

So my result would be:

```<code>{
 id: 5,
 postalcode: 2000
}
{
 id: 5,
 postalcode: 3000
}
{
 id: 5,
 postalcode: 4000
}
{
 id: 5,
 postalcode: 5000
}
{
 id: 6,
 postalcode: 2000
}
{
 id: 6,
 postalcode: 7000
}
</code>```

This is my query:

```<code>collection.Select(x => new

                                                                 {
                                                                     x.id,
                                                                     x.postalcodes
                                                                 })
    .Distinct()
</code>```

I'm stuck in how to flatten the postalcodes so each postal code would create a seperate object.

Thanks!

答:
I think you mean:

```<code>var pairs = collection.SelectMany(x => x.postalcodes.Select(
        y => new { x.Id, postalcode = y })).Distinct();

foreach(var pair in pairs)
{
    Console.WriteLine($"{pair.Id}, {pair.postalcode}");
}
</code>```

Or in LINQ language terms:

```<code>var pairs = (from x in collection
             from postalcode in x.postalcodes
             select new { x.Id, postalcode }).Distinct();
</code>```

The SelectMany expands an inner collection, giving us all the Id / postalcode pairs; then the Distinct collapses them to the uniques.

Which gives:

```<code>5, 2000
5, 3000
5, 4000
5, 5000
6, 2000
6, 7000
</code>```

For the data, I'm using:

```<code>var collection = new[] { new {
        Id = 5,
        postalcodes = new[] { 2000, 3000, 4000}
    },
    new {
        Id = 5,
        postalcodes = new[] { 2000, 5000 }
    },
    new {
        Id = 6,
        postalcodes = new[] { 2000, 7000 }
    }};
</code>```

Body:
I have this collection:

{
  Id: 5,
  postalcodes: {2000, 3000, 4000}
},
{
 Id: 5,
 postalcodes: { 2000, 5000 }
},
{
 Id: 6,
 postalcodes: { 2000, 7000 }
}

I would like to get a list of objects containing an ID and postalcode. The ID may occur multiple times, but the postalcode should be unique PER id.

So my result would be:

{
 id: 5,
 postalcode: 2000
}
{
 id: 5,
 postalcode: 3000
}
{
 id: 5,
 postalcode: 4000
}
{
 id: 5,
 postalcode: 5000
}
{
 id: 6,
 postalcode: 2000
}
{
 id: 6,
 postalcode: 7000
}

This is my query:

collection.Select(x => new

                                                                 {
                                                                     x.id,
                                                                     x.postalcodes
                                                                 })
    .Distinct()

I'm stuck in how to flatten the postalcodes so each postal code would create a seperate object.

Thanks!

Body:
I think you mean:

var pairs = collection.SelectMany(x => x.postalcodes.Select(
        y => new { x.Id, postalcode = y })).Distinct();

foreach(var pair in pairs)
{
    Console.WriteLine($"{pair.Id}, {pair.postalcode}");
}

Or in LINQ language terms:

var pairs = (from x in collection
             from postalcode in x.postalcodes
             select new { x.Id, postalcode }).Distinct();

The SelectMany expands an inner collection, giving us all the Id / postalcode pairs; then the Distinct collapses them to the uniques.

Which gives:

5, 2000
5, 3000
5, 4000
5, 5000
6, 2000
6, 7000

For the data, I'm using:

var collection = new[] { new {
        Id = 5,
        postalcodes = new[] { 2000, 3000, 4000}
    },
    new {
        Id = 5,
        postalcodes = new[] { 2000, 5000 }
    },
    new {
        Id = 6,
        postalcodes = new[] { 2000, 7000 }
    }};


问:
Get all SQL Server services in my machine
I got strange feeling that my local computer runs several versions of SQL Server. How to know all running SQL Servers on my PC?</p>

答:
How to know all running SQL servers on my PC?

Best way would be to go through configuration manager ..As per your version you can open configuration manager and see all the versions of sqlserver installed.

Below is a snippet from my local machine

One more way would be to go through discovery manager,if you have installation media on your system.. you can double click the setup file and click on tools as shown below

and finally you can see all versions of sqlserver in a report like below .Distinct instance Id is the number of instances here.Opening sqlserver 2016 discovery report won't show 2017 instances,so always open with highest version


问:
How to get the content inside div class
I'm writing a python script to extract the details from a website. My code is below.

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url = 'my_company_website'

#opening up connection, grabbing the page
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

#html parsing
page_soup = soup(page_html, "html.parser")

#grabs each product
containers = page_soup.findAll("div",{"class":"navigator-content"})

print (containers)
```

<p>I'm getting the output like this </p>

```

```

I want the contents inside this as output. Please help.

答:
You can try this:

```<code>import re
inside = re.split(r'>*</*div', containers)[1].split()
</code>```

inside is this list:

```<code>['class="navigator-content"',
 'data-issue-table-model-state=""',
 'data-selected-issue=""',
 'data-session-search-state=""']
</code>```

Title: How to get the content inside div class

Body:
I'm writing a python script to extract the details from a website. My code is below.

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url = 'my_company_website'

#opening up connection, grabbing the page
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

#html parsing
page_soup = soup(page_html, "html.parser")

#grabs each product
containers = page_soup.findAll("div",{"class":"navigator-content"})

print (containers)

I'm getting the output like this

I want the contents inside this as output. Please help.

Body:
You can try this:

import re
inside = re.split(r'>*</*div', containers)[1].split()

inside is this list:

['class="navigator-content"',
 'data-issue-table-model-state=""',
 'data-selected-issue=""',
 'data-session-search-state=""']


问:
How to add a tag before another tag using jquery
I'm developing a soccer website  and i want to add before hometeam a red card and after away team a red card,
This is my code:

```<code> if (isHome) {
   $(dataRow).find(".homeTeamName").before("<span class='redcard'></span>");
 } else {
   $(dataRow).find(".AwayTeamName").after("<span class='redcard'></span>");
 }
</code>```

i also used append() to add a tag but it didn't appear nothing
this is my css class:

```<code>.redcard {
    background-color:red;
    width:13px;
    height:20px;
    box-shadow: 3px 3px 1px #888888;
    border-radius:3px
 }
</code>```

答:
it looks like your javascript is correct. The reason why you are not seeing the spans is because they have no width, since they are inline elements.

Try with this CSS:

```<code>.redcard{
    display:inline-block;
    background-color:red;
    width:13px;
    height:20px;
    box-shadow: 3px 3px 1px #888888;
    border-radius:3px
}
</code>```

Body:
I'm developing a soccer website  and i want to add before hometeam a red card and after away team a red card,
This is my code:

 if (isHome) {
   $(dataRow).find(".homeTeamName").before("");
 } else {
   $(dataRow).find(".AwayTeamName").after("");
 }

i also used append() to add a tag but it didn't appear nothing
this is my css class:

.redcard {
    background-color:red;
    width:13px;
    height:20px;
    box-shadow: 3px 3px 1px #888888;
    border-radius:3px
 }

Body:
it looks like your javascript is correct. The reason why you are not seeing the spans is because they have no width, since they are inline elements.

Try with this CSS:

.redcard{
    display:inline-block;
    background-color:red;
    width:13px;
    height:20px;
    box-shadow: 3px 3px 1px #888888;
    border-radius:3px
}


问:
Rails How to pass params from controller to after_save inside model
I have a Rfq contoller i am creating new or updating existing Rfqs, when i create or update the object is saved, what i want is as i have number of quotes params i want to update the line_items table with the quotes in params[:quotes] in quote_price column after saving the Rfqs

i know its confusing, but who are ror-ish should have got some hint wat i want to ask.

答:
If you're trying to use the params hash in your model, you are violating principles of MVC. The model should stand alone with arguments. If you are trying to do the following:

```<code># controller
Model.foo

# model
def foo
  params[:bar].reverse!
end
</code>```

You should do the following instead:

```<code># controller
Model.foo(params[:bar])

# model
def foo(foobar)
  foobar.reverse!
end
</code>```

Body:
If you're trying to use the params hash in your model, you are violating principles of MVC. The model should stand alone with arguments. If you are trying to do the following:

# controller
Model.foo

# model
def foo
  params[:bar].reverse!
end

You should do the following instead:

# controller
Model.foo(params[:bar])

# model
def foo(foobar)
  foobar.reverse!
end


问:
Parse nested XML from URL
I'm currently working on a .NET 4.6 console application. I need to parse a nested XML from an URL and transform the XML into an object list.

The URL for the sample XML is the following:

https://www.w3schools.com/xml/cd_catalog.xml

The XML looks like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<CATALOG>
    <CD>
        <TITLE>Empire Burlesque</TITLE>
        <ARTIST>Bob Dylan</ARTIST>
        <COUNTRY>USA</COUNTRY>
        <COMPANY>Columbia</COMPANY>
        <PRICE>10.90</PRICE>
        <YEAR>1985</YEAR>
    </CD>
    <CD>
        <TITLE>Hide your heart</TITLE>
        <ARTIST>Bonnie Tyler</ARTIST>
        <COUNTRY>UK</COUNTRY>
        <COMPANY>CBS Records</COMPANY>
        <PRICE>9.90</PRICE>
        <YEAR>1988</YEAR>
    </CD>
</CATALOG>
</code>```

My corresponding C# classes look like this:

```<code>[XmlRoot(ElementName = "CATALOG")]
public class Catalog
{
    [XmlElement("CD")]
    List<Cd> Cds { get; set; }
}

[XmlRoot(ElementName = "CD")]
public class Cd
{
    [XmlElement("TITLE")]
    public string Title { get; set; }
    [XmlElement("ARTIST")]
    public string Artist { get; set; }
    [XmlElement("COUNTRY")]
    public string Country { get; set; }
    [XmlElement("COMPANY")]
    public string Company { get; set; }
    [XmlElement("PRICE")]
    public double Price { get; set; }
    [XmlElement("YEAR")]
    public int Year { get; set; }
}
</code>```

My program class looks like this:

```<code>class Program
{
    static void Main(string[] args)
    {
        Init();
    }

    public static void Init() {

        var url = "https://www.w3schools.com/xml/cd_catalog.xml";

        XmlDocument myXmlDocument = new XmlDocument();
        myXmlDocument.Load(url);

        var catalog = myXmlDocument.InnerXml.ToString();

        var result = Deserialize<Catalog>(catalog);
        // result is null :(

        Console.ReadKey();
    }

    public static T Deserialize<T>(string xmlText)
    {
        try
        {
            var stringReader = new StringReader(xmlText);
            var serializer = new XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(stringReader);
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}
</code>```

So far so good, my variable catalog consists out of an XML string, but somehow the XML doesn't get parsed correctly. I always get null as a return result. Perhaps it's because of my class definitions.

What do you think, do you have an idea on how to solve this issue? To retrieve an List<Cd> instead of null.

答:
The error is very subtle. You have done everything right, but you missed to add the public access qualifier in your Catalog class, on the list of Cd like so:

```<code>[XmlRoot(ElementName = "CATALOG")]
public class Catalog
{
    [XmlElement("CD")]
    public List<Cd> Cds { get; set; }
}
</code>```

Since the access qualifiers default to private, the deserializer is having a hard time finding the correct property to deserialize the XML into.

Title: Parse nested XML from URL

Body:
I'm currently working on a .NET 4.6 console application. I need to parse a nested XML from an URL and transform the XML into an object list.

The URL for the sample XML is the following:

https://www.w3schools.com/xml/cd_catalog.xml

The XML looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<CATALOG>
    <CD>
        <TITLE>Empire Burlesque</TITLE>
        <ARTIST>Bob Dylan</ARTIST>
        <COUNTRY>USA</COUNTRY>
        <COMPANY>Columbia</COMPANY>
        <PRICE>10.90</PRICE>
        <YEAR>1985</YEAR>
    </CD>
    <CD>
        <TITLE>Hide your heart</TITLE>
        <ARTIST>Bonnie Tyler</ARTIST>
        <COUNTRY>UK</COUNTRY>
        <COMPANY>CBS Records</COMPANY>
        <PRICE>9.90</PRICE>
        <YEAR>1988</YEAR>
    </CD>
</CATALOG>

My corresponding C# classes look like this:

[XmlRoot(ElementName = "CATALOG")]
public class Catalog
{
    [XmlElement("CD")]
    List<Cd> Cds { get; set; }
}

[XmlRoot(ElementName = "CD")]
public class Cd
{
    [XmlElement("TITLE")]
    public string Title { get; set; }
    [XmlElement("ARTIST")]
    public string Artist { get; set; }
    [XmlElement("COUNTRY")]
    public string Country { get; set; }
    [XmlElement("COMPANY")]
    public string Company { get; set; }
    [XmlElement("PRICE")]
    public double Price { get; set; }
    [XmlElement("YEAR")]
    public int Year { get; set; }
}

My program class looks like this:

class Program
{
    static void Main(string[] args)
    {
        Init();
    }

    public static void Init() {

        var url = "https://www.w3schools.com/xml/cd_catalog.xml";

        XmlDocument myXmlDocument = new XmlDocument();
        myXmlDocument.Load(url);

        var catalog = myXmlDocument.InnerXml.ToString();

        var result = Deserialize<Catalog>(catalog);
        // result is null :(

        Console.ReadKey();
    }

    public static T Deserialize<T>(string xmlText)
    {
        try
        {
            var stringReader = new StringReader(xmlText);
            var serializer = new XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(stringReader);
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}

So far so good, my variable catalog consists out of an XML string, but somehow the XML doesn't get parsed correctly. I always get null as a return result. Perhaps it's because of my class definitions.

What do you think, do you have an idea on how to solve this issue? To retrieve an List<Cd> instead of null.

Body:
The error is very subtle. You have done everything right, but you missed to add the public access qualifier in your Catalog class, on the list of Cd like so:

[XmlRoot(ElementName = "CATALOG")]
public class Catalog
{
    [XmlElement("CD")]
    public List<Cd> Cds { get; set; }
}

Since the access qualifiers default to private, the deserializer is having a hard time finding the correct property to deserialize the XML into.


问:
How to show divider between spinner items?
I using listviews and expandedviews that has dividers and I can set them but on spinner its looks like it is no divider between items.

Someone that has a idea of how to fix this?

答:
Based on @Talihawk answer, I made it work for specific spinner only. Instead of setting your activity theme, set the theme directly for the spinner view:

```<code><style name="MatchSpinnerStyle" parent="android:style/Widget.ListView.DropDown">
    <item name="android:divider">#123456</item>
    <item name="android:dividerHeight">1dp</item>
</style>

<style name="MatchSpinnerTheme" parent="AppTheme">
    <item name="android:dropDownListViewStyle">@style/MatchSpinnerStyle</item>
</style>
</code>```

and

```<code><android.support.v7.widget.AppCompatSpinner
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/MatchSpinnerTheme"/>
</code>```

Body:
Based on @Talihawk answer, I made it work for specific spinner only. Instead of setting your activity theme, set the theme directly for the spinner view:

<style name="MatchSpinnerStyle" parent="android:style/Widget.ListView.DropDown">
    <item name="android:divider">#123456</item>
    <item name="android:dividerHeight">1dp</item>
</style>

<style name="MatchSpinnerTheme" parent="AppTheme">
    <item name="android:dropDownListViewStyle">@style/MatchSpinnerStyle</item>
</style>

and

<android.support.v7.widget.AppCompatSpinner
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/MatchSpinnerTheme"/>


问:
OpenClover not Running - Error
I am trying to integrate OpenClover into my project.
I have a Java based webapp and I use maven
I have setup the plugin as follows

```<code>        <plugin>
            <groupId>org.openclover</groupId>
            <artifactId>clover-maven-plugin</artifactId>
            <version>4.2.0</version>
            <configuration>
                <targetPercentage>50%</targetPercentage>
            </configuration>
            <executions>
                <execution>
                    <phase>verify</phase>
                    <goals>
                        <goal>check</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
</code>```

When I run the following command

```<code>mvn clean test clover:aggregate clover:clover -Dsurefire.skip.tests=false;
</code>```

I get this error

```<code>[ERROR] Failed to execute goal org.openclover:clover-maven-plugin:4.2.0:setup (default-cli) on project fcservices-web: Execution default-cli of goal org.openclover:clover-maven-plugin:4.2.0:setup failed: Unable to load the mojo 'setup' (or one of its required components) from the plugin 'org.openclover:clover-maven-plugin:4.2.0': com.google.inject.ProvisionException: Guice provision errors:
[ERROR]
[ERROR] 1) No implementation for org.apache.maven.execution.MavenSession was bound.
[ERROR] while locating com.atlassian.maven.plugin.clover.CloverSetupMojo
[ERROR] at ClassRealm[plugin>org.openclover:clover-maven-plugin:4.2.0, parent: sun.misc.Launcher$AppClassLoader@55f96302]
[ERROR] while locating org.apache.maven.plugin.Mojo annotated with @com.google.inject.name.Named(value=org.openclover:clover-maven-plugin:4.2.0:setup)
[ERROR]
[ERROR] 1 error
[ERROR] role: org.apache.maven.plugin.Mojo
[ERROR] roleHint: org.openclover:clover-maven-plugin:4.2.0:setup
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginContainerException
</code>```

Any ideas what is up here?

Thank you
Damien

答: Going to the latest version of Maven (3.5.2) resolved this issue</p>

Title: OpenClover not Running - Error

Body:
I am trying to integrate OpenClover into my project.
I have a Java based webapp and I use maven
I have setup the plugin as follows

        <plugin>
            <groupId>org.openclover</groupId>
            <artifactId>clover-maven-plugin</artifactId>
            <version>4.2.0</version>
            <configuration>
                <targetPercentage>50%</targetPercentage>
            </configuration>
            <executions>
                <execution>
                    <phase>verify</phase>
                    <goals>
                        <goal>check</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

When I run the following command

mvn clean test clover:aggregate clover:clover -Dsurefire.skip.tests=false;

I get this error

[ERROR] Failed to execute goal org.openclover:clover-maven-plugin:4.2.0:setup (default-cli) on project fcservices-web: Execution default-cli of goal org.openclover:clover-maven-plugin:4.2.0:setup failed: Unable to load the mojo 'setup' (or one of its required components) from the plugin 'org.openclover:clover-maven-plugin:4.2.0': com.google.inject.ProvisionException: Guice provision errors:
[ERROR]
[ERROR] 1) No implementation for org.apache.maven.execution.MavenSession was bound.
[ERROR] while locating com.atlassian.maven.plugin.clover.CloverSetupMojo
[ERROR] at ClassRealm[plugin>org.openclover:clover-maven-plugin:4.2.0, parent: sun.misc.Launcher$AppClassLoader@55f96302]
[ERROR] while locating org.apache.maven.plugin.Mojo annotated with @com.google.inject.name.Named(value=org.openclover:clover-maven-plugin:4.2.0:setup)
[ERROR]
[ERROR] 1 error
[ERROR] role: org.apache.maven.plugin.Mojo
[ERROR] roleHint: org.openclover:clover-maven-plugin:4.2.0:setup
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginContainerException

Any ideas what is up here?

Thank you
Damien


问:
Default constructor with interface injection along with Parameterized Constructor in same class
```<code>        public class xyz
          {

            private readonly ICheck _checker;

            private readonly IChecker checker;.

            public xyz()
            {
            _checker = checker.Create<xyz>(); //default constructor initialization
            };

            public xyz(string value)
            {
            validateIt(value);//parameter Constructor
            <!--do something-->
            }

            private static void validateIt(string value){
            var msg= "Is not Valid";   //static method which will log the msg
            _checker.log(msg);
            }

        }
</code>```

//Now the problem is that default constructor is not working(C# code)

 //1.checker is initializing as null

 //2. unable to get reference of _checker in static method(even if problem 1 is resolved)

答:
First, nitpicking:

A default constructor is the constructor provided by the c# compiler when you don't specify a constructor in your class code.

You can't specify a default constructor in your class code. you can specify a constructor that doesn't take any parameters, but it's not going to be "default" anymore.

Once you have specified a constructor, that's the only constructor you have, unless you specify other constructors as well.

Second, if you are initializing your class with one constructor, you don't automatically use other constructors as well. For that you need to use constructor chaining - call one constructor from the other. In your case:

```<code>public xyz(string value) : this()
{
    // constructor logic goes here
}
</code>```

Third, private readonly _checker; will cause a compilation error - you must specify the type of the private member (and in any case, it's defined correctly in the next code line)

Fourth, You can't access instance members from a static member, unless you have a reference to an instance. If you want to use the _checker as a static member, it needs to be defined as static. otherwise, you either need to pass an instance of xyz to your static method or simply make it an instance method:

```<code>public class xyz
{
    private readonly IChecker checker;

    public xyz()
    {
        // default constructor initialization
        _checker = checker.Create<xyz>();
    };

    public xyz(string value) : this()
    {
        // parameterized Constructor
        validateIt(value);
        //do something
    }

    private void validateIt(string value)
    {
        var msg= "Is not Valid";
        _checker.log(msg);
    }
}
</code>```

Body:
        public class xyz
          {

            private readonly ICheck _checker;

            private readonly IChecker checker;.

            public xyz()
            {
            _checker = checker.Create<xyz>(); //default constructor initialization
            };

            public xyz(string value)
            {
            validateIt(value);//parameter Constructor

            }

            private static void validateIt(string value){
            var msg= "Is not Valid";   //static method which will log the msg
            _checker.log(msg);
            }

        }

//Now the problem is that default constructor is not working(C# code)

 //1.checker is initializing as null

 //2. unable to get reference of _checker in static method(even if problem 1 is resolved)

Body:
First, nitpicking:

A default constructor is the constructor provided by the c# compiler when you don't specify a constructor in your class code.

You can't specify a default constructor in your class code. you can specify a constructor that doesn't take any parameters, but it's not going to be "default" anymore.

Once you have specified a constructor, that's the only constructor you have, unless you specify other constructors as well.

Second, if you are initializing your class with one constructor, you don't automatically use other constructors as well. For that you need to use constructor chaining - call one constructor from the other. In your case:

public xyz(string value) : this()
{
    // constructor logic goes here
}

Third, private readonly _checker; will cause a compilation error - you must specify the type of the private member (and in any case, it's defined correctly in the next code line)

Fourth, You can't access instance members from a static member, unless you have a reference to an instance. If you want to use the _checker as a static member, it needs to be defined as static. otherwise, you either need to pass an instance of xyz to your static method or simply make it an instance method:

public class xyz
{
    private readonly IChecker checker;

    public xyz()
    {
        // default constructor initialization
        _checker = checker.Create<xyz>();
    };

    public xyz(string value) : this()
    {
        // parameterized Constructor
        validateIt(value);
        //do something
    }

    private void validateIt(string value)
    {
        var msg= "Is not Valid";
        _checker.log(msg);
    }
}


问:
How to make my h1 in the center of the image background without using absolute position?

/*General*/
@import url('https://fonts.googleapis.com/css?family=Oxygen');

.wrapper {
    max-width: 630px;
    margin: 0 auto;
}

/*Header*/
#header .navbar .navbar-header a {
    color: white;
    font-size: 25px;
    font-family: 'Oxygen', sans-serif;
}
#header .navbar-inverse {
    background-color: #2C3E50;
    border-color: #2C3E50;
}
#header .navbar {
    border-radius: 0;
}
#header .navbar-nav > li > a {
    color:white;
}
#header .navbar {
    margin-bottom: 0;
}
.nav.navbar-nav.navbar-right li a {
    color: white;
}

/*Content*/
#content .content-content .responsive-image {
    width: 100%;
    background-size: 100% 100%;
    z-index:0;
}
#content .content-content h1 {
    font-family: 'Open Sans', sans-serif;
    color: #2c3e50;
    font-size: 50px;
    font-weight: bold;
    z-index: 2;
    text-align: center;
}

/*Footer*/

/*Responsiveness*/

/*Desktop*/
@media screen and (min-width: 992px)
{
    #content .content-content .responsive-image {
        background-image: url('https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg');
    }
}

/*Tablet*/
@media screen and (min-width: 768px) and (max-width: 991px)
{
    #content .content-content .responsive-image {
        background-image: url('https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg');
    }
}

/*Mobile*/
@media screen and (max-width: 767px)
{
    #content .content-content .responsive-image {
        background-image: url('https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg');
    }
}

/*Custom*/
@media screen and (max-width: 574px)
{
    #content .content-content .responsive-image {
        background-image: url('https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg');height:250px;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <title>Magic Gate</title>
    <link rel="stylesheet" type="text/css" href="Custom.css">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
    <div id="header">
        <nav class="navbar navbar-inverse">
            <div class="container-fluid">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    Magic Gate
                </div>
                <div class="collapse navbar-collapse" id="myNavbar">
                    <ul class="nav navbar-nav navbar-right">
                        <li>
                            Play
                        </li>
                        <li>
                            Log Out
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
    </div>
    <div id="content">
        <div class="content-content">
            <img src="https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg" class="responsive-image">
            <div class="wrapper">
                <h1>Welcome to Magic Gate</h1>
            </div>
        </div>
    </div>
    <div id="footer">
    </div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</html></code>```

I don't want to use absolute positioning because it disrupts the centering of objects/controls at the center of the banner. Can you help me with this one without also changing the img to a div background unless it will be responsive, since everything is responsive. My goal is to center the h1 text at the middle of the banner.

答:
Here like you ask, i add position:relative; top:-250px; to h1 . But it is an ugly practice and a realy bad code. position:absolute; and transform:transle() much more better

/*General*/
@import url('https://fonts.googleapis.com/css?family=Oxygen');
.wrapper {
    max-width: 630px;
    margin: 0 auto;
}

/*Header*/
#header .navbar .navbar-header a{color: white;font-size: 25px;font-family: 'Oxygen', sans-serif;}
#header .navbar-inverse {background-color: #2C3E50;border-color: #2C3E50;}
#header .navbar {border-radius: 0;}
#header .navbar-nav > li > a {color:white;}
#header .navbar {margin-bottom: 0;}
.nav.navbar-nav.navbar-right li a {color: white;}

/*Content*/

#content .content-content .responsive-image{width: 100%;background-size: 100% 100%;z-index:0;}
#content .content-content h1{font-family: 'Open Sans', sans-serif;color: #2c3e50;font-size: 50px;font-weight: bold;z-index: 2;text-align: center;position:relative;top:-250px;}

/*Footer*/

/*Responsiveness*/

/*Desktop*/
@media screen and (min-width: 992px)
{
#content .content-content .responsive-image{background-image: url('https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg');}
}

/*Tablet*/
@media screen and (min-width: 768px) and (max-width: 991px)
{
#content .content-content .responsive-image{background-image: url('https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg');}
}

/*Mobile*/
@media screen and (max-width: 767px)
{
#content .content-content .responsive-image{background-image: url('https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg');}
}

/*Custom*/
@media screen and (max-width: 574px)
{
#content .content-content .responsive-image{background-image: url('https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg');height:250px;}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
 <title>Magic Gate</title>
 <link rel="stylesheet" type="text/css" href="Custom.css">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
 <div id="header">
  <nav class="navbar navbar-inverse">
   <div class="container-fluid">
       <div class="navbar-header">
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        Magic Gate
       </div>
       <div class="collapse navbar-collapse" id="myNavbar">
        <ul class="nav navbar-nav navbar-right">
            <li>Play</li>
            <li>Log Out</li>
          </ul>
       </div>
   </div>
  </nav>
 </div>
 <div id="content">
  <div class="content-content">
   <img src="https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg" class="responsive-image">
   <div class="wrapper">
    <h1>Welcome to Magic Gate</h1>
   </div>
  </div>
 </div>
 <div id="footer">
 </div>
</body>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</html></code>```

Body:
/*General*/
@import url('https://fonts.googleapis.com/css?family=Oxygen');

.wrapper {
    max-width: 630px;
    margin: 0 auto;
}

/*Header*/
#header .navbar .navbar-header a {
    color: white;
    font-size: 25px;
    font-family: 'Oxygen', sans-serif;
}
#header .navbar-inverse {
    background-color: #2C3E50;
    border-color: #2C3E50;
}
#header .navbar {
    border-radius: 0;
}
#header .navbar-nav > li > a {
    color:white;
}
#header .navbar {
    margin-bottom: 0;
}
.nav.navbar-nav.navbar-right li a {
    color: white;
}

/*Content*/
#content .content-content .responsive-image {
    width: 100%;
    background-size: 100% 100%;
    z-index:0;
}
#content .content-content h1 {
    font-family: 'Open Sans', sans-serif;
    color: #2c3e50;
    font-size: 50px;
    font-weight: bold;
    z-index: 2;
    text-align: center;
}

/*Footer*/

/*Responsiveness*/

/*Desktop*/
@media screen and (min-width: 992px)
{
    #content .content-content .responsive-image {
        background-image: url('https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg');
    }
}

/*Tablet*/
@media screen and (min-width: 768px) and (max-width: 991px)
{
    #content .content-content .responsive-image {
        background-image: url('https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg');
    }
}

/*Mobile*/
@media screen and (max-width: 767px)
{
    #content .content-content .responsive-image {
        background-image: url('https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg');
    }
}

/*Custom*/
@media screen and (max-width: 574px)
{
    #content .content-content .responsive-image {
        background-image: url('https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg');height:250px;
    }
}

<!DOCTYPE html>

    <title>Magic Gate</title>
    <link rel="stylesheet" type="text/css" href="Custom.css">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

                    </button>
                    Magic Gate

                            Play

                            Log Out

Welcome to Magic Gate

I don't want to use absolute positioning because it disrupts the centering of objects/controls at the center of the banner. Can you help me with this one without also changing the img to a div background unless it will be responsive, since everything is responsive. My goal is to center the h1 text at the middle of the banner.

Body:
Here like you ask, i add position:relative; top:-250px; to h1 . But it is an ugly practice and a realy bad code. position:absolute; and transform:transle() much more better

/*General*/
@import url('https://fonts.googleapis.com/css?family=Oxygen');
.wrapper {
    max-width: 630px;
    margin: 0 auto;
}

/*Header*/
#header .navbar .navbar-header a{color: white;font-size: 25px;font-family: 'Oxygen', sans-serif;}
#header .navbar-inverse {background-color: #2C3E50;border-color: #2C3E50;}
#header .navbar {border-radius: 0;}
#header .navbar-nav > li > a {color:white;}
#header .navbar {margin-bottom: 0;}
.nav.navbar-nav.navbar-right li a {color: white;}

/*Content*/

#content .content-content .responsive-image{width: 100%;background-size: 100% 100%;z-index:0;}
#content .content-content h1{font-family: 'Open Sans', sans-serif;color: #2c3e50;font-size: 50px;font-weight: bold;z-index: 2;text-align: center;position:relative;top:-250px;}

/*Footer*/

/*Responsiveness*/

/*Desktop*/
@media screen and (min-width: 992px)
{
#content .content-content .responsive-image{background-image: url('https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg');}
}

/*Tablet*/
@media screen and (min-width: 768px) and (max-width: 991px)
{
#content .content-content .responsive-image{background-image: url('https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg');}
}

/*Mobile*/
@media screen and (max-width: 767px)
{
#content .content-content .responsive-image{background-image: url('https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg');}
}

/*Custom*/
@media screen and (max-width: 574px)
{
#content .content-content .responsive-image{background-image: url('https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg');height:250px;}
}

<!DOCTYPE html>
<html>
<head>
 <title>Magic Gate</title>
 <link rel="stylesheet" type="text/css" href="Custom.css">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
 <div id="header">
  <nav class="navbar navbar-inverse">
   <div class="container-fluid">
       <div class="navbar-header">
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="#">Magic Gate</a>
       </div>
       <div class="collapse navbar-collapse" id="myNavbar">
        <ul class="nav navbar-nav navbar-right">
            <li><a href="#">Play</a></li>
            <li><a href="#">Log Out</a></li>
          </ul>
       </div>
   </div>
  </nav>
 </div>
 <div id="content">
  <div class="content-content">
   <img src="https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg" class="responsive-image">
   <div class="wrapper">
    <h1>Welcome to Magic Gate</h1>
   </div>
  </div>
 </div>
 <div id="footer">
 </div>
</body>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</html>


问:
how to retrieve single data from the Firebase database
I need to retrieve single data from Firebase database. Where I have a list view contains id list. Whenever user clicks the listview i need to display the respective value field.

check screen shot of db

here is the code.

```<code> l1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                        r2= FirebaseDatabase.getInstance().getReference().child("type").child("discord").child("ad");

                        r2.addChildEventListener(new ChildEventListener() {
                        @Override
                        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                            String name1;
                            name1=dataSnapshot.getValue().toString();
                            Toast.makeText(Main2Activity.this, name1, Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                        }

                        @Override
                        public void onChildRemoved(DataSnapshot dataSnapshot) {

                        }

                        @Override
                        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });

                }
            });
</code>```

I need to execute the query

select value from table_name where id="01" ;

答:
You need to change this line of code:

```<code>name1=dataSnapshot.getValue().toString();
</code>```

with

```<code>name1=dataSnapshot.child("01").getValue(String.class);
</code>```

Body:
I need to retrieve single data from Firebase database. Where I have a list view contains id list. Whenever user clicks the listview i need to display the respective value field.

check screen shot of db

here is the code.

 l1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                        r2= FirebaseDatabase.getInstance().getReference().child("type").child("discord").child("ad");

                        r2.addChildEventListener(new ChildEventListener() {
                        @Override
                        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                            String name1;
                            name1=dataSnapshot.getValue().toString();
                            Toast.makeText(Main2Activity.this, name1, Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                        }

                        @Override
                        public void onChildRemoved(DataSnapshot dataSnapshot) {

                        }

                        @Override
                        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });

                }
            });

I need to execute the query

select value from table_name where id="01" ;

Body:
You need to change this line of code:

name1=dataSnapshot.getValue().toString();

with

name1=dataSnapshot.child("01").getValue(String.class);