问:
Page doesn't open on clicking in side menu - ionic 2 app
I am unable to open a page upon clicking it in side menu.

This is my app.component.ts:

```<code>this.pages = [
                { title: 'NFC Page', component: NfcPage, note: 'NFC Page' },
                { title: 'Student Details', component: StudentDetails, note: 'Student Details' },
    ];
</code>```

This is my app.module.ts:

```<code>@NgModule({
  declarations: [
    StudentDetails,
    NfcPage,
],
entryComponents: [
    StudentDetails,
    NfcPage,
  ],
</code>```

This is my nfc.ts page:

```<code> import {Component} from '@angular/core';
    import {IonicPage, NavController, NavParams} from 'ionic-angular';
    import {NFC, Ndef} from '@ionic-native/nfc';

    @IonicPage()
    @Component({
        selector: 'page-nfc',
        templateUrl: 'nfc.html',
    })
    export class NfcPage {

        constructor(public navCtrl: NavController,
                    public navParams: NavParams,
                    private nfc: NFC,
                    private ndef: Ndef) {
}
}
</code>```

This is my nfc.html page:

```<code><ion-header>
    <ion-navbar>
        <button ion-button menuToggle>
            <ion-icon name="menu"></ion-icon>
        </button>
        <ion-title>NFCPage</ion-title>
    </ion-navbar>
</ion-header>

<ion-content padding>
    <p>NFC Page!</p>
</ion-content>
</code>```

Student details page opens fine but when I click "Nfc page", nothing happens.

答:
for open the page through the side menu you need to make that page as a rootpage when you click on the side menu option.You may find the below code:-

app.html:

```<code><ion-menu id="myMenu" [content]="mycontent" >
    <ion-content>
        <ion-list>
            <ion-item  ion-item small menuClose  (click)="nav.setRoot(pages.nfc)">
                <ion-icon name="home" item-left menuClose ></ion-icon> NFC
            </ion-item >
                <ion-item small menuClose  (click)="nav.setRoot(pages.std_detils)">
                <ion-icon ios="ios-contact" md="ios-contact" item-left ></ion-icon> Student Details
            </ion-item>
        </ion-list>
    </ion-content>
</ion-menu>

<ion-nav #mycontent [root]="rootPage"></ion-nav>
</code>```

app.component.ts:

```<code>this.rootPage = NfcPage;
  this.pages = {
        "nfc": NfcPage,
        "std_detils": StudentDetails,

      };
</code>```

Body:
I am unable to open a page upon clicking it in side menu.

This is my app.component.ts:

this.pages = [
                { title: 'NFC Page', component: NfcPage, note: 'NFC Page' },
                { title: 'Student Details', component: StudentDetails, note: 'Student Details' },
    ];

This is my app.module.ts:

