问:
can attributes be hidden in a simplexmlobject?
I have this simplexml object and it looks fine, but when i convert a part of it... like:
$xmlMeshHeading = $MeshHeading->asXML();

I suddenly get attributes which i can't find in the simple XML object...?
Here are some parts of the two files:

```<code>SimpleXMLObject:

[MeshHeadingList] => SimpleXMLElement Object [DescriptorName] => Acoustic Stimulation
                                (
                                    [MeshHeading] => Array
                                        (
                                            [0] => SimpleXMLElement Object
                                                (

                                                    [QualifierName] => methods
                                                )

                                            [1] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Adolescent
                                                )

                                            [2] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Age Factors
                                                )

                                            [3] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Child
                                                )

                                            [4] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Electromyography
                                                    [QualifierName] => methods
                                                )

                                            [5] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Female
                                                )

                                            [6] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Galvanic Skin Response
                                                    [QualifierName] => physiology
                                                )

                                            [7] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Humans
                                                )

                                            [8] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Male
                                                )

                                            [9] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Muscle, Skeletal
                                                    [QualifierName] => physiology
                                                )

                                            [10] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Probability
                                                )

                                            [11] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Reaction Time
                                                    [QualifierName] => physiology
                                                )

                                            [12] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Sex Factors
                                                )

                                            [13] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Startle Reaction
                                                    [QualifierName] => physiology
                                                )
</code>```

And here the asXML file it's from the same source...:

```<code> <MeshHeadingList>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Acoustic Stimulation</DescriptorName>
                <QualifierName MajorTopicYN="N">methods</QualifierName>
            </MeshHeading>

            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Adolescent</DescriptorName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Age Factors</DescriptorName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Child</DescriptorName>

            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Electromyography</DescriptorName>
                <QualifierName MajorTopicYN="Y">methods</QualifierName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Female</DescriptorName>

            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Galvanic Skin Response</DescriptorName>
                <QualifierName MajorTopicYN="N">physiology</QualifierName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Humans</DescriptorName>

            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Male</DescriptorName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Muscle, Skeletal</DescriptorName>
                <QualifierName MajorTopicYN="Y">physiology</QualifierName>

            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Probability</DescriptorName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Reaction Time</DescriptorName>
                <QualifierName MajorTopicYN="N">physiology</QualifierName>

            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Sex Factors</DescriptorName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Startle Reaction</DescriptorName>
                <QualifierName MajorTopicYN="Y">physiology</QualifierName>

            </MeshHeading>
        </MeshHeadingList>
</code>```

My question is...
1. Is there a function to "unhide" the attributes in SimpleXML?
OR
2. How can i get stuff from an XML file, like attributes and the values...?

Best,
Thijs

答:
Yes. Attributes are only returned when accessing a specific node. Per example:

```<code>$xml = new SimpleXMLElement('<xml><foo bar="baz">hello world</foo></xml>');
print_r($xml);
</code>```

Outputs:

```<code>SimpleXMLElement Object
(
    [foo] => hello world
)
</code>```

While this:

```<code>$xml = new SimpleXMLElement('<xml><foo bar="baz">hello world</foo></xml>');
print_r($xml->foo);
</code>```

Outputs:

```<code>SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [bar] => baz
        )

    [0] => hello world
)
</code>```

It's probably because of the internal structure of SimpleXMLElement. Like many built-in objects in PHP (DOMDocument, etc.), most properties aren't printed out when using print_r on them. For SimpleXML attributes, print_r won't display them unless you access a node, because it will overload to __get (kind of).

Body:
I have this simplexml object and it looks fine, but when i convert a part of it... like:
$xmlMeshHeading = $MeshHeading->asXML();

I suddenly get attributes which i can't find in the simple XML object...?
Here are some parts of the two files:

SimpleXMLObject:

[MeshHeadingList] => SimpleXMLElement Object [DescriptorName] => Acoustic Stimulation
                                (
                                    [MeshHeading] => Array
                                        (
                                            [0] => SimpleXMLElement Object
                                                (

                                                    [QualifierName] => methods
                                                )

                                            [1] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Adolescent
                                                )

                                            [2] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Age Factors
                                                )

                                            [3] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Child
                                                )

                                            [4] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Electromyography
                                                    [QualifierName] => methods
                                                )

                                            [5] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Female
                                                )

                                            [6] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Galvanic Skin Response
                                                    [QualifierName] => physiology
                                                )

                                            [7] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Humans
                                                )

                                            [8] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Male
                                                )

                                            [9] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Muscle, Skeletal
                                                    [QualifierName] => physiology
                                                )

                                            [10] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Probability
                                                )

                                            [11] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Reaction Time
                                                    [QualifierName] => physiology
                                                )

                                            [12] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Sex Factors
                                                )

                                            [13] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Startle Reaction
                                                    [QualifierName] => physiology
                                                )

And here the asXML file it's from the same source...:

 <MeshHeadingList>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Acoustic Stimulation</DescriptorName>
                <QualifierName MajorTopicYN="N">methods</QualifierName>
            </MeshHeading>

            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Adolescent</DescriptorName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Age Factors</DescriptorName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Child</DescriptorName>

            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Electromyography</DescriptorName>
                <QualifierName MajorTopicYN="Y">methods</QualifierName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Female</DescriptorName>

            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Galvanic Skin Response</DescriptorName>
                <QualifierName MajorTopicYN="N">physiology</QualifierName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Humans</DescriptorName>

            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Male</DescriptorName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Muscle, Skeletal</DescriptorName>
                <QualifierName MajorTopicYN="Y">physiology</QualifierName>

            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Probability</DescriptorName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Reaction Time</DescriptorName>
                <QualifierName MajorTopicYN="N">physiology</QualifierName>

            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Sex Factors</DescriptorName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Startle Reaction</DescriptorName>
                <QualifierName MajorTopicYN="Y">physiology</QualifierName>

            </MeshHeading>
        </MeshHeadingList>

My question is...
1. Is there a function to "unhide" the attributes in SimpleXML?
OR
2. How can i get stuff from an XML file, like attributes and the values...?

Best,
Thijs

Body:
Yes. Attributes are only returned when accessing a specific node. Per example:

$xml = new SimpleXMLElement('<xml><foo bar="baz">hello world</foo></xml>');
print_r($xml);

Outputs:

SimpleXMLElement Object
(
    [foo] => hello world
)

While this:

$xml = new SimpleXMLElement('<xml><foo bar="baz">hello world</foo></xml>');
print_r($xml->foo);

Outputs:

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [bar] => baz
        )

    [0] => hello world
)

It's probably because of the internal structure of SimpleXMLElement. Like many built-in objects in PHP (DOMDocument, etc.), most properties aren't printed out when using print_r on them. For SimpleXML attributes, print_r won't display them unless you access a node, because it will overload to __get (kind of).


来源: stackexchange

问:
How to prevent inline-block divs from wrapping?

jsFiddle demo

I want the divs to:

Wrap their content.

Stay in their originally associated line, essentially without wrapping.

Basically, the tables are stacking below each other, when they can't stay on screen. I would rather they become hidden off screen.

I've tried adding overflow: hidden; to the main layout style. I do not want to fix a width for each div. It needs to fit content in.

.layout {
  -moz-border-radius: 15px;
  border-radius: 15px;
  vertical-align: top;
  display: inline-block;
}