@NgModule({
  declarations: [
    StudentDetails,
    NfcPage,
],
entryComponents: [
    StudentDetails,
    NfcPage,
  ],

This is my nfc.ts page:

 import {Component} from '@angular/core';
    import {IonicPage, NavController, NavParams} from 'ionic-angular';
    import {NFC, Ndef} from '@ionic-native/nfc';

    @IonicPage()
    @Component({
        selector: 'page-nfc',
        templateUrl: 'nfc.html',
    })
    export class NfcPage {

        constructor(public navCtrl: NavController,
                    public navParams: NavParams,
                    private nfc: NFC,
                    private ndef: Ndef) {
}
}

This is my nfc.html page:

<ion-header>
    <ion-navbar>
        <button ion-button menuToggle>
            <ion-icon name="menu"></ion-icon>
        </button>
        <ion-title>NFCPage</ion-title>
    </ion-navbar>
</ion-header>

<ion-content padding>

NFC Page!

</ion-content>

Student details page opens fine but when I click "Nfc page", nothing happens.

Body:
for open the page through the side menu you need to make that page as a rootpage when you click on the side menu option.You may find the below code:-

app.html:

<ion-menu id="myMenu" [content]="mycontent" >
    <ion-content>
        <ion-list>
            <ion-item  ion-item small menuClose  (click)="nav.setRoot(pages.nfc)">
                <ion-icon name="home" item-left menuClose ></ion-icon> NFC
            </ion-item >
                <ion-item small menuClose  (click)="nav.setRoot(pages.std_detils)">
                <ion-icon ios="ios-contact" md="ios-contact" item-left ></ion-icon> Student Details
            </ion-item>
        </ion-list>
    </ion-content>
</ion-menu>

<ion-nav #mycontent [root]="rootPage"></ion-nav>

app.component.ts:

this.rootPage = NfcPage;
  this.pages = {
        "nfc": NfcPage,
        "std_detils": StudentDetails,

      };


来源: stackexchange

问:
Way to compare index of 2 lists?
Hi guys how do I compare index of 2 lists (by linking them together)

```<code>a = [1,2,3,4]
b = ["a","b","c","d"]
</code>```

For exammple, let's say I want to print a value from b after inputing a value from a into another variable, how do I go about doing that where output generated is for examples : a and 1
sorry for my bad english

答:
If you are trying to match the variables:

```<code>>>> data = dict(zip(b,a))
>>> data['a']
1
>>> for k,v in data.items():
...     print k,v
</code>```

Maybe you are looking for dictionaries, in that case you should have your data defined immediately instead of two arrays:

```<code>data = {'a': 1, 'c': 3, 'b': 2, 'd': 4}
</code>```

Where you can still get two distinct arrays:

```<code>>>> data.keys()
['a','c','b','d']

>>> data.values()
[1,3,2,4]
</code>```

Edit:

Since you are also looking a way to start with the value input and keeping the arrays:

```<code>y=[1,2,3,4]
x=['a','b','c','d']

value = int(input("Enter a value:"))

try:
    y_index = y.index(value)
    print(x[y.index(value)])
except Exception as e:
    print("not found")
</code>```

ContentLicense: CC BY-SA 3.0

Title: Way to compare index of 2 lists?

Body:
Hi guys how do I compare index of 2 lists (by linking them together)

a = [1,2,3,4]
b = ["a","b","c","d"]

For exammple, let's say I want to print a value from b after inputing a value from a into another variable, how do I go about doing that where output generated is for examples : a and 1
sorry for my bad english

Body:
If you are trying to match the variables:

>>> data = dict(zip(b,a))
>>> data['a']
1
>>> for k,v in data.items():
...     print k,v

Maybe you are looking for dictionaries, in that case you should have your data defined immediately instead of two arrays:

data = {'a': 1, 'c': 3, 'b': 2, 'd': 4}

Where you can still get two distinct arrays:

>>> data.keys()
['a','c','b','d']

>>> data.values()
[1,3,2,4]

Edit:

Since you are also looking a way to start with the value input and keeping the arrays:

y=[1,2,3,4]
x=['a','b','c','d']

value = int(input("Enter a value:"))

try:
    y_index = y.index(value)
    print(x[y.index(value)])
except Exception as e:
    print("not found")


问:
Parenthesis/Brackets Matching using Stack algorithm
For example if the parenthesis/brackets is matching in the following:

```<code>({})
(()){}()
()
</code>```

and so on but if the parenthesis/brackets is not matching it should return false, eg:

```<code>{}
({}(
){})
(()
</code>```

and so on. Can you please check this code?

public static boolean isParenthesisMatch(String str) {
    Stack<Character> stack = new Stack<Character>();

    char c;
    for(int i=0; i < str.length(); i++) {
        c = str.charAt(i);

        if(c == '{')
            return false;

        if(c == '(')
            stack.push(c);

        if(c == '{') {
            stack.push(c);
            if(c == '}')
                if(stack.empty())
                    return false;
                else if(stack.peek() == '{')
                    stack.pop();
        }
        else if(c == ')')
            if(stack.empty())
                return false;
            else if(stack.peek() == '(')
                    stack.pop();
                else
                    return false;
        }
        return stack.empty();
}

public static void main(String[] args) {
    String str = "({})";
    System.out.println(Weekly12.parenthesisOtherMatching(str));
}
```

答:
```<code>public static bool IsBalanced(string input)
    {
        Dictionary<char, char> bracketPairs = new Dictionary<char, char>() {
        { '(', ')' },
        { '{', '}' },
        { '[', ']' },
        { '<', '>' }
    };

        Stack<char> brackets = new Stack<char>();

        try
        {
            // Iterate through each character in the input string
            foreach (char c in input)
            {
                // check if the character is one of the 'opening' brackets
                if (bracketPairs.Keys.Contains(c))
                {
                    // if yes, push to stack
                    brackets.Push(c);
                }
                else
                    // check if the character is one of the 'closing' brackets
                    if (bracketPairs.Values.Contains(c))
                    {
                        // check if the closing bracket matches the 'latest' 'opening' bracket
                        if (c == bracketPairs[brackets.First()])
                        {
                            brackets.Pop();
                        }
                        else
                            // if not, its an unbalanced string
                            return false;
                    }
                    else
                        // continue looking
                        continue;
            }
        }
        catch
        {
            // an exception will be caught in case a closing bracket is found,
            // before any opening bracket.
            // that implies, the string is not balanced. Return false
            return false;
        }

        // Ensure all brackets are closed
        return brackets.Count() == 0 ? true : false;
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
For example if the parenthesis/brackets is matching in the following:

({})
(()){}()
()

and so on but if the parenthesis/brackets is not matching it should return false, eg:

{}
({}(
){})
(()

and so on. Can you please check this code?

public static boolean isParenthesisMatch(String str) {
    Stack<Character> stack = new Stack<Character>();

    char c;
    for(int i=0; i < str.length(); i++) {
        c = str.charAt(i);

        if(c == '{')
            return false;

        if(c == '(')
            stack.push(c);

        if(c == '{') {
            stack.push(c);
            if(c == '}')
                if(stack.empty())
                    return false;
                else if(stack.peek() == '{')
                    stack.pop();
        }
        else if(c == ')')
            if(stack.empty())
                return false;
            else if(stack.peek() == '(')
                    stack.pop();
                else
                    return false;
        }
        return stack.empty();
}

public static void main(String[] args) {
    String str = "({})";
    System.out.println(Weekly12.parenthesisOtherMatching(str));
}


问:
Set video tag as background image and match the content
Here's my code:

```<code>.video-bg-container {
    position: relative;
    z-index: 9;
}

.video-bg {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    /*z-index: 9;*/
}

.video-bg-boxes {
    position: relative;
    /*position: absolute;*/
    /*top: 0;*/
    /*left: 0;*/
    /*right: 0;*/
    /*bottom: 0;*/
    padding: 70px 10%;
    z-index: 10;
}

.video-bg-boxes .blue-box {
    color: #ffffff;
    background-color: #0091cf!important;
    padding: 30px 30px 80px 30px;
    font-size: 16px;
    cursor: pointer;
    margin-bottom: 30px;
}
</code>```

Read full + demo at: https://jsfiddle.net/lanford/aeqx6ubp/4/

I want the video tag acts like an background image with back ground size cover: the width is always 100% but the height scale with the height of the contents inside and always responsive. Is there anyway to achive it by jquery or CSS?

答:
You can use object-fit get it

Update css

```<code>video {
  object-fit: cover;
  height:100vh;
  min-height:100%;
}
    body, html {
    margin: 0px;
    padding: 0px;
    height:100%;
    min-height:100%;
}
</code>```

    body, html {
    margin: 0px;
    padding: 0px;
}

video {
  object-fit: cover;
}

.video-module {
  margin-bottom: 0px;
}

.video-bg-container {
  position: relative;
  z-index: 9;
}

.video-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  /*z-index: 9;*/
}

.video-bg-boxes {
  position: relative;
  /*position: absolute;*/
  /*top: 0;*/
  /*left: 0;*/
  /*right: 0;*/
  /*bottom: 0;*/
  padding: 70px 10%;
  z-index: 10;
}

.video-bg-boxes .blue-box {
  color: #ffffff;
  background-color: #0091cf!important;
  padding: 30px 30px 80px 30px;
  font-size: 16px;
  cursor: pointer;
  margin-bottom: 30px;
}

.video-bg-boxes .blue-box strong {
  font-size: 30px;
  color: #ffffff;
  text-transform: uppercase;
}

.video-bg-boxes .blue-box:hover {
  background-color: #E4E1E0!important;
  color: #4C4145!important;
}

.video-bg-boxes .blue-box:hover strong {
  color: #0091CF!important;
}

.video-bg-boxes .blue-box a {
  text-decoration: none;
  color: #ffffff;
}

.video-bg-boxes .blue-box:hover a {
  color: #0091CF;
}

.video-bg-boxes .grey-box {
  border: none!important;
  padding: 30px 30px 80px 30px;
  background: url("https://cdn2.hubspot.net/hubfs/3372283/axon-active/img/p1/blue-arrow-ico.png");
  background-position: center 90%;
  background-repeat: no-repeat;
  font-size: 16px;
  cursor: pointer;
  margin-bottom: 30px;
  background-color: #E4E1E0;
  color: #4C4145!important;
}

.video-bg-boxes .grey-box strong {
  font-size: 30px;
  color: #0091CF;
  text-transform: uppercase;
}

.video-bg-boxes .grey-box:hover {
  background: url("https://cdn2.hubspot.net/hubfs/3372283/axon-active/img/p1/arrow-ico.png")!important;
  background-position: center 90%!important;
  background-repeat: no-repeat!important;
  background-color: #0091cf!important;
  color: #ffffff!important;
}

.video-bg-boxes .grey-box:hover strong {
  color: #ffffff!important;
}

.video-bg-boxes .grey-box a {
  text-decoration: none;
  color: #4C4145;
}

.video-bg-boxes .grey-box:hover a {
  color: #ffffff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="video-module">
  <div class="video-bg-container">
    <div class="video-bg">
      <video autoplay="autoplay" loop="loop" controls="controls" width="100%" height="100%">
            <source src="https://cdn2.hubspot.net/hubfs/3372283/axon-active/img/p1/VerseQuence%20-%20Wilt%20(VOEZ%20Official%20Soundtrack)%20-%20YouTube.mp4?t=1496825800724" type="video/mp4">
      </video>
    </div>

    <div class="video-bg-boxes">
      <div class="blue-box">
        <div style="text-align: center;"><strong>Title</strong></div>
        <div style="text-align: center;"> </div>
        <div style="text-align: center;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed condimentum enim eu finibus tincidunt. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Praesent eget neque scelerisque, molestie turpis sed,
          tristique turpis. Proin placerat pretium libero, at pellentesque lorem condimentum eu.</div>
      </div>

      <div class="blue-box">
        <div style="text-align: center;"><strong>Title</strong></div>
        <div style="text-align: center;"> </div>
        <div style="text-align: center;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed condimentum enim eu finibus tincidunt. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Praesent eget neque scelerisque, molestie turpis sed,
          tristique turpis. Proin placerat pretium libero, at pellentesque lorem condimentum eu.</div>
      </div>

      <div class="blue-box">
        <div style="text-align: center;"><strong>Title</strong></div>
        <div style="text-align: center;"> </div>
        <div style="text-align: center;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed condimentum enim eu finibus tincidunt. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Praesent eget neque scelerisque, molestie turpis sed,
          tristique turpis. Proin placerat pretium libero, at pellentesque lorem condimentum eu.</div>
      </div>

    </div></code>```

Body:
Here's my code:

.video-bg-container {
    position: relative;
    z-index: 9;
}

.video-bg {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    /*z-index: 9;*/
}

.video-bg-boxes {
    position: relative;
    /*position: absolute;*/
    /*top: 0;*/
    /*left: 0;*/
    /*right: 0;*/
    /*bottom: 0;*/
    padding: 70px 10%;
    z-index: 10;
}

.video-bg-boxes .blue-box {
    color: #ffffff;
    background-color: #0091cf!important;
    padding: 30px 30px 80px 30px;
    font-size: 16px;
    cursor: pointer;
    margin-bottom: 30px;
}

Read full + demo at: https://jsfiddle.net/lanford/aeqx6ubp/4/

I want the video tag acts like an background image with back ground size cover: the width is always 100% but the height scale with the height of the contents inside and always responsive. Is there anyway to achive it by jquery or CSS?

Body:
You can use object-fit get it

Update css

video {
  object-fit: cover;
  height:100vh;
  min-height:100%;
}
    body, html {
    margin: 0px;
    padding: 0px;
    height:100%;
    min-height:100%;
}

    body, html {
    margin: 0px;
    padding: 0px;
}

video {
  object-fit: cover;
}

.video-module {
  margin-bottom: 0px;
}

.video-bg-container {
  position: relative;
  z-index: 9;
}

.video-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  /*z-index: 9;*/
}

.video-bg-boxes {
  position: relative;
  /*position: absolute;*/
  /*top: 0;*/
  /*left: 0;*/
  /*right: 0;*/
  /*bottom: 0;*/
  padding: 70px 10%;
  z-index: 10;
}

.video-bg-boxes .blue-box {
  color: #ffffff;
  background-color: #0091cf!important;
  padding: 30px 30px 80px 30px;
  font-size: 16px;
  cursor: pointer;
  margin-bottom: 30px;
}

.video-bg-boxes .blue-box strong {
  font-size: 30px;
  color: #ffffff;
  text-transform: uppercase;
}

.video-bg-boxes .blue-box:hover {
  background-color: #E4E1E0!important;
  color: #4C4145!important;
}

.video-bg-boxes .blue-box:hover strong {
  color: #0091CF!important;
}

.video-bg-boxes .blue-box a {
  text-decoration: none;
  color: #ffffff;
}

.video-bg-boxes .blue-box:hover a {
  color: #0091CF;
}

.video-bg-boxes .grey-box {
  border: none!important;
  padding: 30px 30px 80px 30px;
  background: url("https://cdn2.hubspot.net/hubfs/3372283/axon-active/img/p1/blue-arrow-ico.png");
  background-position: center 90%;
  background-repeat: no-repeat;
  font-size: 16px;
  cursor: pointer;
  margin-bottom: 30px;
  background-color: #E4E1E0;
  color: #4C4145!important;
}

.video-bg-boxes .grey-box strong {
  font-size: 30px;
  color: #0091CF;
  text-transform: uppercase;
}

.video-bg-boxes .grey-box:hover {
  background: url("https://cdn2.hubspot.net/hubfs/3372283/axon-active/img/p1/arrow-ico.png")!important;
  background-position: center 90%!important;
  background-repeat: no-repeat!important;
  background-color: #0091cf!important;
  color: #ffffff!important;
}

.video-bg-boxes .grey-box:hover strong {
  color: #ffffff!important;
}

.video-bg-boxes .grey-box a {
  text-decoration: none;
  color: #4C4145;
}

.video-bg-boxes .grey-box:hover a {
  color: #ffffff;
}

<div class="video-module">
  <div class="video-bg-container">
    <div class="video-bg">
      <video autoplay="autoplay" loop="loop" controls="controls" width="100%" height="100%">
            <source src="https://cdn2.hubspot.net/hubfs/3372283/axon-active/img/p1/VerseQuence%20-%20Wilt%20(VOEZ%20Official%20Soundtrack)%20-%20YouTube.mp4?t=1496825800724" type="video/mp4">
      </video>
    </div>

    <div class="video-bg-boxes">
      <div class="blue-box">
        <div style="text-align: center;"><strong>Title</strong></div>
        <div style="text-align: center;">&nbsp;</div>
        <div style="text-align: center;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed condimentum enim eu finibus tincidunt. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Praesent eget neque scelerisque, molestie turpis sed,
          tristique turpis. Proin placerat pretium libero, at pellentesque lorem condimentum eu.</div>
      </div>

      <div class="blue-box">
        <div style="text-align: center;"><strong>Title</strong></div>
        <div style="text-align: center;">&nbsp;</div>
        <div style="text-align: center;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed condimentum enim eu finibus tincidunt. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Praesent eget neque scelerisque, molestie turpis sed,
          tristique turpis. Proin placerat pretium libero, at pellentesque lorem condimentum eu.</div>
      </div>

      <div class="blue-box">
        <div style="text-align: center;"><strong>Title</strong></div>
        <div style="text-align: center;">&nbsp;</div>
        <div style="text-align: center;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed condimentum enim eu finibus tincidunt. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Praesent eget neque scelerisque, molestie turpis sed,
          tristique turpis. Proin placerat pretium libero, at pellentesque lorem condimentum eu.</div>
      </div>

    </div>


问:
Python - pptx - Text Reads
Code to import data from table and text frame:

```<code> pres = Presentation(ppt_file)

    for slide in pres.slides:
        for shape in slide.shapes:
            if(shape.has_text_frame):
                for paragraph in shape.text_frame.paragraphs:
                    for run in paragraph.runs:
                        print run.text
</code>```

I've a slide like this:

Output is:
   Running text

Text is being read from the left frame or the big box but not from the two right frames.

答:
The shapes that are reporting None as their shape type are Group shapes. You can confirm this by printing out their XML:

```<code>print(shape._element)  # should give something like 'CT_GroupShape'
print(shape._element.xml)  # should show XML that starts with `<p:grpSp>`
</code>```

<s>Group shapes aren't yet supported in python-pptx. If you can ungroup them in PowerPoint their text will be accessible.</s>

UPDATE: A group shape has no text. However, you can use group_shape.shapes to iterate over the shapes inside the group and access their text. Note that groups can contain other groups.

Title: Python - pptx - Text Reads

Body:
Code to import data from table and text frame:

 pres = Presentation(ppt_file)

    for slide in pres.slides:
        for shape in slide.shapes:
            if(shape.has_text_frame):
                for paragraph in shape.text_frame.paragraphs:
                    for run in paragraph.runs:
                        print run.text

I've a slide like this:

Output is:
   Running text

Text is being read from the left frame or the big box but not from the two right frames.

Body:
The shapes that are reporting None as their shape type are Group shapes. You can confirm this by printing out their XML:

print(shape._element)  # should give something like 'CT_GroupShape'
print(shape._element.xml)  # should show XML that starts with `<p:grpSp>`

<s>Group shapes aren't yet supported in python-pptx. If you can ungroup them in PowerPoint their text will be accessible.</s>

UPDATE: A group shape has no text. However, you can use group_shape.shapes to iterate over the shapes inside the group and access their text. Note that groups can contain other groups.


问:
Is it possible to generate this query?
Select * From table1.

if table1.field1=1 then inner join table2

else if table1.field1=2 then inner join table3

答:
I think you are looking for something like this, even though it's not entirely clear from your question:</p>

```<code>SELECT *
FROM table1 t1
LEFT JOIN table2 t2 ON <join condition> AND t1.field1 = 1
LEFT JOIN table3 t3 ON <join condition> AND t1.field1 = 2
</code>```

Title: Is it possible to generate this query?

Body:
I think you are looking for something like this, even though it's not entirely clear from your question:

SELECT *
FROM table1 t1
LEFT JOIN table2 t2 ON <join condition> AND t1.field1 = 1
LEFT JOIN table3 t3 ON <join condition> AND t1.field1 = 2


问:
Why does databinding not work?
I have a car-class like this:

```<code>public class car
{
    public String Name {get; private set;}

    public car(string name)
    {
      this.Name = name;
    }
}
</code>```

I also have a userControl:

```<code>public partial class CarListItem : UserControl
{
    private Car car;

    public CarListItem (Car car)
    {
        InitializeComponent();
        this.car= car;
    }

}
</code>```

With xaml:

```<code><Grid>
     <Label Content="{Binding Path=car.Name}" Name="lblCarName"/>
</Grid>
</code>```

but the databinding does not work. What am I doing wrong?

I want to show the name of the car on the userControl.

答:
Using this.DataContext will work, but it's fragile and horrible and not a good way to design your application.  If I were to consume your user control and write this xaml:

```<code><CarListItem DataContext="{Binding MyThing}" />
</code>```

... then your control will break, regardless of whether the Car property is correctly set or not.  That's not very pretty.

A more robust approach is to mark your UserControl element in Xaml with an x:Name, and use ElementName in your binding.  So, your control looks something like this:

```<code><UserControl x:Name="control" ....... (namespaces/etc here)>
  <Grid>
    <Label Content="{Binding Car.Name, ElementName=control}" Name="lblCarName"/>
  </Grid>
</code>```

Now, if you want to set DataContext on the Grid (using DataContext="{Binding Car, ElementName=control}"), you can get the benefit of datacontext in a more robust way.

However, for any of this to work, you need to be exposing your car field as a property, rather than just as a field.  You also need to implement INotifyPropertyChanged so that the UI realises when you change the value of the property, though you can work around this temporarily by setting car before you call InitializeComponent() in your constructor.

ContentLicense: CC BY-SA 2.5

Title: Why does databinding not work?

Body:
I have a car-class like this:

public class car
{
    public String Name {get; private set;}

    public car(string name)
    {
      this.Name = name;
    }
}

I also have a userControl:

public partial class CarListItem : UserControl
{
    private Car car;

    public CarListItem (Car car)
    {
        InitializeComponent();
        this.car= car;
    }

}

With xaml:

<Grid>

</Grid>

but the databinding does not work. What am I doing wrong?

I want to show the name of the car on the userControl.

Body:
Using this.DataContext will work, but it's fragile and horrible and not a good way to design your application.  If I were to consume your user control and write this xaml:

<CarListItem DataContext="{Binding MyThing}" />

... then your control will break, regardless of whether the Car property is correctly set or not.  That's not very pretty.

A more robust approach is to mark your UserControl element in Xaml with an x:Name, and use ElementName in your binding.  So, your control looks something like this:

<UserControl x:Name="control" ....... (namespaces/etc here)>
  <Grid>
    <Label Content="{Binding Car.Name, ElementName=control}" Name="lblCarName"/>
  </Grid>

Now, if you want to set DataContext on the Grid (using DataContext="{Binding Car, ElementName=control}"), you can get the benefit of datacontext in a more robust way.

However, for any of this to work, you need to be exposing your car field as a property, rather than just as a field.  You also need to implement INotifyPropertyChanged so that the UI realises when you change the value of the property, though you can work around this temporarily by setting car before you call InitializeComponent() in your constructor.


问:
Mapbox marker click event in Ionic 2 / Angular 2
I'm getting started with Ionic 2 / Angular 2 and trying to implement Mapbox into my app.

To display custom markers (code example here) Mapbox expects a DOM element, which, as far as I understand it, is not really the Angular way. I want to add a click event on the marker but because Mapbox uses elements, I'm not entirely sure how to approach this cleanly "the Angular way".

Basically, this is the latest version (showing the map and the marker works, but predictably when I click the marker the event listener can't find this.onMarkerClicked):

```<code>export class HomePage {
  //(...)

  refreshMapPosition() {
    /*Initializing Map*/
    mapboxgl.accessToken = this.config.mapbox_public_token;
    this.map = new mapboxgl.Map({ /*https://www.mapbox.com/mapbox-gl-js/api/#map*/
      style: 'mapbox://styles/mapbox/light-v9',
      center: [this.Coordinates.longitude, this.Coordinates.latitude],
      zoom: 16,
      pitch: 80,
      minZoom: 7.5,
      maxZoom: 17,
      container: 'map',
      interactive: false,
    });

    var elCreature = document.createElement('div');
    elCreature.className = 'icon-creature alpaca';
    elCreature.addEventListener('click', function() {
      this.onMarkerClicked();
    });

    var markerCreature = new mapboxgl.Marker(elCreature, {offset: [-20, -20]})
      .setLngLat([this.Coordinates.longitude, this.Coordinates.latitude])
      .addTo(this.map);
  }

  onMarkerClicked() {
    console.log("click");
  }
}
</code>```

I'd be much happier if it was possible to have elCreature coming from a component, where I could use

. What's the best approach there?

答:
```<code>// on your marker HTML
var _self = this;
var _data = this.value;
el.addEventListener('click', function() {
   self.markerClicked(_data);
});

// angular method
markerClicked(value){
  console.log(value);
}
</code>```

Body:
I'm getting started with Ionic 2 / Angular 2 and trying to implement Mapbox into my app.

To display custom markers (code example here) Mapbox expects a DOM element, which, as far as I understand it, is not really the Angular way. I want to add a click event on the marker but because Mapbox uses elements, I'm not entirely sure how to approach this cleanly "the Angular way".

Basically, this is the latest version (showing the map and the marker works, but predictably when I click the marker the event listener can't find this.onMarkerClicked):

export class HomePage {
  //(...)

  refreshMapPosition() {
    /*Initializing Map*/
    mapboxgl.accessToken = this.config.mapbox_public_token;
    this.map = new mapboxgl.Map({ /*https://www.mapbox.com/mapbox-gl-js/api/#map*/
      style: 'mapbox://styles/mapbox/light-v9',
      center: [this.Coordinates.longitude, this.Coordinates.latitude],
      zoom: 16,
      pitch: 80,
      minZoom: 7.5,
      maxZoom: 17,
      container: 'map',
      interactive: false,
    });

    var elCreature = document.createElement('div');
    elCreature.className = 'icon-creature alpaca';
    elCreature.addEventListener('click', function() {
      this.onMarkerClicked();
    });

    var markerCreature = new mapboxgl.Marker(elCreature, {offset: [-20, -20]})
      .setLngLat([this.Coordinates.longitude, this.Coordinates.latitude])
      .addTo(this.map);
  }

  onMarkerClicked() {
    console.log("click");
  }
}

I'd be much happier if it was possible to have elCreature coming from a component, where I could use

. What's the best approach there?


问:
Accessing CollectionViewCell
I have added a button on the collectionviewcell, and once user clicks on that button, it calls the following method, but uviCollectionViewCell is returning nil.

```<code>- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if(collectionView == productCollectionView)
    {
        __weak ProductCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

        cell.addBtnOutlet.tag = indexPath.row;
        [cell.addBtnOutlet addTarget:self
                        action:@selector(collectionViewCellAddButtonPressed:)
              forControlEvents:UIControlEventTouchUpInside];
    }
  return cell;
}

- (IBAction)collectionViewCellAddButtonPressed:(UIButton *)button{
     NSLog(@"Add Button Clicked" );
     // the following is nil
     UICollectionViewCell *uviCollectionCell =  [self.productCollectionView cellForItemAtIndexPath:[NSIndexPath indexPathWithIndex:0]];
 }
</code>```

答:
If you want to do without tag then </p>

```<code>- (IBAction)collectionViewCellAddButtonPressed:(UIButton *)button{
    NSLog(@"Add Button Clicked" );
    UICollectionViewCell *uviCollectionCell =  (UICollectionViewCell *)button.superview;

    // if this is return nil then use like below as i am not sure it will retuen contentview for superview
    UICollectionViewCell *uviCollectionCell1 =  (UICollectionViewCell *)button.superview.superview;
 }
</code>```

Title: Accessing CollectionViewCell

Body:
I have added a button on the collectionviewcell, and once user clicks on that button, it calls the following method, but uviCollectionViewCell is returning nil.

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if(collectionView == productCollectionView)
    {
        __weak ProductCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

        cell.addBtnOutlet.tag = indexPath.row;
        [cell.addBtnOutlet addTarget:self
                        action:@selector(collectionViewCellAddButtonPressed:)
              forControlEvents:UIControlEventTouchUpInside];
    }
  return cell;
}

- (IBAction)collectionViewCellAddButtonPressed:(UIButton *)button{
     NSLog(@"Add Button Clicked" );
     // the following is nil
     UICollectionViewCell *uviCollectionCell =  [self.productCollectionView cellForItemAtIndexPath:[NSIndexPath indexPathWithIndex:0]];
 }

Body:
If you want to do without tag then

- (IBAction)collectionViewCellAddButtonPressed:(UIButton *)button{
    NSLog(@"Add Button Clicked" );
    UICollectionViewCell *uviCollectionCell =  (UICollectionViewCell *)button.superview;

    // if this is return nil then use like below as i am not sure it will retuen contentview for superview
    UICollectionViewCell *uviCollectionCell1 =  (UICollectionViewCell *)button.superview.superview;
 }


问:
what is portable executable format and why we need it?
what are executable formats and what is the use of them?
ex-PE format,com format,ms dos format
why they are necessary and what information does they contain?</p>

答:
PE (Portable Executable) is the file format for .exe, .dll, .sys, etc...

The PE files contain the code(program) and additional information(eg.: import and exports tables, .dlls ,resource management) wrapped inside it.
Program Loader interprets the information and map the file to the memory and load shared libraries that are need.


问:
when installing pyaudio, pip cannot find portaudio.h in /usr/local/include
I'm using mac osx 10.10
As the PyAudio Homepage said, I install the PyAudio using

```<code>brew install portaudio
pip install pyaudio
</code>```

the installation of portaudio seems successful, I can find headers and libs in /usr/local/include and /usr/local/lib
but when I try to install pyaudio, it gives me an error that

```<code>src/_portaudiomodule.c:29:10: fatal error: 'portaudio.h' file not found
#include "portaudio.h"
         ^
1 error generated.
error: command 'cc' failed with exit status 1
</code>```

actually it is in /usr/local/include
why can't it find the file?
some answers to similar questions are not working for me(like using virtualenv, or compile it manually), and I want to find a simple way to solve this.

答:
on Centos:</p>

```<code>yum install -y portaudio portaudio-devel && pip install pyaudio
</code>```

Body:
I'm using mac osx 10.10
As the PyAudio Homepage said, I install the PyAudio using

brew install portaudio
pip install pyaudio

the installation of portaudio seems successful, I can find headers and libs in /usr/local/include and /usr/local/lib
but when I try to install pyaudio, it gives me an error that

src/_portaudiomodule.c:29:10: fatal error: 'portaudio.h' file not found
#include "portaudio.h"
         ^
1 error generated.
error: command 'cc' failed with exit status 1

actually it is in /usr/local/include
why can't it find the file?
some answers to similar questions are not working for me(like using virtualenv, or compile it manually), and I want to find a simple way to solve this.

Body:
on Centos:

yum install -y portaudio portaudio-devel && pip install pyaudio


问:
Transaction concurrency to prevent read of old version of a record
Let's say I have a table called tasks. Each task has a status. I take one of the tasks that are in the To Manage status, put it in the In Management status, and run the procedure that the task was created for (which may take several seconds to complete).

At the end of the execution, the task may return to To Manage or Completed status, depending on whether the procedure must be run again or not.

Now let's say there are several processes that run this activity at the same time, in order to complete or otherwise handle multiple different tasks together.

I would like to make sure that two processes do not manage the same task at the same time. To accomplish this, the activity described above should be performeded within a transaction:

```<code>$db->beginTransaction(); /* transaction A */

/* Reads one task from the database (SELECT query with LIMIT 1) which is in the `To Manage` status and returns it */
$task = $tasks->getNextTask(); /* operation 1 */

/* Changes the status into the `In Management` status (UPDATE query) */
$task->changeStatusToManage(); /* operation 2 */

$db->commit();

$task->execute(); /* operation 3 */
</code>```

I'm using a MySql database and the table is InnoDB, with READ COMMITTED isolation level: https://dev.mysql.com/doc/refman/5.7/en/innodb-transaction-isolation-levels.html

We say that there is only one task in the To Manage status. If two processes (P1 and P2) are executed simultaneously and that transaction A does not exist, the following could happen:

```<code>Instant 1: (operation 1) P1 reads the task id 100 in `To Manage` status
Instant 2: (operation 1) P2 reads the task id 100 in `To Manage` status
Instant 3: (operation 2) P1 puts the task id 100 in the `In Management` status
Instant 4: (operation 2) P2 puts the task id 100 in the `In Management` status
Instant 5: (operation 3) P1 performs the task id 100
Instant 6: (operation 3) P2 performs the task id 100
</code>```

However, the fact that operations 1-2-3 are actually executed within a transaction, this scenario should be impossible.

Can you confirm that it is actually so?

Do I need to perform an explicit LOCK for reading of the task table before doing the operation 1 and release it after the operation 2 has been completed?

Is there anything else I should do to prevent unexpected results?

The DB structure is much more complicated than the one described above. When I change a task status, I write a log on another table, too. This is done by the code (Model classes) itself. I have the task table, the task_status table with a foreign key on task and a task_status_change (which is the log table). Each txn performs 1 read (get the task), 2 writes (change status and write log). So I need to perform something similar to this (pseudocode):

```<code>BEGIN;
$id = SELECT task_id FROM task WHERE task_status_id = 1 LIMIT 1;
UPDATE task SET task_status_id = 2 WHERE task_id = $id;
INSERT INTO task_status_change SET task_id = $id, task_status_id = 2;
COMMIT;
</code>```

As I mentioned above, I'm using READ COMMITED isolation level. I tried to launch two processes at the same time, running together on the same tasks pool.

Task IDs chosen by the first process (ID and timestamp):

```<code>55 1496925510
274 1496925512
384 1496925512
589 1496925513
648 1496925513
1088 1496925513
1990 1496925513
</code>```

Task IDs chosen by the second process (ID and timestamp):

```<code>55 1496925510
274 1496925512
589 1496925512
648 1496925513
810 1496925513
1088 1496925513
2049 1496925514
</code>```

Thank you

答:
getNextTask should modify the status and get the id of the task it modified in a single transaction.  One way (in pseudo code):

```<code>BEGIN;
$id = SELECT id ...
        WHERE status = 'idle'
        LIMIT 1 ... FOR UPDATE;
UPDATE ...  SET status = 'management' WHERE id = $id
COMMIT;
</code>```

Depending on your table structure, it may be possible to do the transaction in a single atomic UPDATE statement.  (You have not provided much detail.)

Do something similar for each status transition.

This provides transactional semantics to a long-running collection of your code, using nothing but one status in the database.

It sounds like a "queuing" mechanism.  I have a mantra:  "Don't queue it, just do it."  This means that it may be easier/faster/simpler to spawn a worker process whenever you have a task to do, instead of queuing it, etc.

Body:
Let's say I have a table called tasks. Each task has a status. I take one of the tasks that are in the To Manage status, put it in the In Management status, and run the procedure that the task was created for (which may take several seconds to complete).

At the end of the execution, the task may return to To Manage or Completed status, depending on whether the procedure must be run again or not.

Now let's say there are several processes that run this activity at the same time, in order to complete or otherwise handle multiple different tasks together.

I would like to make sure that two processes do not manage the same task at the same time. To accomplish this, the activity described above should be performeded within a transaction:

$db->beginTransaction(); /* transaction A */

/* Reads one task from the database (SELECT query with LIMIT 1) which is in the `To Manage` status and returns it */
$task = $tasks->getNextTask(); /* operation 1 */

/* Changes the status into the `In Management` status (UPDATE query) */
$task->changeStatusToManage(); /* operation 2 */

$db->commit();

$task->execute(); /* operation 3 */

I'm using a MySql database and the table is InnoDB, with READ COMMITTED isolation level: https://dev.mysql.com/doc/refman/5.7/en/innodb-transaction-isolation-levels.html

We say that there is only one task in the To Manage status. If two processes (P1 and P2) are executed simultaneously and that transaction A does not exist, the following could happen:

Instant 1: (operation 1) P1 reads the task id 100 in `To Manage` status
Instant 2: (operation 1) P2 reads the task id 100 in `To Manage` status
Instant 3: (operation 2) P1 puts the task id 100 in the `In Management` status
Instant 4: (operation 2) P2 puts the task id 100 in the `In Management` status
Instant 5: (operation 3) P1 performs the task id 100
Instant 6: (operation 3) P2 performs the task id 100

However, the fact that operations 1-2-3 are actually executed within a transaction, this scenario should be impossible.

Can you confirm that it is actually so?

Do I need to perform an explicit LOCK for reading of the task table before doing the operation 1 and release it after the operation 2 has been completed?

Is there anything else I should do to prevent unexpected results?

The DB structure is much more complicated than the one described above. When I change a task status, I write a log on another table, too. This is done by the code (Model classes) itself. I have the task table, the task_status table with a foreign key on task and a task_status_change (which is the log table). Each txn performs 1 read (get the task), 2 writes (change status and write log). So I need to perform something similar to this (pseudocode):

BEGIN;
$id = SELECT task_id FROM task WHERE task_status_id = 1 LIMIT 1;
UPDATE task SET task_status_id = 2 WHERE task_id = $id;
INSERT INTO task_status_change SET task_id = $id, task_status_id = 2;
COMMIT;

As I mentioned above, I'm using READ COMMITED isolation level. I tried to launch two processes at the same time, running together on the same tasks pool.

Task IDs chosen by the first process (ID and timestamp):

55 1496925510
274 1496925512
384 1496925512
589 1496925513
648 1496925513
1088 1496925513
1990 1496925513

Task IDs chosen by the second process (ID and timestamp):

55 1496925510
274 1496925512
589 1496925512
648 1496925513
810 1496925513
1088 1496925513
2049 1496925514

Thank you

Body:
getNextTask should modify the status and get the id of the task it modified in a single transaction.  One way (in pseudo code):

BEGIN;
$id = SELECT id ...
        WHERE status = 'idle'
        LIMIT 1 ... FOR UPDATE;
UPDATE ...  SET status = 'management' WHERE id = $id
COMMIT;

Depending on your table structure, it may be possible to do the transaction in a single atomic UPDATE statement.  (You have not provided much detail.)

Do something similar for each status transition.

This provides transactional semantics to a long-running collection of your code, using nothing but one status in the database.

It sounds like a "queuing" mechanism.  I have a mantra:  "Don't queue it, just do it."  This means that it may be easier/faster/simpler to spawn a worker process whenever you have a task to do, instead of queuing it, etc.


问:
C# facebook graph / How to upload an image on Facebook album?
I am trying to upload an image using ASP.NET with C#.I do not how to send image in parameter
source="F://sample.jpg".I have also tried  to send an image in a byte format.

URL is
  http://graph.facebook.com/album_id/photos?access_token=access_tokenvalue;

Post Data is

source= "F://sample.jpg"

I am getting an exception.Please help me to sort out this issue.

Thanks in advance.

答:
Could you post the error message you're getting?  Might be helpful in tracking down exactly what the error is.  In any case, I'm not too familiar with the Facebook APIs but it appears in the Graph API document for Photo that you have to prefix the file path with an @.</p>

```<code>source="@F:\\sample.jpg"
</code>```

Body:
Could you post the error message you're getting?  Might be helpful in tracking down exactly what the error is.  In any case, I'm not too familiar with the Facebook APIs but it appears in the Graph API document for Photo that you have to prefix the file path with an @.

source="@F:\\sample.jpg"


问:
How to modify a JSON file in a script?
I am trying to edit Chrome's preferences using command line. The file is a JSON file and I want to edit the data below:

```<code>{"browser":{"last_redirect_origin":""}}
</code>```

to

```<code>{"browser":{"enabled_labs_experiments":["ssl-version-max@2"],"last_redirect_origin":""}}
</code>```

I was using sed command earlier to accomplish this but want to know how this can be done using python. This was the command I was using:

```<code>sed -i '.bak' -e 's|\(\"browser\"\):{\(\".*origin\":\"\"\)}|\1:{\"enabled_labs_experiments\":[\"ssl-version-max@2\"],\2}|' ~/Library/Application\ Support/Google/Chrome/Local\ State
</code>```

The reason I can't use jq is that it is not native to macs and will need installation. I am not able to understand how to do this with python.

I will really appreciate it if someone could help me with this or point me in the right direction.

EDIT

This is what my python script looks like:

```<code>import json
jsonData = json.loads(open('/Users/username/Library/Application Support/Google/Chrome/Local state').read())
if 'enabled_labs_experiments' in jsonData['browser']:
    if 'ssl-version-max@2' in jsonData['browser']['enabled_labs_experiments']:
        print('Exist')
    else:
        jsonData['browser']['enabled_labs_experiments'] = ['ssl-version-max@2']
        print('Added')
</code>```

After the changes are made, I would like to commit the changes to the file.

答:
```<code>import json
with open(path_to_json_file) as f:
    data = f.read()
d = json.loads(data)
d["browser"]["enabled_labs_experiments"] = ["ssl-version-max@2"]
with open(path_to_json_file, 'w') as f:
    f.write(json.dumps(d))
</code>```

Title: How to modify a JSON file in a script?

Body:
I am trying to edit Chrome's preferences using command line. The file is a JSON file and I want to edit the data below:

{"browser":{"last_redirect_origin":""}}

to

{"browser":{"enabled_labs_experiments":["ssl-version-max@2"],"last_redirect_origin":""}}

I was using sed command earlier to accomplish this but want to know how this can be done using python. This was the command I was using:

sed -i '.bak' -e 's|\(\"browser\"\):{\(\".*origin\":\"\"\)}|\1:{\"enabled_labs_experiments\":[\"ssl-version-max@2\"],\2}|' ~/Library/Application\ Support/Google/Chrome/Local\ State

The reason I can't use jq is that it is not native to macs and will need installation. I am not able to understand how to do this with python.

I will really appreciate it if someone could help me with this or point me in the right direction.

EDIT

This is what my python script looks like:

import json
jsonData = json.loads(open('/Users/username/Library/Application Support/Google/Chrome/Local state').read())
if 'enabled_labs_experiments' in jsonData['browser']:
    if 'ssl-version-max@2' in jsonData['browser']['enabled_labs_experiments']:
        print('Exist')
    else:
        jsonData['browser']['enabled_labs_experiments'] = ['ssl-version-max@2']
        print('Added')

After the changes are made, I would like to commit the changes to the file.


问:
Calling Naviation.PushAsync from CustomMapRenderer when clicked on a marker
I am working on a xamarin project for ios aswel as android where we are showing custom markers on the Xamarin.Forms maps, we want the user to navigate to another view when he clicks on a custom marker.

We are using Navigation.PushAsync to navigate through the views. this is done from the viewmodels from the non platform specific code, and navigation.PushAsync can only be used there and not from the platformspecific code. Wich is where the customMapRenderers are and where the onlclick for the markers is handled.

So my question is how can i navigate to another view from these onClick Events.
underneath are the methods that catch the onclick.

Android:

```<code>private void OnMarkerClick(object sender, GoogleMap.MarkerClickEventArgs e)
        {
            Toast.MakeText(MainApplication.Context, "Button Pressed", ToastLength.Long).Show();
        }
</code>```

iOS:

```<code>private void OnDidSelectAnnotationView(object sender, MKAnnotationViewEventArgs e)
    {
        UIAlertView alert = new UIAlertView()
        {
            Title = "Event",
            Message = "Button Clicked"
        };
        alert.AddButton("Oke");
        alert.Show();
    }
</code>```

答:
As Yuri said, you can implement this by using Messenger, here is a sample  about how to use Messenger. You can use it in custom renderer onClick Events, When send a message in renderer, the Page will received Message. So you can navigate to another view in your Page's MessagingCenter.Subscribe method.

Page:

```<code>MessagingCenter.Subscribe<MainPage>(this, "Navigation", async (sender) =>
{
     var page1 = new Page1();
     await Navigation.PushModalAsync(page1);
});
</code>```

Custom Renderer:

```<code>MessagingCenter.Send<MainPage>(MainPage.getInstance(), "Navigation");
</code>```

Body:
I am working on a xamarin project for ios aswel as android where we are showing custom markers on the Xamarin.Forms maps, we want the user to navigate to another view when he clicks on a custom marker.

We are using Navigation.PushAsync to navigate through the views. this is done from the viewmodels from the non platform specific code, and navigation.PushAsync can only be used there and not from the platformspecific code. Wich is where the customMapRenderers are and where the onlclick for the markers is handled.

So my question is how can i navigate to another view from these onClick Events.
underneath are the methods that catch the onclick.

Android:

private void OnMarkerClick(object sender, GoogleMap.MarkerClickEventArgs e)
        {
            Toast.MakeText(MainApplication.Context, "Button Pressed", ToastLength.Long).Show();
        }

iOS:

private void OnDidSelectAnnotationView(object sender, MKAnnotationViewEventArgs e)
    {
        UIAlertView alert = new UIAlertView()
        {
            Title = "Event",
            Message = "Button Clicked"
        };
        alert.AddButton("Oke");
        alert.Show();
    }

Body:
As Yuri said, you can implement this by using Messenger, here is a sample  about how to use Messenger. You can use it in custom renderer onClick Events, When send a message in renderer, the Page will received Message. So you can navigate to another view in your Page's MessagingCenter.Subscribe method.

Page:

MessagingCenter.Subscribe<MainPage>(this, "Navigation", async (sender) =>
{
     var page1 = new Page1();
     await Navigation.PushModalAsync(page1);
});

Custom Renderer:

MessagingCenter.Send<MainPage>(MainPage.getInstance(), "Navigation");


问:
Display first 3 line from large paragraph from php mysql
I am using PHP and MySQL to get data from database. I have one description field in database. In description field contains large para.

For example: (In database description field contain this para)

The ‘Fox and the Grapes’ is often cited as an example for cognitive dissonance: the discomfort people experience when their beliefs/actions are at odds with other beliefs/actions. In the story, the fox sees some grapes on a vine and wants to eat them. He tries to jump up, but cannot reach them because they are too high. When he realizes he will not be able to eat any grapes, the fox becomes disdainful; he tells himself that those grapes were sour and not worthy of desire anyway.

Now I want only first three line from this para like that

The ‘Fox and the Grapes’ is often cited as an example for cognitive dissonance: the discomfort people experience when their beliefs/actions are at odds with other beliefs/actions.

答:
Instead of first three line, you can go with first 100 or 200 characters what ever fulfill you requirements and show ... or more button to get the entire text. For this you have to take the first 100 or 200 characters of the entire text and after that show ... or more button.

For taking the first 100 characters of a string make sure you don't break a word like:

```<code>$pos=strpos($content, ' ', 200);
echo substr($content,0,$pos );
</code>```

Example

Body:
Instead of first three line, you can go with first 100 or 200 characters what ever fulfill you requirements and show ... or more button to get the entire text. For this you have to take the first 100 or 200 characters of the entire text and after that show ... or more button.

For taking the first 100 characters of a string make sure you don't break a word like:

$pos=strpos($content, ' ', 200);
echo substr($content,0,$pos );

Example


问:
Should I install Visual Studio 2017 beside Visual Studio 2015 or should I first uninstall Visual Studio 2015 and then install Visual Studio 2017?
I am currently using Visual Studio 2015 for programming ASP.NET Core applications. I have the following questions regarding installing Visual Studio 2017:

What is considered to be best practice and/or cleanest method?

Should I install Visual Studio 2017 beside Visual Studio 2015?

Should I first uninstall Visual Studio 2015 and all .NET Core dependencies and then install Visual Studio 2017?

Are there any tools that would ensure a clean uninstall of Visual Studio 2015?

答:
From page Visual Studio 2017 Platform Targeting and Compatibility

Compatibility with Previous Releases Installation

You can install and use Visual Studio 2017 alongside previous versions of Visual Studio, including Visual Studio 2015, Visual Studio 2013, and Visua Studio 2012.

So yes. you can install them without any problem.


问:
How to append entry in the same page using angularJS, without using array to store previous entry
This is my html file, that get data from controller. Controller get new data every time from API once i press the load button by increasing the offset value.

```<code> <div class="container" ng-app="myApp" ng-controller="myctrl">
    <div class="row row-gap" ng-repeat="data in data">
        <div  class="media-left media-middle">
          <a href="#">
            <img class="media-object rounded" ng-src="{{data.thumbnail}}">
          </a>
        </div>
        <div class="media-body" >
          <table class="table table-striped">
            <tr>
               <td class="col-md-3"> <span class="glyphicon glyphicon-share-alt" aria-hidden="true">Name</span></td>
                <td class="col-md-9">{{data.title}}</td>
          </tr>
            <tr>
              <td class="col-md-3"> <span class="glyphicon glyphicon-map-marker" aria-hidden="true"></span> Place </td>
              <td class="col-md-9"> Star{{data.placeName}} </td>
               </tr>
                 <tr>
                    <td class="col-md-3"> <span class="glyphicon glyphicon-time" aria-hidden="true"></span> Submitted On </td>
              <td class="col-md-9">{{data.createdOn |date }}</td>
               </tr>
           </table>
             <img ng-src="{{data.author.icon}}";alt="{{data.author.name}}";height=30px; width=30px  >
        </div>
      </div>

      <button  type="button"  ng-click="loadMore(count=count+1)"  class="btn btn-default">load More</button>

     </div>
</code>```

The container code is as follow. I am aware that i am using the same data variable to store the subsequent query result.
I just want that whenever i click on load more button, data get append in the same page without effecting the previous values.

```<code> var myApp=angular.module('myApp',[]);

myApp.controller('myctrl',function ($scope, $http) {

  $http({
        method: 'GET',
        url: 'API?max=10&offset=0&format=json'

     }).then(function (datacontent){
         $scope.data=datacontent.data.model.observationInstanceList;
        console.log(show);
     },function (error){
//console.log(error);
     });

$scope.count=0;
$scope.loadMore=function(value) {
value=value*10;
  $http({
        method: 'GET',
        url: 'http://API?max=10&offset='+value+'&format=json'

     }).then(function (dataco){
         $scope.data=dataco.data.model.observationInstanceList;

     },function (error){
//console.log(error);
     });
}

});

  I need answer in such a way, the array size doesnot increase much.
</code>```

答:
Try this, but only works if dataco.data.model.observationInstanceList is an array.

```<code>$scope.data = $scope.data.length ? $scope.data.concat(dataco.data.model.observationInstanceList) : dataco.data.model.observationInstanceList;
</code>```

Change your code as below

```<code>$scope.count=0;
$scope.loadMore=function(value) {
value=value*10;
  $http({
        method: 'GET',
        url: 'http://API?max=10&offset='+value+'&format=json'

     }).then(function (dataco){
         $scope.data = $scope.data.length ? $scope.data.concat(dataco.data.model.observationInstanceList) : dataco.data.model.observationInstanceList;

     },function (error){
//console.log(error);
     });
}
</code>```

Body:
This is my html file, that get data from controller. Controller get new data every time from API once i press the load button by increasing the offset value.

                Name
                {{data.title}}

                Place
               Star{{data.placeName}}

                      Submitted On
              {{data.createdOn |date }}

      <button  type="button"  ng-click="loadMore(count=count+1)"  class="btn btn-default">load More</button>

The container code is as follow. I am aware that i am using the same data variable to store the subsequent query result.
I just want that whenever i click on load more button, data get append in the same page without effecting the previous values.

 var myApp=angular.module('myApp',[]);

myApp.controller('myctrl',function ($scope, $http) {

  $http({
        method: 'GET',
        url: 'API?max=10&offset=0&format=json'

     }).then(function (datacontent){
         $scope.data=datacontent.data.model.observationInstanceList;
        console.log(show);
     },function (error){
//console.log(error);
     });

$scope.count=0;
$scope.loadMore=function(value) {
value=value*10;
  $http({
        method: 'GET',
        url: 'http://API?max=10&offset='+value+'&format=json'

     }).then(function (dataco){
         $scope.data=dataco.data.model.observationInstanceList;

     },function (error){
//console.log(error);
     });
}

});

  I need answer in such a way, the array size doesnot increase much.

Body:
Try this, but only works if dataco.data.model.observationInstanceList is an array.

$scope.data = $scope.data.length ? $scope.data.concat(dataco.data.model.observationInstanceList) : dataco.data.model.observationInstanceList;

Change your code as below

$scope.count=0;
$scope.loadMore=function(value) {
value=value*10;
  $http({
        method: 'GET',
        url: 'http://API?max=10&offset='+value+'&format=json'

     }).then(function (dataco){
         $scope.data = $scope.data.length ? $scope.data.concat(dataco.data.model.observationInstanceList) : dataco.data.model.observationInstanceList;

     },function (error){
//console.log(error);
     });
}


问:
Get chosen shipping method title by its Id in WooCommerce
In WooCommerce includes\class-express-checkout-gateway.php file I am getting shipping method Id by the following code:

```<code>$chosen_shipping_methods = WC()->session->get('chosen_shipping_methods');
</code>```

It gets flat_rate:1, but I need its title - Flat Rate.

I have already tried all this answers and many more.

How can I get this?

答:
```<code>$rate_table = array();

$shipping_methods = WC()->shipping->get_shipping_methods();

foreach($shipping_methods as $shipping_method){
    $shipping_method->init();

    foreach($shipping_method->rates as $key=>$val)
        $rate_table[$key] = $val->label;
}

echo $rate_table[WC()->session->get( 'chosen_shipping_methods' )[0]];
</code>```

Try like this

Body:
In WooCommerce includes\class-express-checkout-gateway.php file I am getting shipping method Id by the following code:

$chosen_shipping_methods = WC()->session->get('chosen_shipping_methods');

It gets flat_rate:1, but I need its title - Flat Rate.

I have already tried all this answers and many more.

How can I get this?

Body:
$rate_table = array();

$shipping_methods = WC()->shipping->get_shipping_methods();

foreach($shipping_methods as $shipping_method){
    $shipping_method->init();

    foreach($shipping_method->rates as $key=>$val)
        $rate_table[$key] = $val->label;
}

echo $rate_table[WC()->session->get( 'chosen_shipping_methods' )[0]];

Try like this


问:
the directory check for /proc/<thread id> return true, although there is no such directory
I'm running this code in bash shell:

```<code>if [ ! -d /proc/<thread id> ]
then
    echo "There is no such process"
fi
</code>```

It doesn't print error message, although I can see that there is no such directory. When I do the same thing with another id, different from any thread id, it print message.

So for all threads there is also /proc/<thread id> directory, which I can't see with ls?

答:
I also noticed this problem. After tracing syscalls, it seems that ls -l /proc/ calls openat and then calls getdents64 syscall. This will only shows PIDs.

However, stat /proc/TID/ will call newfstatat, which can retrieve file information of /proc/TID. Guess this issue is caused by kernel implementation of procfs.

Body:
I'm running this code in bash shell:

if [ ! -d /proc/<thread id> ]
then
    echo "There is no such process"
fi

It doesn't print error message, although I can see that there is no such directory. When I do the same thing with another id, different from any thread id, it print message.

So for all threads there is also /proc/<thread id> directory, which I can't see with ls?


问:
Python Sum of Linked List
These are my code

```<code>class Node():
'''A node in a linked list'''
    def __init__(self, data, next_node=None):
        self.data = data
        self.next_node = next_node

def sum(LL):

    head = LL

    # If Linked list is empty, return 0
    if (head.data is None or head.data == []):
        result = 0

    # If Linked List contain only 1 node then return it
    elif (head.next_node is None):
        result = head.data

    else:
        curr = head
        result = curr.data
        # If next is not None then add up to result
        while (curr.next_node is not None):
            curr = curr.next_node
            result += curr.data

    return result
</code>```

Problem is at the end of the code

```<code>while (curr.next_node is not None):
    curr = curr.next_node
    result += curr.data
</code>```

If i try this

```<code>LL = Node(1, Node(2, 3))
sum(LL)
</code>```

I don't understand why it said

builtins.AttributeError: 'int' object has no attribute 'data'

The while loop works until it reach the last node

result should be 6

答:
How about a different approach; create an iterator to iterate through the linked list.  Then you've got a standard iterator and you can just sum it with the builtin sum function:</p>

```<code>def traverse(LL):
    head = LL
    while (head):
        yield head.data
        head = head.next_node

sum(traverse(LL))
</code>```

Title: Python Sum of Linked List

Body:
These are my code

class Node():
'''A node in a linked list'''
    def __init__(self, data, next_node=None):
        self.data = data
        self.next_node = next_node

def sum(LL):

    head = LL

    # If Linked list is empty, return 0
    if (head.data is None or head.data == []):
        result = 0

    # If Linked List contain only 1 node then return it
    elif (head.next_node is None):
        result = head.data

    else:
        curr = head
        result = curr.data
        # If next is not None then add up to result
        while (curr.next_node is not None):
            curr = curr.next_node
            result += curr.data

    return result

Problem is at the end of the code

while (curr.next_node is not None):
    curr = curr.next_node
    result += curr.data

If i try this

LL = Node(1, Node(2, 3))
sum(LL)

I don't understand why it said

builtins.AttributeError: 'int' object has no attribute 'data'

The while loop works until it reach the last node

result should be 6

Body:
How about a different approach; create an iterator to iterate through the linked list.  Then you've got a standard iterator and you can just sum it with the builtin sum function:

def traverse(LL):
    head = LL
    while (head):
        yield head.data
        head = head.next_node

sum(traverse(LL))


问:
What kind of vulnerabilities involve the attacker sending "php://input"?
My site was just bombarded by an attacker trying to pass "php://input" into any GET/POST variable they could think of. If this is trying to take advantage of a vulnerability, I'm unaware of it. What could this user be trying to exploit?</p>

答:
http://www.owasp.org/index.php/Top_10_2007-Malicious_File_Execution

php://input reads data from the incoming request. Basically, what the attacker might be trying to do is pass "php://input" into a weak php directive such as:

```<code>include $_REQUEST['filename'];
</code>```

It would allow the attacker to send the "contents" of the php file to execute via the request, thereby allowing him to execute php code on your machine

Body:
http://www.owasp.org/index.php/Top_10_2007-Malicious_File_Execution

php://input reads data from the incoming request. Basically, what the attacker might be trying to do is pass "php://input" into a weak php directive such as:

include $_REQUEST['filename'];

It would allow the attacker to send the "contents" of the php file to execute via the request, thereby allowing him to execute php code on your machine


问:
Unexpected Behavior from .Net Charts
I am trying to create .Net Chart (Windows.Forms) and export it to a .jpeg file.

Below is the code for it

```<code>public void ExportRouteGraphToJpeg(string nameOfChart, int xMax, int yMax, int xMin, int yMin )
{
    var chartForExport = new Chart();
    chartForExport.Series.Clear();

    var xVsYSeries = new Series
    {
        Name = "XvsY",
        Color = Color.Blue,
        IsVisibleInLegend = false,
        IsXValueIndexed = true,
        ChartType = SeriesChartType.Point,
        MarkerSize = 6,
        MarkerColor   = Color.Blue
    };

    for (var i = 0; i < xValue.Length; i++)
    {
        xVsYSeries.Points.AddXY(xValue[i], yValue[i]);
    }

    chartForExport.Series.Add(xVsYSeries);

    // Chart Area Definition
    var chartArea = new ChartArea
    {
        Name = "SupportPoints",
        AxisX =
        {
            Title = "X Co-ordinate [cm]",
            ArrowStyle = AxisArrowStyle.Triangle,
            Maximum = xMax + 100,
            Minimum = xMin - 100
        },
        AxisY =
        {
            Title = "Y Co-ordinate [cm]",
            ArrowStyle = AxisArrowStyle.Triangle,
            Maximum = yMax + 100,
            Minimum = yMin - 100
        }
    };

    chartForExport.ChartAreas.Add(chartArea);
    chartForExport.Location = new Point(0, 50);
    chartForExport.TabIndex = 0;

    chartForExport.Name = "ChartRoute";

    chartForExport.SaveImage(nameOfChart + ".jpeg", ChartImageFormat.Jpeg);
}
</code>```

The output I get is shown below (for 5 points of xValue = 1000, 2000, 3000, 4000 and same for yValue)

When I remove Maximum = yMax + 100, Minimum = yMin - 100 for AxisX and AxisY, I get desired output. please see below

Any suggestion why is this happening?

答:
Use some third party charts like high chart,Example is given below</p>

```<code>DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>Bar Chart</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
    <script src="http://code.highcharts.com/highcharts.js" type="text/javascript"></script>
      <script src="http://code.highcharts.com/modules/exporting.js" type="text/javascript"></script>

      <script type="text/javascript">
          $(function() {
              $('#container').highcharts({
                  chart: {
                      type: 'bar'
                  },
                  title: {
                      text: 'MyFruit database info'
                  },
                  xAxis: {
                      categories: ['Records', 'Fragmentation', 'Users']
                  },
                  yAxis: {
                      title: {
                          text: 'Values'
                      }
                  },
                  series: [
                      {
                          name: 'MyFruit_Sites',
                          data: [10, 50, 4]
                      }, {
                          name: 'MyFruit_Devices',
                          data: [500, 80, 3]
                      }
                  ]
              });

              // the button handler
              $('#button').click(function () {
                  var chart = $('#container').highcharts();
                  chart.addSeries({
                              name: 'MyFruit_Users',
                              data: [30, 60, 4]
                          });
                });
          });
      </script>
  </head>
  <body>
    <div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
      <button id="button" class="autocompare">Add series</button>
  </body>
</html>
</code>```

Title: Unexpected Behavior from .Net Charts

Body:
I am trying to create .Net Chart (Windows.Forms) and export it to a .jpeg file.

Below is the code for it

public void ExportRouteGraphToJpeg(string nameOfChart, int xMax, int yMax, int xMin, int yMin )
{
    var chartForExport = new Chart();
    chartForExport.Series.Clear();

    var xVsYSeries = new Series
    {
        Name = "XvsY",
        Color = Color.Blue,
        IsVisibleInLegend = false,
        IsXValueIndexed = true,
        ChartType = SeriesChartType.Point,
        MarkerSize = 6,
        MarkerColor   = Color.Blue
    };

    for (var i = 0; i < xValue.Length; i++)
    {
        xVsYSeries.Points.AddXY(xValue[i], yValue[i]);
    }

    chartForExport.Series.Add(xVsYSeries);

    // Chart Area Definition
    var chartArea = new ChartArea
    {
        Name = "SupportPoints",
        AxisX =
        {
            Title = "X Co-ordinate [cm]",
            ArrowStyle = AxisArrowStyle.Triangle,
            Maximum = xMax + 100,
            Minimum = xMin - 100
        },
        AxisY =
        {
            Title = "Y Co-ordinate [cm]",
            ArrowStyle = AxisArrowStyle.Triangle,
            Maximum = yMax + 100,
            Minimum = yMin - 100
        }
    };

    chartForExport.ChartAreas.Add(chartArea);
    chartForExport.Location = new Point(0, 50);
    chartForExport.TabIndex = 0;

    chartForExport.Name = "ChartRoute";

    chartForExport.SaveImage(nameOfChart + ".jpeg", ChartImageFormat.Jpeg);
}

The output I get is shown below (for 5 points of xValue = 1000, 2000, 3000, 4000 and same for yValue)

When I remove Maximum = yMax + 100, Minimum = yMin - 100 for AxisX and AxisY, I get desired output. please see below

Any suggestion why is this happening?

Body:
Use some third party charts like high chart,Example is given below

DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>Bar Chart</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
    <script src="http://code.highcharts.com/highcharts.js" type="text/javascript"></script>
      <script src="http://code.highcharts.com/modules/exporting.js" type="text/javascript"></script>

      <script type="text/javascript">
          $(function() {
              $('#container').highcharts({
                  chart: {
                      type: 'bar'
                  },
                  title: {
                      text: 'MyFruit database info'
                  },
                  xAxis: {
                      categories: ['Records', 'Fragmentation', 'Users']
                  },
                  yAxis: {
                      title: {
                          text: 'Values'
                      }
                  },
                  series: [
                      {
                          name: 'MyFruit_Sites',
                          data: [10, 50, 4]
                      }, {
                          name: 'MyFruit_Devices',
                          data: [500, 80, 3]
                      }
                  ]
              });

              // the button handler
              $('#button').click(function () {
                  var chart = $('#container').highcharts();
                  chart.addSeries({
                              name: 'MyFruit_Users',
                              data: [30, 60, 4]
                          });
                });
          });
      </script>
  </head>
  <body>
    <div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
      <button id="button" class="autocompare">Add series</button>
  </body>
</html>


问:
Using GroupLayout and FlowLayout together : OutPut is not appearing in Center
I am trying to create a UI in Java swing with Layouts. I want radio buttons and 2 texts field and buttons. For radio buttons, I have used Flow layout and for text fields and button I am using Group layout. But output I am getting is scattered and the text fields are stretched. I want all these components at the center of the window. Following is my code.</p>

```<code>  package DecodeTool1;

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;

      public class SwingLayoutDemo {
          private JFrame mainFrame;
            private JLabel file_1;
          private JLabel file_2;
        private JPanel RPanel;
         private JPanel TextPanel;

         private JPanel panel;

         public SwingLayoutDemo(){
                prepareGUI();
         }
              public static void main(String[] args){
            SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo();
            swingLayoutDemo.showGroupLayoutDemo();
       }
       private void prepareGUI(){
          mainFrame = new JFrame("Java SWING Examples");
         mainFrame.setSize(400,400);
              mainFrame.setLayout(new GridLayout(3, 2,20,10));

  file_1 = new JLabel("",JLabel.CENTER);
  file_2 = new JLabel("",JLabel.CENTER);
  file_2.setSize(100,100);

             mainFrame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent windowEvent){
                 System.exit(0);
                 }
          });
         panel = new JPanel();

          TextPanel = new JPanel();
            mainFrame.add(file_1);
           mainFrame.add(file_2);

          mainFrame.setVisible(true);
      }
        private void showGroupLayoutDemo(){

           RPanel = new JPanel();
           RPanel.setSize(50,50);
            RPanel.setBounds(150, 0, 50, 50);
           TextPanel = new JPanel();
             TextPanel.setSize(50,50);

            JRadioButton r1=new JRadioButton("Airport");
            JRadioButton r2 = new JRadioButton("Apex");
            JRadioButton r3 = new JRadioButton("IN");
             ButtonGroup bg=new ButtonGroup();

             FlowLayout layoutFL = new FlowLayout();
              layoutFL.setAlignment(FlowLayout.CENTER);
                RPanel.setLayout(layoutFL);
               layoutFL.setHgap(15);

                 RPanel.add(bg);

                 RPanel.add(comboApex);

               RPanel.add(comboINAV);

               file_1.setText("File1");
                file_2.setText("File2");
                JTextField text1 = new JTextField(10);
                JTextField text2 = new JTextField(10);
                   text1.setSize(15, 5);
                  text2.setSize(15,5);

                  GroupLayout layout = new GroupLayout(TextPanel);
              layout.setAutoCreateGaps(true);
             layout.setAutoCreateContainerGaps(true);

               JButton btn1 = new JButton("Browse");
                  JButton btn2 = new JButton("Browse");

              layout.setHorizontalGroup(layout.createSequentialGroup()
                //  .addGroup(layout.createSequentialGroup()
     .addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)

     .addComponent(file_1)
     .addComponent(file_2))
     .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
     .addComponent(text1)
     .addComponent(text2))

          .addGroup(layout.createParallelGroup(
          GroupLayout.Alignment.CENTER)

             .addComponent(btn1))
         .addComponent(btn2)

          .addGroup(layout.createSequentialGroup()
             .addComponent(btn3)));

           layout.setVerticalGroup(layout.createSequentialGroup()

     .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
          .addComponent(file_1)
          .addComponent(text1)
          .addComponent(btn1))
          .addComponent(btn3)

      .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
             .addComponent(file_2)
                     .addComponent(text2)
                     .addComponent(btn2)));

                TextPanel.setLayout(layout);

               mainFrame.add(RPanel);
             mainFrame.add(TextPanel);
              mainFrame.add(panel);

              mainFrame.pack();

                 mainFrame.setVisible(true);

      }
      }
</code>```

答:
You can use BoxLayout layout and GridBagLayout.

GridBagLayout is one of the recommended as the flexible and powerful layout manager.

Little exampele:

```<code>import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.GridBagLayout;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;

public class Framework {
    public Framework(){
        init();
    }

    public void init(){
        JFrame frame = new JFrame("Exo");
        //frame.setSize(300, 300); -@Andrew comment: frame.setSize(300, 300); will be negated by.. frame.pack();. Only do the latter.
        frame.setLayout(new CardLayout());

        JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.PAGE_AXIS));

        JButton bt1 = new JButton("Say");
        JButton bt2 = new JButton("Say");
        JButton bt3 = new JButton("Say");
        centerPanel.add(bt1);
        centerPanel.add(bt2);
        centerPanel.add(bt3);
        centerPanel.add(Box.createVerticalGlue());

        JPanel panelConstrain = new JPanel(new GridBagLayout());
        panelConstrain.add(centerPanel);
        frame.add(panelConstrain, BorderLayout.CENTER);

        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);
        frame.pack();
        frame.setVisible(true);
    }
    public static void main(String[] args) {
        new Framework();
    }
}
</code>```

Body:
I am trying to create a UI in Java swing with Layouts. I want radio buttons and 2 texts field and buttons. For radio buttons, I have used Flow layout and for text fields and button I am using Group layout. But output I am getting is scattered and the text fields are stretched. I want all these components at the center of the window. Following is my code.

  package DecodeTool1;

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;

      public class SwingLayoutDemo {
          private JFrame mainFrame;
            private JLabel file_1;
          private JLabel file_2;
        private JPanel RPanel;
         private JPanel TextPanel;

         private JPanel panel;

         public SwingLayoutDemo(){
                prepareGUI();
         }
              public static void main(String[] args){
            SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo();
            swingLayoutDemo.showGroupLayoutDemo();
       }
       private void prepareGUI(){
          mainFrame = new JFrame("Java SWING Examples");
         mainFrame.setSize(400,400);
              mainFrame.setLayout(new GridLayout(3, 2,20,10));

  file_1 = new JLabel("",JLabel.CENTER);
  file_2 = new JLabel("",JLabel.CENTER);
  file_2.setSize(100,100);

             mainFrame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent windowEvent){
                 System.exit(0);
                 }
          });
         panel = new JPanel();

          TextPanel = new JPanel();
            mainFrame.add(file_1);
           mainFrame.add(file_2);

          mainFrame.setVisible(true);
      }
        private void showGroupLayoutDemo(){

           RPanel = new JPanel();
           RPanel.setSize(50,50);
            RPanel.setBounds(150, 0, 50, 50);
           TextPanel = new JPanel();
             TextPanel.setSize(50,50);

            JRadioButton r1=new JRadioButton("Airport");
            JRadioButton r2 = new JRadioButton("Apex");
            JRadioButton r3 = new JRadioButton("IN");
             ButtonGroup bg=new ButtonGroup();

             FlowLayout layoutFL = new FlowLayout();
              layoutFL.setAlignment(FlowLayout.CENTER);
                RPanel.setLayout(layoutFL);
               layoutFL.setHgap(15);

                 RPanel.add(bg);

                 RPanel.add(comboApex);

               RPanel.add(comboINAV);

               file_1.setText("File1");
                file_2.setText("File2");
                JTextField text1 = new JTextField(10);
                JTextField text2 = new JTextField(10);
                   text1.setSize(15, 5);
                  text2.setSize(15,5);

                  GroupLayout layout = new GroupLayout(TextPanel);
              layout.setAutoCreateGaps(true);
             layout.setAutoCreateContainerGaps(true);

               JButton btn1 = new JButton("Browse");
                  JButton btn2 = new JButton("Browse");

              layout.setHorizontalGroup(layout.createSequentialGroup()
                //  .addGroup(layout.createSequentialGroup()
     .addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)

     .addComponent(file_1)
     .addComponent(file_2))
     .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
     .addComponent(text1)
     .addComponent(text2))

          .addGroup(layout.createParallelGroup(
          GroupLayout.Alignment.CENTER)

             .addComponent(btn1))
         .addComponent(btn2)

          .addGroup(layout.createSequentialGroup()
             .addComponent(btn3)));

           layout.setVerticalGroup(layout.createSequentialGroup()

     .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
          .addComponent(file_1)
          .addComponent(text1)
          .addComponent(btn1))
          .addComponent(btn3)

      .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
             .addComponent(file_2)
                     .addComponent(text2)
                     .addComponent(btn2)));

                TextPanel.setLayout(layout);

               mainFrame.add(RPanel);
             mainFrame.add(TextPanel);
              mainFrame.add(panel);

              mainFrame.pack();

                 mainFrame.setVisible(true);

      }
      }

Body:
You can use BoxLayout layout and GridBagLayout.

GridBagLayout is one of the recommended as the flexible and powerful layout manager.

Little exampele:

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.GridBagLayout;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;

public class Framework {
    public Framework(){
        init();
    }

    public void init(){
        JFrame frame = new JFrame("Exo");
        //frame.setSize(300, 300); -@Andrew comment: frame.setSize(300, 300); will be negated by.. frame.pack();. Only do the latter.
        frame.setLayout(new CardLayout());

        JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.PAGE_AXIS));

        JButton bt1 = new JButton("Say");
        JButton bt2 = new JButton("Say");
        JButton bt3 = new JButton("Say");
        centerPanel.add(bt1);
        centerPanel.add(bt2);
        centerPanel.add(bt3);
        centerPanel.add(Box.createVerticalGlue());

        JPanel panelConstrain = new JPanel(new GridBagLayout());
        panelConstrain.add(centerPanel);
        frame.add(panelConstrain, BorderLayout.CENTER);

        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);
        frame.pack();
        frame.setVisible(true);
    }
    public static void main(String[] args) {
        new Framework();
    }
}


问:
banner refresh code
I have banner code, which is not like images and hyperlinks. All I need is the javascript code that will refresh this code every 30 seconds without refreshing the rest of the page.

This banner code will be appear in chatroom. I would really appreciate any help.
The banner code:

```<code><script language='JavaScript'
        type='text/javascript'
        src='xxxxxx/banner.php?uname=yyyy&type=2&rows=1' >