.layoutbacking {
  -moz-border-radius: 15px;
  border-radius: 15px;
  padding: 5px;
  margin: 5px;
  background: #CCCCCC;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="layout" style="background: #222222; width: 100%">
  <div>
    <div class="layout layoutbacking">
      <table>
        <tr>
          <th>header 1</th>
          <th>header 2</th>
          <th>header 3</th>
          <th>header 4</th>
        </tr>
        <tr>
          <td>data 1</td>
          <td>data 2</td>
          <td>data 3</td>
          <td>data 4</td>
        </tr>
        <tr>
          <td>data 1</td>
          <td>data 2</td>
          <td>data 3</td>
          <td>data 4</td>
        </tr>
        <tr>
          <td>data 1</td>
          <td>data 2</td>
          <td>data 3</td>
          <td>data 4</td>
        </tr>
      </table>
    </div>
    <div class="layout">
      <div class="layout layoutbacking">
        <table>
          <tr>
            <th>header 1</th>
            <th>header 2</th>
            <th>header 3</th>
            <th>header 4</th>
          </tr>
          <tr>
            <td>data 1</td>
            <td>data 2</td>
            <td>data 3</td>
            <td>data 4</td>
          </tr>
        </table>
      </div>
      <br />
      <div class="layout layoutbacking">
        <table>
          <tr>
            <th>header 1</th>
            <th>header 2</th>
            <th>header 3</th>
            <th>header 4</th>
          </tr>
          <tr>
            <td>data 1</td>
            <td>data 2</td>
            <td>data 3</td>
            <td>data 4</td>
          </tr>
        </table>
      </div>
    </div>
  </div>
  <div>
    <div class="layout layoutbacking">
      <table>
        <tr>
          <th>header 1</th>
          <th>header 2</th>
          <th>header 3</th>
          <th>header 4</th>
        </tr>
        <tr>
          <td>data 1</td>
          <td>data 2</td>
          <td>data 3</td>
          <td>data 4</td>
        </tr>
      </table>
    </div>
    <div class="layout layoutbacking">
      <table>
        <tr>
          <th>header 1</th>
          <th>header 2</th>
          <th>header 3</th>
          <th>header 4</th>
        </tr>
        <tr>
          <td>data 1</td>
          <td>data 2</td>
          <td>data 3</td>
          <td>data 4</td>
        </tr>
      </table>
    </div></code>```

答:
This will stop text wrapping, and keep it inline</p>

```<code>.leftContent { float: left; }
.rightContent { overflow: hidden; }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
jsFiddle demo

I want the divs to:

Wrap their content.

Stay in their originally associated line, essentially without wrapping.

Basically, the tables are stacking below each other, when they can't stay on screen. I would rather they become hidden off screen.

I've tried adding overflow: hidden; to the main layout style. I do not want to fix a width for each div. It needs to fit content in.

.layout {
  -moz-border-radius: 15px;
  border-radius: 15px;
  vertical-align: top;
  display: inline-block;
}

.layoutbacking {
  -moz-border-radius: 15px;
  border-radius: 15px;
  padding: 5px;
  margin: 5px;
  background: #CCCCCC;
}

          header 1
          header 2
          header 3
          header 4

          data 1
          data 2
          data 3
          data 4

          data 1
          data 2
          data 3
          data 4

          data 1
          data 2
          data 3
          data 4

            header 1
            header 2
            header 3
            header 4

            data 1
            data 2
            data 3
            data 4

            header 1
            header 2
            header 3
            header 4

            data 1
            data 2
            data 3
            data 4

          header 1
          header 2
          header 3
          header 4

          data 1
          data 2
          data 3
          data 4

          header 1
          header 2
          header 3
          header 4

          data 1
          data 2
          data 3
          data 4

Body:
This will stop text wrapping, and keep it inline

.leftContent { float: left; }
.rightContent { overflow: hidden; }


问:
Python: parsing a string of concatenated ascending integers
The objective is to parse the output of an ill-behaving program which concatenates a list of numbers, e.g., 3, 4, 5, into a string "345", without any non-number separating the numbers. I also know that the list is sorted in ascending order.

I came up with the following solution which reconstructs the list from a string:

```<code>a = '3456781015203040'
numlist = []

numlist.append(int(a[0]))

i = 1
while True:
    j = 1
    while True:
        if int(a[i:i+j]) <= numlist[-1]:
            j = j + 1
        else:
            numlist.append(int(a[i:i+j]))
            i = i + j
            break
    if i >= len(a):
        break
</code>```

This works, but I have a feeling that the solution reflects too much the fact that I have been trained in Pascal, decades ago.  Is there a better or more pythonic way to do it?

I am aware that the problem is ill-posed, i.e., I could start with '34' as the initial element and get a different solution (or possibly end up with remaining trailing numeral characters which don't form the next element of the list).

答:
little modification which allows to parse "7000000000001" data and give the best output (max list size)</p>

```<code>a = 30000001
def numbers(a,n):
    current_num, i = 0, 0
    while True:
        while i+n <= len(a) and int(a[i:i+n]) <= current_num:n += 1
        if i+2*n>len(a):current_num = int(a[i:]);yield current_num; return
        elif i+n <= len(a):current_num = int(a[i:i+n]);yield current_num;i += n
        else: return
        print(current_num)
for n in range(1,len(a)):
    l = list(numbers(a,n))
    if "".join(map(str,l)) == a:print (l)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The objective is to parse the output of an ill-behaving program which concatenates a list of numbers, e.g., 3, 4, 5, into a string "345", without any non-number separating the numbers. I also know that the list is sorted in ascending order.

I came up with the following solution which reconstructs the list from a string:

a = '3456781015203040'
numlist = []

numlist.append(int(a[0]))

i = 1
while True:
    j = 1
    while True:
        if int(a[i:i+j]) <= numlist[-1]:
            j = j + 1
        else:
            numlist.append(int(a[i:i+j]))
            i = i + j
            break
    if i >= len(a):
        break

This works, but I have a feeling that the solution reflects too much the fact that I have been trained in Pascal, decades ago.  Is there a better or more pythonic way to do it?

I am aware that the problem is ill-posed, i.e., I could start with '34' as the initial element and get a different solution (or possibly end up with remaining trailing numeral characters which don't form the next element of the list).

Body:
little modification which allows to parse "7000000000001" data and give the best output (max list size)

a = 30000001
def numbers(a,n):
    current_num, i = 0, 0
    while True:
        while i+n <= len(a) and int(a[i:i+n]) <= current_num:n += 1
        if i+2*n>len(a):current_num = int(a[i:]);yield current_num; return
        elif i+n <= len(a):current_num = int(a[i:i+n]);yield current_num;i += n
        else: return
        print(current_num)
for n in range(1,len(a)):
    l = list(numbers(a,n))
    if "".join(map(str,l)) == a:print (l)


问:
Display value from "input range" in another element gives "undefined"
This has been asked before, but I have found no solid, working, plain JS solution, all solutions out there are using frameworks or just do not work.

I simply want to get the value of a input "range" values and have them displayed in a span element.

I get undefined with no error in the console.

Here is the JS code:

```<code>document.getElementById("height").addEventListener("input",
sliderChange(this.value));

function sliderChange(val) {
document.getElementById('yourHeight').innerHTML = val;
}
</code>```

Further, I want to store the user input and use for another function to calculate the final results(this function is not there yet).

Here is the link:

https://codepen.io/damianocel/pen/ZyRogX

答:
In this code document.getElementById("height").addEventListener("input", sliderChange(this.value)), this refers to the global window object and not the input, that's why this.value is undefined.

You need to pass a listener callback function to the addEventListener so it will have its own scope and this will refer to your input:

```<code>document.getElementById("height").addEventListener("input", function(){ sliderChange(this.value)} );
</code>```

This is the updated working Demo.

Body:
This has been asked before, but I have found no solid, working, plain JS solution, all solutions out there are using frameworks or just do not work.

I simply want to get the value of a input "range" values and have them displayed in a span element.

I get undefined with no error in the console.

Here is the JS code:

document.getElementById("height").addEventListener("input",
sliderChange(this.value));

function sliderChange(val) {
document.getElementById('yourHeight').innerHTML = val;
}

Further, I want to store the user input and use for another function to calculate the final results(this function is not there yet).

Here is the link:

https://codepen.io/damianocel/pen/ZyRogX

Body:
In this code document.getElementById("height").addEventListener("input", sliderChange(this.value)), this refers to the global window object and not the input, that's why this.value is undefined.

You need to pass a listener callback function to the addEventListener so it will have its own scope and this will refer to your input:

document.getElementById("height").addEventListener("input", function(){ sliderChange(this.value)} );

This is the updated working Demo.


问:
AutoCompleteTextView force to show all items
There is a moment in my app, that I need to force to show all items in the suggestion list, no matter what the user has typed. How can I do that?

I tried to do something with filtering, but for me as a beginner filtering is just way too complicated, I tried searching beginners tutorial for filtering without any luck. Maybe, there is a simpler way to force to show all the suggestion items?

EDIT:
Basically what was my idea, is that, when user types something whats not in the list, it shows all the available options he can have.

I've found the best way of checking weather the ACTV is beign shown or not, but onTextChangeEvent I compare the user typed text with my list, and then if no elements have been found show full list.

```<code>public void onTextChanged(CharSequence s, int start, int before, int count)
         {
           final EditText editText = (EditText) findViewById(R.id.vardsUserInput);
            String strValue = editText.getText().toString().toUpperCase();
            String temp;
            int Cc=0; //my count variable
            for(int i=0; i<vardi.length; i++)
            {
                temp = vardi[i].toUpperCase();
                if(temp.startsWith(strValue.toUpperCase()))
                {
                    Log.d("testing",vardi[i]);
                    Cc++;
                }
            }
        if(Cc == 0)
        {
        //Show all the available options
    textView.showDropDown();
         }
}
</code>```

答:
This is what worked for me:</p>

```<code>    public class CustomAutoCompleteTextView extends AutoCompleteTextView {
    public CustomAutoCompleteTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean enoughToFilter() {
        return true;
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
        if (focused) {
            performFiltering(getText(), 0);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        this.showDropDown();
        return super.onTouchEvent(event);
    }
}
</code>```

Body:
There is a moment in my app, that I need to force to show all items in the suggestion list, no matter what the user has typed. How can I do that?

I tried to do something with filtering, but for me as a beginner filtering is just way too complicated, I tried searching beginners tutorial for filtering without any luck. Maybe, there is a simpler way to force to show all the suggestion items?

EDIT:
Basically what was my idea, is that, when user types something whats not in the list, it shows all the available options he can have.

I've found the best way of checking weather the ACTV is beign shown or not, but onTextChangeEvent I compare the user typed text with my list, and then if no elements have been found show full list.

public void onTextChanged(CharSequence s, int start, int before, int count)
         {
           final EditText editText = (EditText) findViewById(R.id.vardsUserInput);
            String strValue = editText.getText().toString().toUpperCase();
            String temp;
            int Cc=0; //my count variable
            for(int i=0; i<vardi.length; i++)
            {
                temp = vardi[i].toUpperCase();
                if(temp.startsWith(strValue.toUpperCase()))
                {
                    Log.d("testing",vardi[i]);
                    Cc++;
                }
            }
        if(Cc == 0)
        {
        //Show all the available options
    textView.showDropDown();
         }
}

Body:
This is what worked for me:

    public class CustomAutoCompleteTextView extends AutoCompleteTextView {
    public CustomAutoCompleteTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean enoughToFilter() {
        return true;
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
        if (focused) {
            performFiltering(getText(), 0);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        this.showDropDown();
        return super.onTouchEvent(event);
    }
}


问:
.NET Billboard Control
I still can't seem to get this to work.  If anyone else has any ideas I would really appreciate it.  The two websites whose controls I am trying to duplicate is mtv.com and nba.com.  I couldn't get jCarousel or the adrotator to have four images that rotate.  One large image and three small images.  If anyone has any ideas please let me know.

Hello,

Does anyone know where I can find a billboard control?  I'm not sure what it's really called but I'm going to call it a billboard control.  Examples of these are at the three below websites.  Basically what I'm talking about is anywhere from 3 to 5 images or html files that rotate every couple of seconds with a preview of these images/html files to the side or below.  I am looking for something I can use with C# .net.  Any help would be much appreciated.

espn.go.com
mtv.com
nba.com

Thanks

答: This might help...uses AdRotator

ContentLicense: CC BY-SA 2.5

Title: .NET Billboard Control

Body: This might help...uses AdRotator


问:
Should response of rest api contain ID of a resource?
What is a good practice or a standard in rest api, should a server response contain ID of a resource?

For example this response contains id of a resource

```<code>GET /users/5
{
"user_id": 5
"first_name" : "John",
"last_name" : "Doe",
"minutes_active": 10
}
</code>```

And this assumes that an id of a resource is one stated in the url of a request

```<code>GET /users/5
{
"first_name" : "John",
"last_name" : "Doe",
"minutes_active": 10
}
</code>```

答:
this assumes that an id of a resource is one stated in the url of a request

From the perspective of the client, URI are opaque; if you are communicating information to the client by putting it into a URI that they are expected to parse, then you have lost the plot.

If your API needs to make the id available to the client, then the id should be included in the representation of the resource.

What do you mean by "URI are opaque; if you are communicating information to the client by putting it into a URI that they are expected to parse..."? It looks to me like the client created the URI, so ostensibly it already knows the ID...?

Typically, a REST API client follows links, rather than constructing the URI.  There's nothing in the HTTP request that tells you how the client came to choose that particular URI -- it might be a bookmark, or a link in some other representation, or the result of filling in a form.

Body:
What is a good practice or a standard in rest api, should a server response contain ID of a resource?

For example this response contains id of a resource

GET /users/5
{
"user_id": 5
"first_name" : "John",
"last_name" : "Doe",
"minutes_active": 10
}

And this assumes that an id of a resource is one stated in the url of a request

GET /users/5
{
"first_name" : "John",
"last_name" : "Doe",
"minutes_active": 10
}


问:
Running code after Spring Boot starts
I want to run code after my spring-boot app starts to monitor a directory for changes.

I have tried running a new thread but the @Autowired services have not been set at that point.

I have been able to find ApplicationPreparedEvent, which fires before the @Autowired annotations are set.  Ideally I would like the event to fire once the application is ready to process http requests.

Is there a better event to use, or a better way of running code after the application is live in spring-boot?

答:
It is as simple as this:

```<code>@EventListener(ApplicationReadyEvent.class)
public void doSomethingAfterStartup() {
    System.out.println("hello world, I have just started up");
}
</code>```

Tested on version 1.5.1.RELEASE

Title: Running code after Spring Boot starts

Body:
It is as simple as this:

@EventListener(ApplicationReadyEvent.class)
public void doSomethingAfterStartup() {
    System.out.println("hello world, I have just started up");
}

Tested on version 1.5.1.RELEASE


问:
How to wrap existing object instance into DispatchProxy?
I'm looking for RealProxy replacement in .NET Core, and this issue forwards me to DispatchProxy.

It has simple API, but it's unclear, how to wrap existing object into proxy.

E.g., having this interface:

```<code>interface IFoo
{
    string Bar(int boo);
}
</code>```

and this implementation:

```<code>class FooImpl : IFoo
{
    public string Bar(int boo)
    {
        return $"Value {boo} was passed";
    }
}
</code>```

how to get what I want?

```<code>class Program
{
    static void Main(string[] args)
    {
        var fooInstance = new FooImpl();
        var proxy = DispatchProxy.Create<IFoo, FooProxy>();

        var s = proxy.Bar(123);

        Console.WriteLine(s);
    }
}

class FooProxy : DispatchProxy
{
    protected override object Invoke(MethodInfo targetMethod, object[] args)
    {
        return targetMethod.Invoke(/* I need fooInstance here */, args);
    }
}
</code>```

Since DispatchProxy descendants must have parameterless constructor, the only idea I have is to invent some method, like this:

```<code>class FooProxy : DispatchProxy
{
    private object target;

    public void SetTarget(object target)
    {
        this.target = target;
    }

    protected override object Invoke(MethodInfo targetMethod, object[] args)
    {
        return targetMethod.Invoke(target, args);
    }
}
</code>```

and use it this way:

```<code>var fooInstance = new FooImpl();
var proxy = DispatchProxy.Create<IFoo, FooProxy>();

((FooProxy)proxy).SetTarget(fooInstance);

// the rest of code...
</code>```

Is this correct approach?

答:
You are right that there is no other option here than to cast the generated IFoo to the known proxy type (FooProxy) and use a custom method or property on FooProxy. There is no public API to add constructor arguments or return the proxy as the implementation type. However, DispatchProxy.Create() will return an instance of a subclass of FooProxy whose type is generated at runtime via reflection and IL emitting.

If you are looking at other ways to quickly wrap an implementation and replace interface methods / virtual methods, I suggest using mocking frameworks instead (FakeItEasy, Moq, NSubstitute etc.).

Body:
I'm looking for RealProxy replacement in .NET Core, and this issue forwards me to DispatchProxy.

It has simple API, but it's unclear, how to wrap existing object into proxy.

E.g., having this interface:

interface IFoo
{
    string Bar(int boo);
}

and this implementation:

class FooImpl : IFoo
{
    public string Bar(int boo)
    {
        return $"Value {boo} was passed";
    }
}

how to get what I want?

class Program
{
    static void Main(string[] args)
    {
        var fooInstance = new FooImpl();
        var proxy = DispatchProxy.Create<IFoo, FooProxy>();

        var s = proxy.Bar(123);

        Console.WriteLine(s);
    }
}

class FooProxy : DispatchProxy
{
    protected override object Invoke(MethodInfo targetMethod, object[] args)
    {
        return targetMethod.Invoke(/* I need fooInstance here */, args);
    }
}

Since DispatchProxy descendants must have parameterless constructor, the only idea I have is to invent some method, like this:

class FooProxy : DispatchProxy
{
    private object target;

    public void SetTarget(object target)
    {
        this.target = target;
    }

    protected override object Invoke(MethodInfo targetMethod, object[] args)
    {
        return targetMethod.Invoke(target, args);
    }
}

and use it this way:

var fooInstance = new FooImpl();
var proxy = DispatchProxy.Create<IFoo, FooProxy>();

((FooProxy)proxy).SetTarget(fooInstance);

// the rest of code...

Is this correct approach?


问:
Uploading a file in Web view
I am trying to upload a file inside a web view. I am using angular file upload in the UI.

But after the page load, nothing happens in the webview. The ngf-select dont seems to be responding.

TIA.

答:
Check if these are added in the manifest file</p>

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<preference name="AndroidPersistentFileLocation" value="Compatibility" />
</code>```

Title: Uploading a file in Web view

Body:
Check if these are added in the manifest file

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<preference name="AndroidPersistentFileLocation" value="Compatibility" />


问:
How to split `NSmutableArray` array array to chunks swift 3?
```<code>NSMutableArray *sample;
</code>```

I have an NSmutableArray, and I want to split it into chunks. I have tried checking the internet didn't find the solution for it. I got the link to split integer array.

答:
How about this which is more Swifty?

```<code>let integerArray = [1,2,3,4,5,6,7,8,9,10]
let stringArray = ["a", "b", "c", "d", "e", "f"]
let anyObjectArray: [Any] = ["a", 1, "b", 2, "c", 3]

extension Array {
    func chunks(_ chunkSize: Int) -> [[Element]] {
        return stride(from: 0, to: self.count, by: chunkSize).map {
            Array(self[$0..<Swift.min($0 + chunkSize, self.count)])
        }
    }
}

integerArray.chunks(2) //[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
stringArray.chunks(3) //[["a", "b", "c"], ["d", "e", "f"]]
anyObjectArray.chunks(2) //[["a", 1], ["b", 2], ["c", 3]]
</code>```

To Convert NSMutableArray to Swift Array:

```<code>let nsarray  = NSMutableArray(array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
if let swiftArray = nsarray as NSArray as? [Int] {
    swiftArray.chunks(2) //[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
}
</code>```

If you wanna insist to use NSArray, then:

```<code>let nsarray  = NSMutableArray(array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

extension NSArray {
    func chunks(_ chunkSize: Int) -> [[Element]] {
        return stride(from: 0, to: self.count, by: chunkSize).map {
            self.subarray(with: NSRange(location: $0, length: Swift.min(chunkSize, self.count - $0)))
        }
    }
}

nsarray.chunks(3) //[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
</code>```

Body:
NSMutableArray *sample;

I have an NSmutableArray, and I want to split it into chunks. I have tried checking the internet didn't find the solution for it. I got the link to split integer array.

Body:
How about this which is more Swifty?

let integerArray = [1,2,3,4,5,6,7,8,9,10]
let stringArray = ["a", "b", "c", "d", "e", "f"]
let anyObjectArray: [Any] = ["a", 1, "b", 2, "c", 3]

extension Array {
    func chunks(_ chunkSize: Int) -> [[Element]] {
        return stride(from: 0, to: self.count, by: chunkSize).map {
            Array(self[$0..<Swift.min($0 + chunkSize, self.count)])
        }
    }
}

integerArray.chunks(2) //[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
stringArray.chunks(3) //[["a", "b", "c"], ["d", "e", "f"]]
anyObjectArray.chunks(2) //[["a", 1], ["b", 2], ["c", 3]]

To Convert NSMutableArray to Swift Array:

let nsarray  = NSMutableArray(array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
if let swiftArray = nsarray as NSArray as? [Int] {
    swiftArray.chunks(2) //[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
}

If you wanna insist to use NSArray, then:

let nsarray  = NSMutableArray(array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

extension NSArray {
    func chunks(_ chunkSize: Int) -> [[Element]] {
        return stride(from: 0, to: self.count, by: chunkSize).map {
            self.subarray(with: NSRange(location: $0, length: Swift.min(chunkSize, self.count - $0)))
        }
    }
}

nsarray.chunks(3) //[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]


问:
Set reason for thrown bad request in Yii 2
I'm writing an API and I have to throw HTTP 400 bad request like below

```<code>if (!$model->validate()) {
    throw new BadRequestHttpException;
}
</code>```

and it works fine meaning that it displays the default HTTP 400 page (I have no views defined because I'm building an API)

What I would like to achieve is to give some reason for the bad request error thrown so that who is using the API knows why his request is bad.

Tried the following but with no success

```<code>if (!$model->validate()) {
    Yii::$app->response->content = 'This is the reason for your bad request';
    throw new BadRequestHttpException;
}
</code>```

any ideas?

答:
you can send your reason like this</p>

```<code>if (!$model->validate()) {
    throw new BadRequestHttpException('This is the reason for your bad request');
}
</code>```

Body:
I'm writing an API and I have to throw HTTP 400 bad request like below

if (!$model->validate()) {
    throw new BadRequestHttpException;
}

and it works fine meaning that it displays the default HTTP 400 page (I have no views defined because I'm building an API)

What I would like to achieve is to give some reason for the bad request error thrown so that who is using the API knows why his request is bad.

Tried the following but with no success

if (!$model->validate()) {
    Yii::$app->response->content = 'This is the reason for your bad request';
    throw new BadRequestHttpException;
}

any ideas?

Body:
you can send your reason like this

if (!$model->validate()) {
    throw new BadRequestHttpException('This is the reason for your bad request');
}


问:
How to create a .csv file from a MongoDB tweet database using Python
I have created a database in MongoDB with tweets and their sentimental analisys based on tweepy and NLTK. After some experience with Mongoexport to create a CSV file with a dataset from this database stored in the MongoDB, I decided to explore other options more flexibles (specially with other delimiters than "coma"), for example, using the Python itself to generate the CSV file. So far I could print the dataset successfully, correcting the ASCII and Unicode problems and using "|" as delimiter, however I am suffering to create a CSV file from the printing results. The code so far is as follow:

```<code>import json
import csv
from pymongo import MongoClient

client = MongoClient('localhost', 27017)
db = client['twitter_db_stream_1']
collection = db['twitter_collection']
data_python = collection.find({"user.location":{"$exists":True},"user.location":{"$ne":"null"}},{"created_at":1,"text":1,"user.name":1,"user.location":1,"geo.coordinates":1,"sentiment_value":1,"confidence_value":1})

for data in data_python:
    print(data['created_at'],'|',data['text'].encode('utf8'),'|',data['user']['name'].encode('utf8'),'|',data['user']['location'],'|',data['sentiment_value'],'|',data['confidence_value'])
</code>```

The printing results are as follow:

```<code>Tue Apr 18 06:51:58 +0000 2017 | b'Samsung Galaxy S8 International Giveaway @androidauth #giveaway | b'Matt Torok' | None | pos | 1.0
</code>```

I tried to add the following piece of code using csv.writer, based on some examples from tutorias, however it is not working...

```<code>csv_file = open('Sentiment_Analisys.csv', 'wb')
writer = csv.writer(csv_file)

fields = [["created_at"],["text"],["user.name"],["user.location"],["sentiment_value"],["confidential_value"]] #field names
writer.writerow(fields)

for data in data_python:
    writer.writerow(data['created_at'],data['text'].encode('utf8'),data['user']['name'].encode('utf8'),data['user']['location'],data['sentiment_value'],data['confidence_value'])

csv_file.close()
</code>```

Please, could someone give me some guidance in how to create this CSV file from the printing results above?

Thanks a lot!

答:
You appear to have copied a Python 2.x example, but are writing Python 3.x code. The CSV usage is slightly different between these two versions. Also, it is preferable to use a with statement whilst dealing with files, which avoids the need to explicitly close the file at the end.

writerow() takes a list of strings. Your field names were defined as a list of lists, and your data writerow() needed to be converted to use a list as follows:

```<code>field_names = ["created_at", "text", "user.name", "user.location", "sentiment_value", "confidential_value"]

with open('Sentiment_Analisys.csv', 'w', newline='') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(field_names)

    for data in data_python:
        csv_output.writerow(
            [
            data['created_at'],data['text'].encode('utf8', 'ignore'),
            data['user']['name'].encode('utf8'),
            data['user']['location'],
            data['sentiment_value'],
            data['confidence_value']
            ])
</code>```

Body:
I have created a database in MongoDB with tweets and their sentimental analisys based on tweepy and NLTK. After some experience with Mongoexport to create a CSV file with a dataset from this database stored in the MongoDB, I decided to explore other options more flexibles (specially with other delimiters than "coma"), for example, using the Python itself to generate the CSV file. So far I could print the dataset successfully, correcting the ASCII and Unicode problems and using "|" as delimiter, however I am suffering to create a CSV file from the printing results. The code so far is as follow:

import json
import csv
from pymongo import MongoClient

client = MongoClient('localhost', 27017)
db = client['twitter_db_stream_1']
collection = db['twitter_collection']
data_python = collection.find({"user.location":{"$exists":True},"user.location":{"$ne":"null"}},{"created_at":1,"text":1,"user.name":1,"user.location":1,"geo.coordinates":1,"sentiment_value":1,"confidence_value":1})

for data in data_python:
    print(data['created_at'],'|',data['text'].encode('utf8'),'|',data['user']['name'].encode('utf8'),'|',data['user']['location'],'|',data['sentiment_value'],'|',data['confidence_value'])

The printing results are as follow:

Tue Apr 18 06:51:58 +0000 2017 | b'Samsung Galaxy S8 International Giveaway @androidauth #giveaway | b'Matt Torok' | None | pos | 1.0

I tried to add the following piece of code using csv.writer, based on some examples from tutorias, however it is not working...

csv_file = open('Sentiment_Analisys.csv', 'wb')
writer = csv.writer(csv_file)

fields = [["created_at"],["text"],["user.name"],["user.location"],["sentiment_value"],["confidential_value"]] #field names
writer.writerow(fields)

for data in data_python:
    writer.writerow(data['created_at'],data['text'].encode('utf8'),data['user']['name'].encode('utf8'),data['user']['location'],data['sentiment_value'],data['confidence_value'])

csv_file.close()

Please, could someone give me some guidance in how to create this CSV file from the printing results above?

Thanks a lot!

Body:
You appear to have copied a Python 2.x example, but are writing Python 3.x code. The CSV usage is slightly different between these two versions. Also, it is preferable to use a with statement whilst dealing with files, which avoids the need to explicitly close the file at the end.

writerow() takes a list of strings. Your field names were defined as a list of lists, and your data writerow() needed to be converted to use a list as follows:

field_names = ["created_at", "text", "user.name", "user.location", "sentiment_value", "confidential_value"]

with open('Sentiment_Analisys.csv', 'w', newline='') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(field_names)

    for data in data_python:
        csv_output.writerow(
            [
            data['created_at'],data['text'].encode('utf8', 'ignore'),
            data['user']['name'].encode('utf8'),
            data['user']['location'],
            data['sentiment_value'],
            data['confidence_value']
            ])


问:
How to iterate through a column in an Excel application through C# Console?
I have created a Console Application that reads from an Excel file. I want to take all of the document numbers and place it in an array for searching purposes.
I am able to find the cell that contains the data "DocumentNumber" e.g. $F$5. How can I iterate through rows within column F?
I have the following code:

```<code>public static void Main(string[] args)
    {
        string address;
        string next;
        try
        {
            Excel.ApplicationClass excel = new Excel.ApplicationClass();
            Excel.Workbook workbook = excel.Workbooks.Open(@"D:\sample.xls", Missing.Value, Missing.Value,
                Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                Missing.Value, Missing.Value);
            Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Sheets["Sheet1"];
            Excel.Range docNumber = worksheet.Cells.Find("DocumentNumber", worksheet.Cells[1, 1], Excel.XlFindLookIn.xlValues,
                Excel.XlLookAt.xlPart, Missing.Value, Excel.XlSearchDirection.xlNext,
                false, Missing.Value, Missing.Value);

            if(docNumber != null){
                address = docNumber.get_Address(true, true, Excel.XlReferenceStyle.xlA1, Missing.Value, Missing.Value);
                Console.WriteLine(address);

            }
        }
        catch (Exception err)
        {
            Console.WriteLine(err.Message);
        }
    }
</code>```

Thanks in advance.

答: Wouldn't it be easier to read the data using OLEDB?  Cleaner syntax, then you can foreach a DataTable that is returned.</p>

Body:
I have created a Console Application that reads from an Excel file. I want to take all of the document numbers and place it in an array for searching purposes.
I am able to find the cell that contains the data "DocumentNumber" e.g. $F$5. How can I iterate through rows within column F?
I have the following code:

public static void Main(string[] args)
    {
        string address;
        string next;
        try
        {
            Excel.ApplicationClass excel = new Excel.ApplicationClass();
            Excel.Workbook workbook = excel.Workbooks.Open(@"D:\sample.xls", Missing.Value, Missing.Value,
                Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                Missing.Value, Missing.Value);
            Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Sheets["Sheet1"];
            Excel.Range docNumber = worksheet.Cells.Find("DocumentNumber", worksheet.Cells[1, 1], Excel.XlFindLookIn.xlValues,
                Excel.XlLookAt.xlPart, Missing.Value, Excel.XlSearchDirection.xlNext,
                false, Missing.Value, Missing.Value);

            if(docNumber != null){
                address = docNumber.get_Address(true, true, Excel.XlReferenceStyle.xlA1, Missing.Value, Missing.Value);
                Console.WriteLine(address);

            }
        }
        catch (Exception err)
        {
            Console.WriteLine(err.Message);
        }
    }

Thanks in advance.


问:
Scrapy multiple requests and fill single item
I need to make 2 request to different urls and put that information to the same item. I have tried this method, but the result is written in different rows. The callbacks returns item. I have tried many methods but none seems to work.

```<code>def parse_companies(self, response):
    data = json.loads(response.body)
    if data:
        item = ThalamusItem()
        for company in data:
            comp_id = company["id"]

            url = self.request_details_URL + str(comp_id) + ".json"
            request = Request(url, callback=self.parse_company_details)
            request.meta['item'] = item
            yield request

            url2 = self.request_contacts + str(comp_id)
            yield Request(url2, callback=self.parse_company_contacts, meta={'item': item})
</code>```

答:
Since scrapy is asynchronious you need to chain your requests manually. For transfering data between requests you can use Request's meta attribute:

```<code>def parse(self, response):
    item = dict()
    item['name'] = 'foobar'
    yield request('http://someurl.com', self.parse2,
                  meta={'item': item})

def parse2(self, response):
    print(response.meta['item'])
    # {'name': 'foobar'}
</code>```

In your case you end up with a split chain when you should have one continuous chain.

Your code should look something like this:

```<code>def parse_companies(self, response):
    data = json.loads(response.body)
    if not data:
        return
    for company in data:
        item = ThalamusItem()
        comp_id = company["id"]
        url = self.request_details_URL + str(comp_id) + ".json"
        url2 = self.request_contacts + str(comp_id)
        request = Request(url, callback=self.parse_details,
                          meta={'url2': url2, 'item': item})
        yield request

def parse_details(self, response):
    item = response.meta['item']
    url2 = response.meta['url2']
    item['details'] = ''  # add details
    yield Request(url2, callback=self.parse_contacts, meta={'item': item})

def parse_contacts(self, response):
    item = response.meta['item']
    item['contacts'] = ''  # add details
    yield item
</code>```

Body:
I need to make 2 request to different urls and put that information to the same item. I have tried this method, but the result is written in different rows. The callbacks returns item. I have tried many methods but none seems to work.

def parse_companies(self, response):
    data = json.loads(response.body)
    if data:
        item = ThalamusItem()
        for company in data:
            comp_id = company["id"]

            url = self.request_details_URL + str(comp_id) + ".json"
            request = Request(url, callback=self.parse_company_details)
            request.meta['item'] = item
            yield request

            url2 = self.request_contacts + str(comp_id)
            yield Request(url2, callback=self.parse_company_contacts, meta={'item': item})

Body:
Since scrapy is asynchronious you need to chain your requests manually. For transfering data between requests you can use Request's meta attribute:

def parse(self, response):
    item = dict()
    item['name'] = 'foobar'
    yield request('http://someurl.com', self.parse2,
                  meta={'item': item})

def parse2(self, response):
    print(response.meta['item'])
    # {'name': 'foobar'}

In your case you end up with a split chain when you should have one continuous chain.

Your code should look something like this:

def parse_companies(self, response):
    data = json.loads(response.body)
    if not data:
        return
    for company in data:
        item = ThalamusItem()
        comp_id = company["id"]
        url = self.request_details_URL + str(comp_id) + ".json"
        url2 = self.request_contacts + str(comp_id)
        request = Request(url, callback=self.parse_details,
                          meta={'url2': url2, 'item': item})
        yield request

def parse_details(self, response):
    item = response.meta['item']
    url2 = response.meta['url2']
    item['details'] = ''  # add details
    yield Request(url2, callback=self.parse_contacts, meta={'item': item})

def parse_contacts(self, response):
    item = response.meta['item']
    item['contacts'] = ''  # add details
    yield item


问:
Is it possible to pause/resume the default music player from c# (maybe using the windows API)
Is there a Windows API command to pause and resume the default/current media player? If so what is it, or do I need to spoof a keyboard input somehow?

My reasoning... multimedia keyboards (or in fact almost any modern USB keyboard) have pause buttons which seem to pause most (commercial) music or video players (Windows media player, Spotify player and WinDVD all respect the command on my current windows 7 and win XP machines).

I'm guessing the keyboard drivers aren't aware of all these apps (besides which, I haven't installed a multimedia keyboard driver in about a decade), so some standard event is being raised which the apps are respondind to? What's that event, and can I raise it (or cause it to be raised) myself from c#?

At worst there must be a standard input from the USB Human Interface Device standard? Could I spoof that?

答:
You might consider simulating the multimedia key press event in Windows. It's not guaranteed to work for all media software, but for many it will.

These 3 items look like they may have all the pieces you'll need:

How to simulate multimedia key press (in C)?

pinvoke.net: sendinput (user32)

SendInput Windows API C#


问:
AJAX form submit to PHP not returning correct data
I have a form that I would like to send data from to a php script using AJAX. However I am running into an issue with actually passing the data across. The $_POST array is empty for some reason.

Currently the HTML is:

```<code><form>
    <label>Email Address:</label>
    <input type='text' name='email' value='jackc@test.com'/>
    <input type='submit' name='submit' value='Check subscription status'/>
</form>
</code>```

The JQuery is:

```<code> $(document).ready(function() {
        $('form').submit(function(e){
            e.preventDefault();
            var url = 'request.php';
            $.ajax({
                type: 'POST',
                url: url,
                contentType: "json",
                data: $('form').serialize(),
                success: function(data){
                    console.log(data);
                    $('#results').html(data);
                }
            });

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

The PHP is:

```<code>        $emailAddress = $_POST['email'];
        echo "EMAIL: " . $emailAddress;
</code>```

However it's not returning anything. It's blank each time. When I do a console log for $('form').serialize() I see email=jackc%40@test.com which I would expect to see returned from my PHP.

I'd appreciate some help on this. Many thanks.

答:
Regarding this:

When I do a console log for $('form').serialize() I see
  email=jackc%40@test.com

You have specified contentType: "json", but you sent something looking like application/x-www-form-urlencoded.

You can see here an example: JQuery Post sends form data and not JSON

Body:
I have a form that I would like to send data from to a php script using AJAX. However I am running into an issue with actually passing the data across. The $_POST array is empty for some reason.

Currently the HTML is:

<form>
    Email Address:
    <input type='text' name='email' value='jackc@test.com'/>
    <input type='submit' name='submit' value='Check subscription status'/>
</form>

The JQuery is:

 $(document).ready(function() {
        $('form').submit(function(e){
            e.preventDefault();
            var url = 'request.php';
            $.ajax({
                type: 'POST',
                url: url,
                contentType: "json",
                data: $('form').serialize(),
                success: function(data){
                    console.log(data);
                    $('#results').html(data);
                }
            });

        });
    });

The PHP is:

        $emailAddress = $_POST['email'];
        echo "EMAIL: " . $emailAddress;

However it's not returning anything. It's blank each time. When I do a console log for $('form').serialize() I see email=jackc%40@test.com which I would expect to see returned from my PHP.

I'd appreciate some help on this. Many thanks.


问:
Debug NodeJS + AngularJS 2
How can I debug the entire App NodeJS and ExpressJS?
I tried using 'ng build --prod' , then copying files in dist to my views folder .
I want that whenever I change codes , I refresh browser and its codes are also going to change. Thank you!</p>

答:
I assume you are using Angular2 (AngularJS 2 has no meaning)

If you want to debug only server(NodeJS + ExpressJS)

Use WebStorm. It is very easy with WebStorm to mark break points and then go to 'Run / Debug Configurations' and add new Node.js profile. Set the proper properties in the configuration area. Now you can run the server in debug mode by clicking small green color bug icon in top right corner in the IDE. When you send a request from the client the server will pause at the break point. WebStorm will give you lots of helpful features while debugging.

If you want to debug angular2 application

you can use Google Chrome Extension Augury to debug an Angular2 application. Augury documentation will help you how to use it.

Additionally I want you to tell you is,

while you are developing don't use ng build. use ng serve and serve the angular app in different port(default 4200) and node server in another port (default 3000). Then open the angular app in browser with disabling web-security (CORS disabled - here). This will give you more flexible development experience.

Use Nodemon for start nodeJS server. It will automatically restart the server with the changes of your source code.

Thank you.

Title: Debug NodeJS + AngularJS 2


问:
delete record from two different table using one query Mysql
i want to delete record from two table which is relate by f key.
this is sample code the way i use in my original code. but this is not working.

DELETE from tb_extensions ext
inner JOIN tb_employee em
on em.emp_id = ext.emp_id
where tb_employee.emp_id = 'new1'

答:
Try this may be this works as you expected.</p>

```<code>DELETE FROM tb_extensions, tb_employee USING tb_extension INNER JOIN
tb_employee WHERE tb_employee.emp_id = 'new1'
AND tb_employee.emp_id = tb_extensions.emp_id
</code>```

Body:
Try this may be this works as you expected.

DELETE FROM tb_extensions, tb_employee USING tb_extension INNER JOIN
tb_employee WHERE tb_employee.emp_id = 'new1'
AND tb_employee.emp_id = tb_extensions.emp_id


问:
Android: AutoCompleteTextView show suggestions when no text entered
I am using AutoCompleteTextView, when the user clicks on it, I want to show suggestions even if it has no text - but setThreshold(0) works exactly the same as setThreshold(1) - so the user has to enter at least 1 character to show the suggestions.

答:
This worked for me, pseudo code:

```<code>    public class CustomAutoCompleteTextView extends AutoCompleteTextView {
    public CustomAutoCompleteTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean enoughToFilter() {
        return true;
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
        if (focused) {
            performFiltering(getText(), 0);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        this.showDropDown();
        return super.onTouchEvent(event);
    }
}
</code>```

Body:
This worked for me, pseudo code:

    public class CustomAutoCompleteTextView extends AutoCompleteTextView {
    public CustomAutoCompleteTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean enoughToFilter() {
        return true;
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
        if (focused) {
            performFiltering(getText(), 0);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        this.showDropDown();
        return super.onTouchEvent(event);
    }
}


问:
Achieve the xml hierarchy structure having an ordered list with level numbers
I have a list of numbers which represents the levels in a xml tree.
For example I have the folowwing list:

```<code> 0, 1, 2, 2, 1
</code>```

and the xml (with 'lev' elements) needs to be:

```<code><lev>
  <lev>
    <lev>
    </lev>
    <lev>
    </lev>
  </lev>
  <lev>
  </lev>
</lev>
</code>```

How can I form this xml having just that list?
I need a recursive method, actually I need this for a xsl file, but It will be great also having just as a Java code - with parsing that list.

I'm not sure if this is possible, having just that list.
Any help will be great!
Thanks.

Later edit:

For the above list let's say that we introduce the position too:

```<code>Level     Position
   0        0
   1        1
   2        2
   2        3
   1        4
</code>```

If we are having in the list a number(level) x and after it we are having a number(level) y where y<=x we know at that point that the last element(s) (x, x-1, ..., y) needs to be closed when creating the xml.

Ex.:

when we are at position 3 (level 2) we know that the Element at position 2 (also with level 2) needs to be closed

when we are at position 4 (level 1) we know that the Element at position-s 3 (level 2) and 1 (level 1) needs to be closed

答:
Recursion is overkill for this. Also, there's no need for a "position" value. Here's a pseudocode solution

Assume a function next() that returns the next input value, or zero for EOF.

```<code>curLevel = 0
n        = next();
do
{
  while(curLevel <= n)
  {
    open tag
    ++curLevel
  }
  n = next();
  while(curLevel > n)
  {
    --curLevel
    close tag
  }
}
while(curLevel > 0)
</code>```

Note that the corner case of an empty input file will produce one open/close pair.  Check for EOF a different way and modify the code to handle it if that's not desired.

Body:
I have a list of numbers which represents the levels in a xml tree.
For example I have the folowwing list:

 0, 1, 2, 2, 1

and the xml (with 'lev' elements) needs to be:

<lev>
  <lev>
    <lev>
    </lev>
    <lev>
    </lev>
  </lev>
  <lev>
  </lev>
</lev>

How can I form this xml having just that list?
I need a recursive method, actually I need this for a xsl file, but It will be great also having just as a Java code - with parsing that list.

I'm not sure if this is possible, having just that list.
Any help will be great!
Thanks.

Later edit:

For the above list let's say that we introduce the position too:

Level     Position
   0        0
   1        1
   2        2
   2        3
   1        4

If we are having in the list a number(level) x and after it we are having a number(level) y where y<=x we know at that point that the last element(s) (x, x-1, ..., y) needs to be closed when creating the xml.

Ex.:

when we are at position 3 (level 2) we know that the Element at position 2 (also with level 2) needs to be closed

when we are at position 4 (level 1) we know that the Element at position-s 3 (level 2) and 1 (level 1) needs to be closed

Body:
Recursion is overkill for this. Also, there's no need for a "position" value. Here's a pseudocode solution

Assume a function next() that returns the next input value, or zero for EOF.

curLevel = 0
n        = next();
do
{
  while(curLevel <= n)
  {
    open tag
    ++curLevel
  }
  n = next();
  while(curLevel > n)
  {
    --curLevel
    close tag
  }
}
while(curLevel > 0)

Note that the corner case of an empty input file will produce one open/close pair.  Check for EOF a different way and modify the code to handle it if that's not desired.


问:
Change font color of autofill input field
I've managed to change the background color of an autofilled input field from yellow to white with the following code:

```<code>input.login:-webkit-autofill {
    -webkit-box-shadow: 0 0 0 1000px white inset;
}
</code>```

However, changing the font color to grey simply by adding color: #999; doesn't work. How could I fix this? Many thanks!

答:
Try the below CSS:

```<code>/* Change Autocomplete styles in Chrome*/
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus
input:-webkit-autofill,
textarea:-webkit-autofill,
textarea:-webkit-autofill:hover
textarea:-webkit-autofill:focus,
select:-webkit-autofill,
select:-webkit-autofill:hover,
select:-webkit-autofill:focus {
  border: 1px solid green;
  -webkit-text-fill-color: green;
  -webkit-box-shadow: 0 0 0px 1000px #000 inset;
  transition: background-color 5000s ease-in-out 0s;
}
</code>```

We can use the -webkit-autofill pseudo-selector to target those fields and style them as we see fit.

Body:
I've managed to change the background color of an autofilled input field from yellow to white with the following code:

input.login:-webkit-autofill {
    -webkit-box-shadow: 0 0 0 1000px white inset;
}

However, changing the font color to grey simply by adding color: #999; doesn't work. How could I fix this? Many thanks!

Body:
Try the below CSS:

/* Change Autocomplete styles in Chrome*/
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus
input:-webkit-autofill,
textarea:-webkit-autofill,
textarea:-webkit-autofill:hover
textarea:-webkit-autofill:focus,
select:-webkit-autofill,
select:-webkit-autofill:hover,
select:-webkit-autofill:focus {
  border: 1px solid green;
  -webkit-text-fill-color: green;
  -webkit-box-shadow: 0 0 0px 1000px #000 inset;
  transition: background-color 5000s ease-in-out 0s;
}

We can use the -webkit-autofill pseudo-selector to target those fields and style them as we see fit.


问:
Generator expressions Python
I have a list of dictionaries like the following:

```<code>lst = [{'a': 5}, {'b': 6}, {'c': 7}, {'d': 8}]
</code>```

I wrote a generator expression like:

```<code>next((itm for itm in lst if itm['a']==5))
</code>```

Now the strange part is that though this works for the key value pair of 'a'
it throws an error for all other expressions the next time.
Expression:

```<code>next((itm for itm in lst if itm['b']==6))
</code>```

Error:

```<code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <genexpr>
KeyError: 'b'
</code>```

答:
Indeed, your structure is a list of dictionaries.

```<code>>>> lst = [{'a': 5}, {'b': 6}, {'c': 7}, {'d': 8}]
</code>```

To get a better idea of what is happening with your first condition, try this:

```<code>>>> gen = (itm for itm in lst if itm['a'] == 5)
>>> next(gen)
{'a': 5}
>>> next(gen)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <genexpr>
KeyError: 'a'
</code>```

Each time you call next, you process the next element and return an item. Also...

```<code>next((itm for itm in lst if itm['a'] == 5))
</code>```

Creates a generator that is not assigned to any variable, processes the first element in the lst, sees that key 'a' does indeed exist, and return the item. The generator is then garbage collected. The reason an error is not thrown is because the first item in lst does indeed contain this key.

So, if you changed the key to be something that the first item does not contain, you get the error you saw:

```<code>>>> gen = (itm for itm in lst if itm['b'] == 6)
>>> next(gen)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <genexpr>
KeyError: 'b'
</code>```

The Solution

Well, one solution as already discussed is to use the dict.get function. Here's another alternative using defaultdict:

```<code>from collections import defaultdict
from functools import partial

f = partial(defaultdict, lambda: None)

lst = [{'a': 5}, {'b': 6}, {'c': 7}, {'d': 8}]
lst = [f(itm) for itm in lst] # create a list of default dicts

for i in (itm for itm in lst if itm['b'] == 6):
    print(i)
</code>```

This prints out:

```<code>defaultdict(<function <lambda> at 0x10231ebf8>, {'b': 6})
</code>```

The defaultdict will return None in the event of the key not being present.

Title: Generator expressions Python

Body:
I have a list of dictionaries like the following:

lst = [{'a': 5}, {'b': 6}, {'c': 7}, {'d': 8}]

I wrote a generator expression like:

next((itm for itm in lst if itm['a']==5))

Now the strange part is that though this works for the key value pair of 'a'
it throws an error for all other expressions the next time.
Expression:

next((itm for itm in lst if itm['b']==6))

Error:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <genexpr>
KeyError: 'b'

Body:
Indeed, your structure is a list of dictionaries.

>>> lst = [{'a': 5}, {'b': 6}, {'c': 7}, {'d': 8}]

To get a better idea of what is happening with your first condition, try this:

>>> gen = (itm for itm in lst if itm['a'] == 5)
>>> next(gen)
{'a': 5}
>>> next(gen)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <genexpr>
KeyError: 'a'

Each time you call next, you process the next element and return an item. Also...

next((itm for itm in lst if itm['a'] == 5))

Creates a generator that is not assigned to any variable, processes the first element in the lst, sees that key 'a' does indeed exist, and return the item. The generator is then garbage collected. The reason an error is not thrown is because the first item in lst does indeed contain this key.

So, if you changed the key to be something that the first item does not contain, you get the error you saw:

>>> gen = (itm for itm in lst if itm['b'] == 6)
>>> next(gen)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <genexpr>
KeyError: 'b'

The Solution

Well, one solution as already discussed is to use the dict.get function. Here's another alternative using defaultdict:

from collections import defaultdict
from functools import partial

f = partial(defaultdict, lambda: None)

lst = [{'a': 5}, {'b': 6}, {'c': 7}, {'d': 8}]
lst = [f(itm) for itm in lst] # create a list of default dicts

for i in (itm for itm in lst if itm['b'] == 6):
    print(i)

This prints out:

defaultdict(<function <lambda> at 0x10231ebf8>, {'b': 6})

The defaultdict will return None in the event of the key not being present.


问:
Not able to read Git Environment variables Jenkins using Groovy Jenkinsfile
The Git Plugin is installed (by default) in my Jenkins but I'm unable to get the env variables that are supposed to be passed in by the Git Plugin. I'm looking for:

```<code>GIT_COMMIT
GIT_BRANCH
GIT_PREVIOUS_COMMIT
GIT_PREVIOUS_SUCCESSFUL_COMMIT
GIT_URL
</code>```

etc.  I'm using the Pipeline Job Item that's pointing at a Github repo with the Jenkinsfile with the following code

```<code>stage 'PushToProd'
node {
    git url: "https://github.com/username/fakeurl.git"
    echo "Starting PushToProd"
    sh 'printenv'
    sh 'env'
    sh 'echo $BRANCH_NAME'
    sh 'echo $GIT_COMMIT'
}
</code>```

I'm getting plenty of environment variables when I use env or printenv just not the Github plugin ones.

Any tips on how I can get the Git env variables passed in to the job?

Update: I'm able to easily get the Git env variables when I use a Freestyle Project and have a shell step use echo $GIT_COMMIT.  Still want to know though how to get it to work using Jenkinsfile + Pipeline job item.

答:
This is fixed in Git plugin 3.3.1

Version 3.3.1 (Jun 23, 2017)

Print first line of commit message in console log (JENKINS-38241)

Allow scm steps to return revision (JENKINS-26100)

Don't require crumb for POST to /git/notifyCommit even when CSRF is enabled (JENKINS-34350)

Fix credentials tracking null pointer exception in pipeline library use (JENKINS-44640)

Fix credentials tracking null pointer exception in git parameters use (JENKINS-44087)

Body:
The Git Plugin is installed (by default) in my Jenkins but I'm unable to get the env variables that are supposed to be passed in by the Git Plugin. I'm looking for:

GIT_COMMIT
GIT_BRANCH
GIT_PREVIOUS_COMMIT
GIT_PREVIOUS_SUCCESSFUL_COMMIT
GIT_URL

etc.  I'm using the Pipeline Job Item that's pointing at a Github repo with the Jenkinsfile with the following code

stage 'PushToProd'
node {
    git url: "https://github.com/username/fakeurl.git"
    echo "Starting PushToProd"
    sh 'printenv'
    sh 'env'
    sh 'echo $BRANCH_NAME'
    sh 'echo $GIT_COMMIT'
}

I'm getting plenty of environment variables when I use env or printenv just not the Github plugin ones.

Any tips on how I can get the Git env variables passed in to the job?

Update: I'm able to easily get the Git env variables when I use a Freestyle Project and have a shell step use echo $GIT_COMMIT.  Still want to know though how to get it to work using Jenkinsfile + Pipeline job item.


问:
Making images responsive
I'm creating an image slider and when the screen gets to 600 or below I want the images to be 100% of the screen width. I have tried to use width: 100% and max: width: 600px thinking this would make them responsive. But now I realise that that just makes them 600px wide not 100% of the screen with a max width. How can I achieve this?

$(document).ready(function(){
  var image_width = $(".img_cont").width();
  var image_count = $(".carousel li").length;
  var carousel_width = image_width * image_count + image_width;
  var padding = $(".active img").height() /4;

  $(".carousel").css("width", carousel_width);
  $(".img_cont").css("paddingTop", padding);
  $(".active").css("paddingTop", 0);

  $(window).resize(function(){
    if($(window).width() <= 600){
        var image_width = $(".img_cont").width();
        var image_count = $(".carousel li").length;
        var carousel_width = image_width * image_count;

        $(".carousel").css("width", carousel_width);
        $(".img_cont").css("paddingTop", 0);
        $(".active").css("paddingTop", 0);
      }else if($(window).width() < 1600){
        var image_width = $(".img_cont").width();
        var image_count = $(".carousel li").length;
        var carousel_width = image_width * image_count + image_width;
        var padding = $(".active img").height() /4;

        $(".carousel").css("width", carousel_width);
        $(".img_cont").css("paddingTop", padding);
        $(".active").css("paddingTop", 0);
      }else {
        var image_width = $(".img_cont").width();
        var image_count = $(".carousel li").length;
        var carousel_width = image_width * image_count + image_width;
        var padding = $(".active img").height() /4;

        $(".carousel").css("width", carousel_width);
        $(".img_cont").css("paddingTop", padding);
        $(".active").css("paddingTop", 0);
      }
      });
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*{
  padding: 0;
  margin: 0;
}

body{
  width: 100%;
  margin: 0;
  padding: 0;
}

.cont{
  position: relative;
  font-size: 0;/*removes white space*/
  margin: 60px auto;
  padding: 0;
/*   overflow: hidden; */
}

.carousel{
  padding: 0;
  list-style-type: none;
  height: auto;
  position: relative;
  left: 50%;
  -webkit-transform: translateX(-50%);
  -ms-transform: translateX(-50%);
  -o-transform: translateX(-50%);
  transform: translateX(-50%);
  overflow: hidden;
}

.carousel li{
  float: left;
  background-color: pink;
}

#next{
  position: absolute;
  top: 45%;
  right: 0;
  width: 40px;
  height: 40px;
  background-color: blue;
  font-size: 0;
  z-index: 1;
}

#prev{
  position: absolute;
  top: 45%;
  left: 0;
  width: 40px;
  height: 40px;
  background-color: blue;
  z-index: 1;
}

.img_cont img{
  width: 100%;
  max-width: 600px;
  height: auto;
  max-height:600px;
}

.active img{
  width: 100%;
  max-width: 1200px;
  height: auto;
  padding: 0;
}

@media screen and (max-width: 1600px){
  .img_cont img{
    width: 100%;
    max-width: 500px;
    height: auto;
  }

  .active img{
    width: 100%;
    max-width: 1000px;
    height: auto;
    padding: 0;
  }
}

@media screen and (max-width: 1200px){
  .img_cont img{
    width: 100%;
    max-width: 400px;
    height: auto;
  }

  .active img{
    width: 100%;
    max-width: 800px;
    height: auto;
    padding: 0;
  }
}

@media screen and (max-width: 1000px){
  .img_cont img{
    width: 100%;
    max-width: 300px;
    height: auto;
  }

  .active img{
    width: 100%;
    max-width: 600px;
    height: auto;
    padding: 0;
  }
}

@media screen and (max-width: 600px){

  img_cont{
    width: 100%;
    max-width: none;
  }

  .img_cont img{
    width: 100%;
    max-width: 600px;
    height: auto;
    padding: 0;
  }

  .active img{
    width: 100%;
    max-width: 600px;
    height: auto;
    padding: 0;
  }
}</code>```

```

答:
Just to show you basic concept.
I just pulled the code from w3school about slider.
Add the container around the images and set images' size as 100% and make container have particular size.
Once I've seen your question, your original image size is not over 600px(guess that's why you want to make it larger(100%) when window size got smaller than that. I just override the css content set max-width as 530px. when it got smaller than 600px, make it 600px.
Please see the code below. hope it will work!

```<code><style>
.w3-display-container
{
    max-width:530px;
}
@media screen and (max-width: 600px){
.w3-display-container
{
    max-width:600px;
}
</style>
</code>```

Main code

```<code>    <!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body>

<style>
.w3-display-container
{
    max-width:530px;
}
@media screen and (max-width: 600px){
.w3-display-container
{
    max-width:600px;
}
</style>

<div class="w3-content w3-display-container">
  <img class="mySlides" src="http://lorempixel.com/output/abstract-q-c-1500-700-2.jpg" style="width:100%">
  <img class="mySlides" src="http://lorempixel.com/output/abstract-q-c-1500-700-6.jpg" style="width:100%">
  <img class="mySlides" src="http://lorempixel.com/output/abstract-q-c-1500-700-1.jpg" style="width:100%">

  <button class="w3-button w3-black w3-display-left" onclick="plusDivs(-1)">❮</button>
  <button class="w3-button w3-black w3-display-right" onclick="plusDivs(1)">❯</button>
</div>

<script>
var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
  showDivs(slideIndex += n);
}

function showDivs(n) {
  var i;
  var x = document.getElementsByClassName("mySlides");
  if (n > x.length)
  {
    slideIndex = 1
  }
  if (n < 1)
  {
    slideIndex = x.length
  }
  for (i = 0; i < x.length; i++)
  {
     x[i].style.display = "none";
  }

  x[slideIndex-1].style.display = "block";
}
</script>

</body>
</html>
</code>```

Title: Making images responsive

Body:
I'm creating an image slider and when the screen gets to 600 or below I want the images to be 100% of the screen width. I have tried to use width: 100% and max: width: 600px thinking this would make them responsive. But now I realise that that just makes them 600px wide not 100% of the screen with a max width. How can I achieve this?

$(document).ready(function(){
  var image_width = $(".img_cont").width();
  var image_count = $(".carousel li").length;
  var carousel_width = image_width * image_count + image_width;
  var padding = $(".active img").height() /4;

  $(".carousel").css("width", carousel_width);
  $(".img_cont").css("paddingTop", padding);
  $(".active").css("paddingTop", 0);

  $(window).resize(function(){
    if($(window).width() <= 600){
        var image_width = $(".img_cont").width();
        var image_count = $(".carousel li").length;
        var carousel_width = image_width * image_count;

        $(".carousel").css("width", carousel_width);
        $(".img_cont").css("paddingTop", 0);
        $(".active").css("paddingTop", 0);
      }else if($(window).width() < 1600){
        var image_width = $(".img_cont").width();
        var image_count = $(".carousel li").length;
        var carousel_width = image_width * image_count + image_width;
        var padding = $(".active img").height() /4;

        $(".carousel").css("width", carousel_width);
        $(".img_cont").css("paddingTop", padding);
        $(".active").css("paddingTop", 0);
      }else {
        var image_width = $(".img_cont").width();
        var image_count = $(".carousel li").length;
        var carousel_width = image_width * image_count + image_width;
        var padding = $(".active img").height() /4;

        $(".carousel").css("width", carousel_width);
        $(".img_cont").css("paddingTop", padding);
        $(".active").css("paddingTop", 0);
      }
      });
  });

*{
  padding: 0;
  margin: 0;
}

body{
  width: 100%;
  margin: 0;
  padding: 0;
}

.cont{
  position: relative;
  font-size: 0;/*removes white space*/
  margin: 60px auto;
  padding: 0;
/*   overflow: hidden; */
}

.carousel{
  padding: 0;
  list-style-type: none;
  height: auto;
  position: relative;
  left: 50%;
  -webkit-transform: translateX(-50%);
  -ms-transform: translateX(-50%);
  -o-transform: translateX(-50%);
  transform: translateX(-50%);
  overflow: hidden;
}

.carousel li{
  float: left;
  background-color: pink;
}

#next{
  position: absolute;
  top: 45%;
  right: 0;
  width: 40px;
  height: 40px;
  background-color: blue;
  font-size: 0;
  z-index: 1;
}

#prev{
  position: absolute;
  top: 45%;
  left: 0;
  width: 40px;
  height: 40px;
  background-color: blue;
  z-index: 1;
}

.img_cont img{
  width: 100%;
  max-width: 600px;
  height: auto;
  max-height:600px;
}

.active img{
  width: 100%;
  max-width: 1200px;
  height: auto;
  padding: 0;
}

@media screen and (max-width: 1600px){
  .img_cont img{
    width: 100%;
    max-width: 500px;
    height: auto;
  }

  .active img{
    width: 100%;
    max-width: 1000px;
    height: auto;
    padding: 0;
  }
}

@media screen and (max-width: 1200px){
  .img_cont img{
    width: 100%;
    max-width: 400px;
    height: auto;
  }

  .active img{
    width: 100%;
    max-width: 800px;
    height: auto;
    padding: 0;
  }
}

@media screen and (max-width: 1000px){
  .img_cont img{
    width: 100%;
    max-width: 300px;
    height: auto;
  }

  .active img{
    width: 100%;
    max-width: 600px;
    height: auto;
    padding: 0;
  }
}

@media screen and (max-width: 600px){

  img_cont{
    width: 100%;
    max-width: none;
  }

  .img_cont img{
    width: 100%;
    max-width: 600px;
    height: auto;
    padding: 0;
  }

  .active img{
    width: 100%;
    max-width: 600px;
    height: auto;
    padding: 0;
  }
}

Body:
Just to show you basic concept.
I just pulled the code from w3school about slider.
Add the container around the images and set images' size as 100% and make container have particular size.
Once I've seen your question, your original image size is not over 600px(guess that's why you want to make it larger(100%) when window size got smaller than that. I just override the css content set max-width as 530px. when it got smaller than 600px, make it 600px.
Please see the code below. hope it will work!

<style>
.w3-display-container
{
    max-width:530px;
}
@media screen and (max-width: 600px){
.w3-display-container
{
    max-width:600px;
}
</style>

Main code

    <!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body>

<style>
.w3-display-container
{
    max-width:530px;
}
@media screen and (max-width: 600px){
.w3-display-container
{
    max-width:600px;
}
</style>

<div class="w3-content w3-display-container">
  <img class="mySlides" src="http://lorempixel.com/output/abstract-q-c-1500-700-2.jpg" style="width:100%">
  <img class="mySlides" src="http://lorempixel.com/output/abstract-q-c-1500-700-6.jpg" style="width:100%">
  <img class="mySlides" src="http://lorempixel.com/output/abstract-q-c-1500-700-1.jpg" style="width:100%">

  <button class="w3-button w3-black w3-display-left" onclick="plusDivs(-1)">&#10094;</button>
  <button class="w3-button w3-black w3-display-right" onclick="plusDivs(1)">&#10095;</button>
</div>

<script>
var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
  showDivs(slideIndex += n);
}

function showDivs(n) {
  var i;
  var x = document.getElementsByClassName("mySlides");
  if (n > x.length)
  {
    slideIndex = 1
  }
  if (n < 1)
  {
    slideIndex = x.length
  }
  for (i = 0; i < x.length; i++)
  {
     x[i].style.display = "none";
  }

  x[slideIndex-1].style.display = "block";
}
</script>

</body>
</html>


问:
SQL - HAVING Clause in depth
I'm trying to understand what condition can be placed after the having clause - it is usually a condition, that uses the functions from the select statement, but it also can contain a column, that is typed in the select statement.

Here's an example:

```<code>create table r(a int, b int, c int, d int, e int primary key)

select a, min(b), sum(c)
from r
where b > 5
group by a
having "condition"
</code>```

which of the following can replace the "condition"

```<code>a) b = 5

b) a = sum(e)

c) min(b) >= 6
</code>```

When I execute this in SQL, only a) doesn't work, but what's the logic behind it?

答:
This will be correct one </p>

```<code>create table r(a int, b int, c int, d int, e int primary key)

select a, min(b), sum(c)
from r
where b > 5
group by a
having "min(b) >= 6"
</code>```

Title: SQL - HAVING Clause in depth

Body:
I'm trying to understand what condition can be placed after the having clause - it is usually a condition, that uses the functions from the select statement, but it also can contain a column, that is typed in the select statement.

Here's an example:

create table r(a int, b int, c int, d int, e int primary key)

select a, min(b), sum(c)
from r
where b > 5
group by a
having "condition"

which of the following can replace the "condition"

a) b = 5

b) a = sum(e)

c) min(b) >= 6

When I execute this in SQL, only a) doesn't work, but what's the logic behind it?

Body:
This will be correct one

create table r(a int, b int, c int, d int, e int primary key)

select a, min(b), sum(c)
from r
where b > 5
group by a
having "min(b) >= 6"


问:
Regular Expression - 301 redirect
I have the below URL

```<code>http://www.yyyyy.com/en/x/y/2010/2010-02-03-test
</code>```

And I want to redirect it to

```<code>https://www.yyyyy.com/x/y/2010-02-03-test
</code>```

So what I need to do is, remove the /en/ part from the URL

I need the regular expression to add on .htaccess file that can help me to do 301 redirects for this,

答:
You can use the following redirect:</p>

```<code> RedirectMatch ^/en/x/y/2010/(.+)$ /x/y/$1
</code>```

Title: Regular Expression - 301 redirect

Body:
I have the below URL

http://www.yyyyy.com/en/x/y/2010/2010-02-03-test

And I want to redirect it to

https://www.yyyyy.com/x/y/2010-02-03-test

So what I need to do is, remove the /en/ part from the URL

I need the regular expression to add on .htaccess file that can help me to do 301 redirects for this,

Body:
You can use the following redirect:

 RedirectMatch ^/en/x/y/2010/(.+)$ /x/y/$1


问:
Value based conditional Formatting in Excel
I have 2 cells a1 and  a2, which may have negative or postive values. I want the color of both the cells to change to green if value in either cell is between -10 to 10. And red if the value in either cell is between 10 to 20 or -10 to -20 and purple if the value in either cell exceeds 20 or -20. Can any one help me with the query. </p>

答:
It's not about a query, it's about conditional formatting.

choose the cell and select "conditional formatting" from the menu.

Choose "New Rule" and select "Use a formula to determine which cells to format".

Example -

A rule to color all cells higher than -10 and lower then 10 as red background:

Create several rules on the same selected cell to format it according to your wishes.


问:
Yii2 multidatabase query
I'm struggling with creating activequery joining data from 2 different databases.
Both Databases are on same machine, on PostgreSQL.
In one DB i have almost all my data, but two columns - 'name' and 'region_id', which are in second DB.
I've made relation and i can get these values, but the problem is i need to get values from DB1 depending on region_id from DB2.

DB1(table districts):
district_id -> relation called 'topology' with DB2(id),
some more data...

DB2(table district):
id,
name,
region_id.

I got Two models, to both tables and they works well.
In model for DB1 i got relation to table in DB2 called 'topology', and if i try:Districts::find()->joinWith('topology')->all(); all i get is DB Exception with message Relation not exists.

All in need to do is add clause where to get records with only one region_id...

Any suggestions?
Thanks in advance.

答:
i think multi database work only for MySQL

for other DB multi database join doesn't work

but in Yii2 multidatabase work when you use relation If you models using a different databases

Title: Yii2 multidatabase query


问:
how to disable drag and drop in Jquery Nestable List
Im trying to created a nested list using jquery nestable with drag feature disable throughout the list.
Below is my html.

```<code><div class="dd" id="nestable">
<ol class="dd-list">
    <li class="dd-item" id="no-drag">
        <div class="dd-handle">
            Foo
            <div class="pull-right action-buttons">
                <a class="blue" href="#">
                    <i class="ace-icon fa fa-pencil bigger-130"></i>
                </a>

                <a class="red" href="#">
                    <i class="ace-icon fa fa-trash-o bigger-130"></i>
                </a>
            </div>

        </div>
        <ol class="dd-list">
            <li class="dd-item" id="no-drag">
                <div class="dd-handle">
                    Bar
                    <div class="pull-right action-buttons">
                        <a class="blue" href="#">
                            <i class="ace-icon fa fa-pencil bigger-130"></i>
                        </a>

                        <a class="red" href="#">
                            <i class="ace-icon fa fa-trash-o bigger-130"></i>
                        </a>
                    </div>

                </div>
                <ol class="dd-list">
                    <li class="dd-item" id="no-drag">
                        <div class="dd-handle">
                            Baz
                            <div class="pull-right action-buttons">
                                <a class="blue" href="#">
                                    <i class="ace-icon fa fa-pencil bigger-130"></i>
                                </a>

                                <a class="red" href="#">
                                    <i class="ace-icon fa fa-trash-o bigger-130"></i>
                                </a>
                            </div>

                        </div>
                    </li>
                </ol>
            </li>
        </ol>
    </li>
</ol>
</code>```

My script looks like below::

```<code>$('.dd').each(function(){
            $(this).nestable({
                maxDepth: 1,
                group: $(this).prop('id')
            });
        });
</code>```

At the moment, im able to create nested list and user can rearrange the nested list. I want that feature to disabled but im not able to do it. Please advise.

答:
You can set maxDepth: 0
This will not disable drag and drop, but do not prevent the obj relocation</p>

Body:
Im trying to created a nested list using jquery nestable with drag feature disable throughout the list.
Below is my html.

            Foo

                    Bar

                            Baz

My script looks like below::

$('.dd').each(function(){
            $(this).nestable({
                maxDepth: 1,
                group: $(this).prop('id')
            });
        });

At the moment, im able to create nested list and user can rearrange the nested list. I want that feature to disabled but im not able to do it. Please advise.