</script>
</code>```

答:
you'll want to give that script tag an ID (such as id='dynScript') and then have another script block that does pretty much the following: [Note: I'm using jQuery]

```<code><script>
  $(document).ready(function(){

    setTimeout ( $('#dynScript').attr('src','xxxxxx/banner.php?uname=yyyy&type=2&rows=1'), 3000);
  });
</script>
</code>```

Title: banner refresh code

Body:
you'll want to give that script tag an ID (such as id='dynScript') and then have another script block that does pretty much the following: [Note: I'm using jQuery]

<script>
  $(document).ready(function(){

    setTimeout ( $('#dynScript').attr('src','xxxxxx/banner.php?uname=yyyy&type=2&rows=1'), 3000);
  });
</script>


问:
$_POST data is empty after submit
I'm having a contact form by html below:

```<code><form id="contactForm" action="http://voicemarketing.cmctelecom.vn/php/contact-form.php" method="POST">
<div class="row">
    <div class="form-group">
        <div class="col-md-6">
            <label>Your Name *</label>
            <input type="text" value="" data-msg-required="Please enter your name." maxlength="100" class="form-control" name="name" id="name" required>
        </div>
        <div class="col-md-6">
            <label>Your Company Name *</label>
            <input type="text" value="" data-msg-required="Please enter your company name." maxlength="100" class="form-control" name="companyname" id="companyname" required>
        </div>
    </div>
</div>
<div class="row">
    <div class="form-group">
        <div class="col-md-6">
            <label>Your phone number *</label>
            <input type="number" value="" data-msg-required="Please enter your phone number." maxlength="12" class="form-control" name="phonenumber" id="phonenumber" required>
        </div>
        <div class="col-md-6">
            <label>Your email address *</label>
            <input type="email" value="" data-msg-required="Please enter your email address." data-msg-email="Please enter a valid email address." maxlength="100" class="form-control" name="email" id="email" required>
        </div>
    </div>
</div>
<div class="row">
    <div class="form-group">
        <div class="col-md-12">
            <label>Message *</label>
            <textarea maxlength="5000" data-msg-required="Please enter your message." rows="10" class="form-control" name="message" id="message" required></textarea>
        </div>
    </div>
</div>
<div class="row">
    <div class="col-md-12">
        <input type="submit" value="Send Message" class="btn btn-primary btn-lg mb-xlg" data-loading-text="Loading...">
    </div>
</div>
</code>```

I tried to get the value by $_POST

```<code>$fields = array(
0 => array(
    'text' => 'Name',
    'val' => $_POST['name']
),
1 => array(
    'text' => 'Email address',
    'val' => $_POST['email']

),
2 => array(
    'text' => 'Message',
    'val' => $_POST['message']

),
3 => array(
    'text' => 'Company',
    'val' => $_POST['companyname']
),
4 => array(
    'text' => 'Phone Number',
    'val' => $_POST['phonenumber']
));
</code>```

Like usual, I put $_POST['name of form']
but only name, email, message are working
and companyname, phonenumber return nothing.
I really can't figure what is the problem is

答: Make sure your database is set up correctly, sometimes you might be trying to put text inside of a "int" type row, which will result in this kind of issue. Worth checking.</p>

Title: $_POST data is empty after submit

Body:
I'm having a contact form by html below:

<form id="contactForm" action="http://voicemarketing.cmctelecom.vn/php/contact-form.php" method="POST">

            Your Name *
            <input type="text" value="" data-msg-required="Please enter your name." maxlength="100" class="form-control" name="name" id="name" required>

            Your Company Name *
            <input type="text" value="" data-msg-required="Please enter your company name." maxlength="100" class="form-control" name="companyname" id="companyname" required>

            Your phone number *
            <input type="number" value="" data-msg-required="Please enter your phone number." maxlength="12" class="form-control" name="phonenumber" id="phonenumber" required>

            Your email address *
            <input type="email" value="" data-msg-required="Please enter your email address." data-msg-email="Please enter a valid email address." maxlength="100" class="form-control" name="email" id="email" required>

            Message *
            <textarea maxlength="5000" data-msg-required="Please enter your message." rows="10" class="form-control" name="message" id="message" required></textarea>

        <input type="submit" value="Send Message" class="btn btn-primary btn-lg mb-xlg" data-loading-text="Loading...">

I tried to get the value by $_POST

$fields = array(
0 => array(
    'text' => 'Name',
    'val' => $_POST['name']
),
1 => array(
    'text' => 'Email address',
    'val' => $_POST['email']

),
2 => array(
    'text' => 'Message',
    'val' => $_POST['message']

),
3 => array(
    'text' => 'Company',
    'val' => $_POST['companyname']
),
4 => array(
    'text' => 'Phone Number',
    'val' => $_POST['phonenumber']
));

Like usual, I put $_POST['name of form']
but only name, email, message are working
and companyname, phonenumber return nothing.
I really can't figure what is the problem is


问:
Is there any way to have images adapted on it's own to a fixed resolution but shouldn't look odd?
I mean literally like there is anyway which would take a portrait image and set it to landscape sizes along with extra background like for filling so that the image will not look odd?

For instance this one is the original picture :

And now here it's distorted due to the fact that I set height & width to fixed values as :

So is there any way which would turn this portrait picture into a landscap based picture with everything showing perfectly Okay not just by changing the resolutions just but I mean literally like will resize the picture in there and then add extra background to the picture so that the picture won't look odd?

Is it possible in HTML,CSS,PHP,JS?

答:
Try this code here

html

```<code><div class="img-con">
<img src="http://www.mybligr.com/wp-content/uploads/2017/01/most-beautiful-tiger-animals-pics-images-photos-pictures-6.jpg" alt="" />
</div>
</code>```

css

```<code>.img-con
{
  height:300px;
  width:500px;
  border:1px solid black;
  position: relative;
  max-height:300px;
  max-width:500px;
  padding:30px;
}

.img-con > img
{
  position: absolute;
  left:0;
  right: 0;
  top:0;
  bottom:0;
  margin:auto;
  max-height:inherit;
  max-width:inherit;
}
</code>```

here is the reference link codepn link here

Body:
Try this code here

html

<div class="img-con">
<img src="http://www.mybligr.com/wp-content/uploads/2017/01/most-beautiful-tiger-animals-pics-images-photos-pictures-6.jpg" alt="" />
</div>

css

.img-con
{
  height:300px;
  width:500px;
  border:1px solid black;
  position: relative;
  max-height:300px;
  max-width:500px;
  padding:30px;
}

.img-con > img
{
  position: absolute;
  left:0;
  right: 0;
  top:0;
  bottom:0;
  margin:auto;
  max-height:inherit;
  max-width:inherit;
}

here is the reference link codepn link here


答:
This will resize the image to make it fit without distortion of the ratios.

.container {
width: 200px;
    height: 100px;
    background-image: url("https://i.stack.imgur.com/5ZNYR.png");
    background-size: contain;
    background-repeat: no-repeat;
    background-position: 50% 50%;
    background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='container'></div></code>```

Title: Is there any way to have images adapted on it's own to a fixed resolution but shouldn't look odd?

Body:
I mean literally like there is anyway which would take a portrait image and set it to landscape sizes along with extra background like for filling so that the image will not look odd?

For instance this one is the original picture :

And now here it's distorted due to the fact that I set height & width to fixed values as :

So is there any way which would turn this portrait picture into a landscap based picture with everything showing perfectly Okay not just by changing the resolutions just but I mean literally like will resize the picture in there and then add extra background to the picture so that the picture won't look odd?

Is it possible in HTML,CSS,PHP,JS?

Body:
This will resize the image to make it fit without distortion of the ratios.

.container {
width: 200px;
    height: 100px;
    background-image: url("https://i.stack.imgur.com/5ZNYR.png");
    background-size: contain;
    background-repeat: no-repeat;
    background-position: 50% 50%;
    background-color: blue;
}

<div class='container'></div>


问:
Access to Exchange CustomAttribute1 in Office365
Let's assume we've created a new mailbox in Exchange Online (Office365) service and we've set the "CustomAttribute1" of this mailbox using the following command:

```<code>Get-Mailbox | Set-Mailbox -CustomAttribute1 'Some value'.
</code>```

Is there any API in which those "CustomAttribute1, ..., CustomAttribute15" are exposed? I've tried many options with EWS, Microsoft Graph, AAD Graph API without success.

The only suggestions I've found related to those attributes concern the case of synchronizing them between on-permise AD and AAD (like this: https://learn.microsoft.com/en-us/azure/active-directory/connect/active-directory-aadconnectsync-feature-directory-extensions), but the account I've created is pure online.

答:
I am also not able to find the other way to retrieve the custom attribute set by the set-Mailbox.

As a workaround, you may create an extension to store the custom value and then you can retrieve them using the Microsoft Graph REST. More detail about the adding the custom data using Microsoft Graph, you can refer the link below:

Add custom data to resources using extensions

And if you want the Microsoft Graph also support to retrieve the custom attribute set by the set-Mailbox, you can submit the feedback from here.

Body:
Let's assume we've created a new mailbox in Exchange Online (Office365) service and we've set the "CustomAttribute1" of this mailbox using the following command:

Get-Mailbox | Set-Mailbox -CustomAttribute1 'Some value'.

Is there any API in which those "CustomAttribute1, ..., CustomAttribute15" are exposed? I've tried many options with EWS, Microsoft Graph, AAD Graph API without success.

The only suggestions I've found related to those attributes concern the case of synchronizing them between on-permise AD and AAD (like this: https://learn.microsoft.com/en-us/azure/active-directory/connect/active-directory-aadconnectsync-feature-directory-extensions), but the account I've created is pure online.