问:
Equal cost multipath Dijkstra's Algorithm in python
Using python recipes proposed here:

http://code.activestate.com/recipes/119466-dijkstras-algorithm-for-shortest-paths/

and

http://code.activestate.com/recipes/117228-priority-dictionary/

and using as input the following graph:

```<code> graph_2  = {
    'R1':{'R2':5,'R3':5},
    'R2':{'R1':5,'R4':5},
    'R3':{'R1':5,'R4':5},
    'R4':{'R2':5,'R3':5},
}
</code>```

I'm trying to get ALL shortest paths between R1 and R4.  However, I'm only getting one shortest path (R1-R2-R4), and not (R1-R3-R4).  I need to simulate ECMP (such as OSPF does).  What I need is that function shortestPath returns all shortest path (i.e [[R1-R2-R4],[R1-R3-R4]]) in case of Equal Cost Multipath (like graph_2 on top) and only the shortest path in case of Single Path like for example:

```<code>  graph_3  = {
    'R1':{'R2':5,'R3':5},
    'R2':{'R1':5,'R4':5},
    'R3':{'R1':5,'R4':10},
    'R4':{'R2':5,'R3':5},
}
</code>```

I've modified the code in the Dijkstra function like that:

```<code>from priodict import priorityDictionary

graph_2  = {

'R1':{'R2':5,'R3':5},
'R2':{'R1':5,'R4':5},
'R3':{'R1':5,'R4':5},
'R4':{'R2':5,'R3':5},
}

def Dijkstra(G,start,end=None):

    D = {}  # dictionary of final distances
    P = {}  # dictionary of predecessors
    Q = priorityDictionary()   # est.dist. of non-final vert.
    Q[start] = 0
    for v in Q:
        D[v] = Q[v]
        if v == end: break

        for w in G[v]:
            vwLength = D[v] + G[v][w]

            if w in D:
                if vwLength < D[w]:
                    raise ValueError, \
            elif w not in Q or vwLength < Q[w]:
                Q[w] = vwLength
                P[w] = [v]
            elif  w not in Q or vwLength == Q[w]: <---adding this part
                Q[w] = vwLength
                P[w] += [v]

    return (D,P)

def shortestPath(G,start,end):
    D,P = Dijkstra(G,start,end)
    print D,P
    Path = []
    while 1:
        Path.append(end)
        print end
        if end == start: break
        end = P[end]
    Path.reverse()
    return Path

print shortestPath(graph_2,'R1','R4')
</code>```

and I'm getting the following output and error:

```<code>{'R4': 10, 'R1': 0, 'R2': 5, 'R3': 5} {'R4': ['R2', 'R3'], 'R2': ['R1'], 'R3': ['R1']}

Traceback (most recent call last):
File "next-hop-resolver.py", line 194, in <module>
print shortestPath(graph_2,'R1','R4')
File "next-hop-resolver.py", line 172, in shortestPath
end = P[end]
TypeError: unhashable type: 'list'
</code>```

What I would like to get using graph_2 is :

[['R1', 'R2', 'R4'], ['R1', 'R3', 'R4']]

and using graph_3:

[['R1', 'R2', 'R4']]

If I execute the code as is, i.e without any kind of code modification I get the following result, no matter if I use graph_2 or graph_3:

[['R1', 'R2', 'R4']]

i.e always the shortest path, even if there is more than one path.

I know that a list can't be a key in a dictionary, but to be honest I'm stuck with that, so any help is more than welcome

答:
Finally, I think I got what I was looking for :)

Here's the final code

```<code>from priodict import priorityDictionary
from collections import defaultdict
from collections import OrderedDict
import sys
graph_2  = {

'R1':{'R2':5,'R3':5},
'R2':{'R1':5,'R4':5},
'R3':{'R1':5,'R4':5},
'R4':{'R2':5,'R3':5,'R5':5},
'R5':{'R4':5}

}

graph_3 = {

'192.168.255.1':{'192.168.255.2':10,'192.168.255.3':10},
'192.168.255.2':{'192.168.255.1':10,'192.168.255.3':50},
'192.168.255.3':{'192.168.255.1':20,'192.168.255.2':50},
'192.168.255.4':{'192.168.255.3':20},
'192.168.255.3':{'192.168.255.4':20}
}

graph_4 = {
'R1':{'R2':5},
'R2':{'R1':5},
'R2':{'R3':5},
'R3':{'R2':5},
'R3':{'R4':5},
'R4':{'R3':5}
}

graph_5 = {

'A':{'B':5,'C':10,'E':2},
'B':{'A':5,'C':5},
'C':{'B':5,'A':10,'E':8,'D':4},
'D':{'C':4,'E':5},
'E':{'A':2,'D':5,'C':8}

}

def Dijkstra(g,start,end=None):

    d = {}  # dictionary of final distances
    p = {}  # dictionary of predecessors
    q = priorityDictionary()   # est.dist. of non-final vert.
    q[start] = 0
    for v in q:
        d[v] = q[v]
        if v == end: break
        for w in g[v]:
            vwLength = d[v] + g[v][w]
            if w in d:
                if vwLength < d[w]:
                    raise ValueError
            elif w not in q or vwLength < q[w]:
                q[w] = vwLength
                p[w] = [v]
            elif  w not in q or vwLength == q[w]:
                q[w] = vwLength
                p[w] += [v]
    return (d,p)

def shortestPath(g,start,end):

    d,p = Dijkstra(g,start,end)
    path = [[end]]
    while True:
        if len(p[end]) > 1:
            path.append(p[end])
            for node in p[end]:
                if node != start:
                    if ''.join(p[end]) == start: break
                    end = node
        path.append(p[end])
        if ''.join(p[end]) == start: break
        for node in p[end]:
            if node == start: break
            end = node
    return path[::-1]

print shortestPath(graph_2,'R1','R5')
print shortestPath(graph_3,'192.168.255.1','192.168.255.2')
print shortestPath(graph_4,'R1','R4')
print shortestPath(graph_5,'A','C')
</code>```

and the output for each graph :

```<code>[['R1'], ['R2', 'R3'], ['R4'], ['R5']]
[['192.168.255.1'], ['192.168.255.2']]
[['R1'], ['R2'], ['R3'], ['R4']]
[['A'], ['A', 'E', 'B'], ['C']]
</code>```

Body:
Using python recipes proposed here:

http://code.activestate.com/recipes/119466-dijkstras-algorithm-for-shortest-paths/

and

http://code.activestate.com/recipes/117228-priority-dictionary/

and using as input the following graph:

 graph_2  = {
    'R1':{'R2':5,'R3':5},
    'R2':{'R1':5,'R4':5},
    'R3':{'R1':5,'R4':5},
    'R4':{'R2':5,'R3':5},
}

I'm trying to get ALL shortest paths between R1 and R4.  However, I'm only getting one shortest path (R1-R2-R4), and not (R1-R3-R4).  I need to simulate ECMP (such as OSPF does).  What I need is that function shortestPath returns all shortest path (i.e [[R1-R2-R4],[R1-R3-R4]]) in case of Equal Cost Multipath (like graph_2 on top) and only the shortest path in case of Single Path like for example:

  graph_3  = {
    'R1':{'R2':5,'R3':5},
    'R2':{'R1':5,'R4':5},
    'R3':{'R1':5,'R4':10},
    'R4':{'R2':5,'R3':5},
}

I've modified the code in the Dijkstra function like that:

from priodict import priorityDictionary

graph_2  = {

'R1':{'R2':5,'R3':5},
'R2':{'R1':5,'R4':5},
'R3':{'R1':5,'R4':5},
'R4':{'R2':5,'R3':5},
}

def Dijkstra(G,start,end=None):

    D = {}  # dictionary of final distances
    P = {}  # dictionary of predecessors
    Q = priorityDictionary()   # est.dist. of non-final vert.
    Q[start] = 0
    for v in Q:
        D[v] = Q[v]
        if v == end: break

        for w in G[v]:
            vwLength = D[v] + G[v][w]

            if w in D:
                if vwLength < D[w]:
                    raise ValueError, \
            elif w not in Q or vwLength < Q[w]:
                Q[w] = vwLength
                P[w] = [v]
            elif  w not in Q or vwLength == Q[w]: <---adding this part
                Q[w] = vwLength
                P[w] += [v]

    return (D,P)

def shortestPath(G,start,end):
    D,P = Dijkstra(G,start,end)
    print D,P
    Path = []
    while 1:
        Path.append(end)
        print end
        if end == start: break
        end = P[end]
    Path.reverse()
    return Path

print shortestPath(graph_2,'R1','R4')

and I'm getting the following output and error:

{'R4': 10, 'R1': 0, 'R2': 5, 'R3': 5} {'R4': ['R2', 'R3'], 'R2': ['R1'], 'R3': ['R1']}

Traceback (most recent call last):
File "next-hop-resolver.py", line 194, in <module>
print shortestPath(graph_2,'R1','R4')
File "next-hop-resolver.py", line 172, in shortestPath
end = P[end]
TypeError: unhashable type: 'list'

What I would like to get using graph_2 is :

[['R1', 'R2', 'R4'], ['R1', 'R3', 'R4']]

and using graph_3:

[['R1', 'R2', 'R4']]

If I execute the code as is, i.e without any kind of code modification I get the following result, no matter if I use graph_2 or graph_3:

[['R1', 'R2', 'R4']]

i.e always the shortest path, even if there is more than one path.

I know that a list can't be a key in a dictionary, but to be honest I'm stuck with that, so any help is more than welcome

Body:
Finally, I think I got what I was looking for :)

Here's the final code

from priodict import priorityDictionary
from collections import defaultdict
from collections import OrderedDict
import sys
graph_2  = {

'R1':{'R2':5,'R3':5},
'R2':{'R1':5,'R4':5},
'R3':{'R1':5,'R4':5},
'R4':{'R2':5,'R3':5,'R5':5},
'R5':{'R4':5}

}

graph_3 = {

'192.168.255.1':{'192.168.255.2':10,'192.168.255.3':10},
'192.168.255.2':{'192.168.255.1':10,'192.168.255.3':50},
'192.168.255.3':{'192.168.255.1':20,'192.168.255.2':50},
'192.168.255.4':{'192.168.255.3':20},
'192.168.255.3':{'192.168.255.4':20}
}

graph_4 = {
'R1':{'R2':5},
'R2':{'R1':5},
'R2':{'R3':5},
'R3':{'R2':5},
'R3':{'R4':5},
'R4':{'R3':5}
}

graph_5 = {

'A':{'B':5,'C':10,'E':2},
'B':{'A':5,'C':5},
'C':{'B':5,'A':10,'E':8,'D':4},
'D':{'C':4,'E':5},
'E':{'A':2,'D':5,'C':8}

}

def Dijkstra(g,start,end=None):

    d = {}  # dictionary of final distances
    p = {}  # dictionary of predecessors
    q = priorityDictionary()   # est.dist. of non-final vert.
    q[start] = 0
    for v in q:
        d[v] = q[v]
        if v == end: break
        for w in g[v]:
            vwLength = d[v] + g[v][w]
            if w in d:
                if vwLength < d[w]:
                    raise ValueError
            elif w not in q or vwLength < q[w]:
                q[w] = vwLength
                p[w] = [v]
            elif  w not in q or vwLength == q[w]:
                q[w] = vwLength
                p[w] += [v]
    return (d,p)

def shortestPath(g,start,end):

    d,p = Dijkstra(g,start,end)
    path = [[end]]
    while True:
        if len(p[end]) > 1:
            path.append(p[end])
            for node in p[end]:
                if node != start:
                    if ''.join(p[end]) == start: break
                    end = node
        path.append(p[end])
        if ''.join(p[end]) == start: break
        for node in p[end]:
            if node == start: break
            end = node
    return path[::-1]

print shortestPath(graph_2,'R1','R5')
print shortestPath(graph_3,'192.168.255.1','192.168.255.2')
print shortestPath(graph_4,'R1','R4')
print shortestPath(graph_5,'A','C')

and the output for each graph :

[['R1'], ['R2', 'R3'], ['R4'], ['R5']]
[['192.168.255.1'], ['192.168.255.2']]
[['R1'], ['R2'], ['R3'], ['R4']]
[['A'], ['A', 'E', 'B'], ['C']]


来源: stackexchange

问:
How to connect two stages of circles using CSS
Folks,

We are trying to connect two lines with different stages but it seems stage2 is moving to different line.

How to connect these two stages(circles) with lines so that they appear on same line. As of now always it is coming to new line.

Code below :

.circle {
  width: 10px;
  height: 10px;
  border-radius: 15px 15px 15px 15px;
  padding: 5px;
  background: white;
  border: 1px solid green;
}

.circle-inner {
  width: 10px;
  height: 10px;
  border-radius: 10px 10px 10px 10px;
  background: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><font face="Times New Roman" size="1">stage1</font>
<span class="circle" style="display:block">
 <span class="circle-inner" style="display:block"></span>
</span>
<hr style="height:1px; margin-top:-10px; border:none; color:#000; background-color:#000;width:80px;margin-left:22px">
<font face="Times New Roman" size="1">stage2</font>
</span>
<span class="circle" style="display:block">
 <span class="circle-inner" style="display:block"></span>
</span>
<hr style="height:1px; margin-top:-11px; border:none; color:#000; background-color:#000;width:80px;margin-left:22px"></code>```

答:
Try This:

.circle {
width: 10px;
height: 10px;
border-radius: 15px 15px 15px 15px;
padding:5px;
background: white;
border: 1px solid green;

}
.circle-inner {
  width: 10px;
  height: 10px;
  border-radius: 10px 10px 10px 10px;
  background: green;

}
.line_up {
  float:left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="line_up">
  <font face="Times New Roman" size="1">stage1</font>
  <span class="circle" style="display:block">
    <span class="circle-inner" style="display:block"></span>
  </span>
  <hr style="height:1px; margin-top:-10px; border:none; color:#000; background-color:#000;width:80px;margin-left:22px">
</div>
<div class="line_up">
  <font face="Times New Roman" size="1">stage2</font>
  <span class="circle" style="display:block">
    <span class="circle-inner" style="display:block"></span>
  </span>
  <hr style="height:1px; margin-top:-10px; border:none; color:#000; background-color:#000;width:80px;margin-left:22px">
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
Folks,

We are trying to connect two lines with different stages but it seems stage2 is moving to different line.

How to connect these two stages(circles) with lines so that they appear on same line. As of now always it is coming to new line.

Code below :

.circle {
  width: 10px;
  height: 10px;
  border-radius: 15px 15px 15px 15px;
  padding: 5px;
  background: white;
  border: 1px solid green;
}

.circle-inner {
  width: 10px;
  height: 10px;
  border-radius: 10px 10px 10px 10px;
  background: green;
}

stage1

stage2

Body:
Try This:

.circle {
width: 10px;
height: 10px;
border-radius: 15px 15px 15px 15px;
padding:5px;
background: white;
border: 1px solid green;

}
.circle-inner {
  width: 10px;
  height: 10px;
  border-radius: 10px 10px 10px 10px;
  background: green;

}
.line_up {
  float:left;
}

<div class="line_up">
  <font face="Times New Roman" size="1">stage1</font>
  <span class="circle" style="display:block">
    <span class="circle-inner" style="display:block"></span>
  </span>
  <hr style="height:1px; margin-top:-10px; border:none; color:#000; background-color:#000;width:80px;margin-left:22px">
</div>
<div class="line_up">
  <font face="Times New Roman" size="1">stage2</font>
  <span class="circle" style="display:block">
    <span class="circle-inner" style="display:block"></span>
  </span>
  <hr style="height:1px; margin-top:-10px; border:none; color:#000; background-color:#000;width:80px;margin-left:22px">
</div>


问:
Xamarin Forms listview out of memory error
In Xamarin Forms i have the following listview:

```<code><ListView x:Name="StudentView"  RowHeight="55"  SeparatorVisibility="None" CachingStrategy="RecycleElement">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="55"></RowDefinition>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                    </Grid.ColumnDefinitions>

                    <Image Source="{Binding Image}" Grid.Row="0" Grid.Column="0" Aspect="AspectFill"></Image>
                    <Image Source="{Binding Image}" Grid.Row="0" Grid.Column="1" Aspect="AspectFill"></Image>
                </Grid>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
</code>```

In the code behind i have declared an array of 1000 items.

The problem is that if i scroll up and down the listview, everytime i see in the xamarin profile that the memory usage increase and seems that CachingStrategy="RecycleElement" not work properly (tested on real android device).

After scroll some times, the program crash with out of memory.

What's the problem? How can i resolve it?

答:
I had the same issue , large list of images or images with large resolution causes this problem, I solved this by using FFImageLoading found here, also available on nuget , Also try to bind thumbnails instead of the actual Image if possible.

```<code><ContentPage xmlns:ci="clr-namespace:FFImageLoading.Forms;assembly=FFImageLoading.Forms">
<ci:CachedImage Source="{Binding ActualImageThumbnail}" Aspect="Fill"/>
</code>```

Body:
In Xamarin Forms i have the following listview:

<ListView x:Name="StudentView"  RowHeight="55"  SeparatorVisibility="None" CachingStrategy="RecycleElement">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="55"></RowDefinition>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                    </Grid.ColumnDefinitions>

                    <Image Source="{Binding Image}" Grid.Row="0" Grid.Column="0" Aspect="AspectFill"></Image>
                    <Image Source="{Binding Image}" Grid.Row="0" Grid.Column="1" Aspect="AspectFill"></Image>
                </Grid>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

In the code behind i have declared an array of 1000 items.

The problem is that if i scroll up and down the listview, everytime i see in the xamarin profile that the memory usage increase and seems that CachingStrategy="RecycleElement" not work properly (tested on real android device).

After scroll some times, the program crash with out of memory.

What's the problem? How can i resolve it?

Body:
I had the same issue , large list of images or images with large resolution causes this problem, I solved this by using FFImageLoading found here, also available on nuget , Also try to bind thumbnails instead of the actual Image if possible.

<ContentPage xmlns:ci="clr-namespace:FFImageLoading.Forms;assembly=FFImageLoading.Forms">
<ci:CachedImage Source="{Binding ActualImageThumbnail}" Aspect="Fill"/>


问:
Not getting the ASP response to work with JQuery AutoComplete
This is driving me nuts. I've tried solving this two days already browsing through many webpages.

I'd like to use the jquery-ui autocomplete functionality just exactly as the sample in http://jqueryui.com/resources/demos/autocomplete/remote-jsonp.html, but instead of calling search.php I need to call an ASP file (Microsoft IIS environment). So, I created a local copy of above mentioned HTML file and adjusted only the URL.

$(function() {
  function log(message) {
    $("
").text(message).prependTo("#log");
    $("#log").scrollTop(0);
  }

  $("#birds").autocomplete({
    source: function(request, response) {
      $.ajax({
        url: "http://jqueryui.com/resources/demos/autocomplete/search.php",
        dataType: "jsonp",
        data: {
          term: request.term
        },
        success: function(data) {
          response(data);
        }
      });
    },
    minLength: 2,
    select: function(event, ui) {
      log("Selected: " + ui.item.value + " aka " + ui.item.id);
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.ui-autocomplete-loading {
  background: white url("http://jqueryui.com/resources/demos/autocomplete/images/ui-anim_basic_16x16.gif") right center no-repeat;
}</code>```

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Remote JSONP datasource</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="http://jqueryui.com/resources/demos/style.css">

    Birds:
    <input id="birds">

    Result:

```
</div>
</div>
</p>

<ul>
<li>Now, when I set URL to search.php of jquery.com (cross-domain, from my web server to the file which is also used by the original HTML) it works a bit slow, but fine</li>
<li>When I try it with my local ASP file which is reading data from SQL it doesn't work although when I call the file directly in the browser it returns valid JSON data... I even changed the ASP file to do nothing than only a <code>Response.Write</code> with hard coded JSON data</li>
<li>I also tried it with <code>Response.ContentType = "application/json"</code>, but this didn't help either</li>
<li>Then I loaded an own search.php file which again only does a <code>echo</code> of some hardcoded JSON data to https://softd4u.ch/search.php and tried to call this, but again without success</li>
</ul>

<p>I found several samples in the Internet where the ASP file would be directly entered as source parameter (often older posts). I guess this might be working, but I think it makes sense to call the file via AJAX.</p>

<p>Trying to debug the <em>jquery-1.12.4.js</em> I at least found out that there is a 'parseerror' returned at one point, but I have no idea why and what I should do differently. At <code>function ajaxHandleResponses( s, jqXHR, responses )</code> the variable responses was undefined in the case when it worked, but had content iin the case when it didn't work.</p>

<p>I'm sure the files are actually called (checked logs etc.) but they never trigger the success function of the AJAX call.</p>

<p>Does anyone have an idea what I'm missing here?</p>

<p>Source of classic asp file - version 1 (DB connection etc. handled in inc file):</p>

```

<%
Dim errortextInternal, rs, search, sql
Dim coma

search = Request.QueryString("term")
sql = "SELECT TOP 20 itmId, itmNo, itmDescr1, itmDescr2, itmInact, CASE WHEN itsuSupId1 IS NULL THEN '' ELSE itsuSupId1 END AS SupId1, " & _
        "CASE WHEN itsuSupId2 IS NULL THEN '' ELSE itsuSupId2 END AS SupId2, " & _
        "CASE WHEN itsuSupId3 IS NULL THEN '' ELSE itsuSupId3 END AS SupId3 " & _
        "FROM Items LEFT JOIN ItemsSuppl ON itmId = itsuItmId WHERE "
sql = sql & " (itmNo LIKE '%" & search & "%' OR itmDescr1 LIKE '%" & search & "%' OR itmDescr2 LIKE '%" & search & "%' OR EXISTS " & _
            "(SELECT * FROM ItemsSuppl AS sub WHERE sub.itsuItmId = itmId AND (itsuSupId1 LIKE '%" & search & "%' OR itsuSupId2 LIKE '%" & search & "%' OR itsuSupId3 LIKE '%" & search & "%'))) ORDER BY itmNo, itmDescr1 "

'Response.ContentType = "application/json"
Response.Write("[")
coma = ""

Success = SelectDbRecords(errortextInternal, rs, sql)

If Success Then

    Do While Not rs.EOF
        Response.Write(coma & "{""id"":""" & rs("itmId") & """,""label"":""" & Server.HTMLEncode(rs("itmNo") & " - " & Trim(Trim(rs("itmDescr1")) & " " & Trim(rs("itmDescr2")))) & """,""value"":""" & Server.HTMLEncode(rs("itmNo") & " - " & Trim(Trim(rs("itmDescr1")) & " " & Trim(rs("itmDescr2")))) & """}")
        If coma = "" Then
            coma = ","
        End If
        rs.MoveNext
    Loop
    rs.ActiveConnection.Close

Else
    Response.Write("Fehler!")
End If

Response.Write("]")

%>
```

<p>Source of classic asp file - version 2 (hardcoded response for test purpose; no need to retrieve querystring):</p>

```<%@LANGUAGE="VBSCRIPT"%>
<%
Response.Write("[{""id"":""Nycticorax nycticorax"",""label"":""Black-crowned Night Heron"",""value"":""Black-crowned Night Heron""},{""id"":""Ardea purpurea"",""label"":""Purple Heron"",""value"":""Purple Heron""},{""id"":""Tetrao tetrix"",""label"":""Black Grouse"",""value"":""Black Grouse""},{""id"":""Caprimulgus europaeus"",""label"":""European Nightjar"",""value"":""European Nightjar""},{""id"":""Picus viridis"",""label"":""European Green Woodpecker"",""value"":""European Green Woodpecker""},{""id"":""Saxicola rubicola"",""label"":""European Stonechat"",""value"":""European Stonechat""},{""id"":""Luscinia svecica"",""label"":""Bluethroat"",""value"":""Bluethroat""},{""id"":""Ardea cinerea"",""label"":""Grey Heron"",""value"":""Grey Heron""},{""id"":""Corvus cornix"",""label"":""Hooded Crow"",""value"":""Hooded Crow""},{""id"":""Sylvia curruca"",""label"":""Lesser Whitethroat"",""value"":""Lesser Whitethroat""},{""id"":""Pluvialis apricaria"",""label"":""European Golden Plover"",""value"":""European Golden Plover""},{""id"":""Sylvia communis"",""label"":""Common Whitethroat"",""value"":""Common Whitethroat""}]")
%>
```

答:
So, this finally worked for me.

Form with search field:

```<code><!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>jQuery UI Autocomplete - Remote JSONP datasource</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="/resources/demos/style.css">
    <style>
    .ui-autocomplete-loading {
        background: white url("https://jqueryui.com/resources/demos/autocomplete/images/ui-anim_basic_16x16.gif") right center no-repeat;
    }
    </style>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script>
    $( function() {
        function log( message ) {
            $( "<div>" ).text( message ).prependTo( "#log" );
            $( "#log" ).scrollTop( 0 );
        }
        $( "#article" ).autocomplete({
            source: function( request, response ) {
                $.ajax( {
                    url: "itemSearchAj2.asp",
                    dataType: "json",
                    data: 'term=' + escape(request.term),
                    success: function( data ) {
                        console.log("Data: ", data)
                        response(data);
                    }
                } );
            },
            minLength: 2,
            select: function( event, ui ) {
                log( "Selected: " + ui.item.value + " aka " + ui.item.id );
            }
        } );
    } );
    </script>
</head>
<body>

<div class="ui-widget">
    <label for="article">Article: </label>
    <input id="article">
</div>

<div class="ui-widget" style="margin-top:2em; font-family:Arial">
    Result:
    <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>

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

itemSearchAj2.asp - The classic ASP response when using datatype: 'json'

```<code> <%@LANGUAGE="VBSCRIPT"%>
<%response.Expires=-1%>

<!-- #INCLUDE FILE="includes/global.inc" -->

<%
Dim errortextInternal, rs, con, search, sql
Dim coma, retVal, label

Set con = Server.CreateObject("ADODB.Connection")
Set rs = Server.CreateObject("ADODB.Recordset")

con.Open odbcname

search = Request.QueryString("term")
sql = "SELECT TOP 20 itmId, itmNo, itmDescr1, itmDescr2, itmInact, CASE WHEN itsuSupId1 IS NULL THEN '' ELSE itsuSupId1 END AS SupId1, " & _
        "CASE WHEN itsuSupId2 IS NULL THEN '' ELSE itsuSupId2 END AS SupId2, " & _
        "CASE WHEN itsuSupId3 IS NULL THEN '' ELSE itsuSupId3 END AS SupId3 " & _
        "FROM Items LEFT JOIN ItemsSuppl ON itmId = itsuItmId WHERE "
sql = sql & " (itmNo LIKE '%" & search & "%' OR itmDescr1 LIKE '%" & search & "%' OR itmDescr2 LIKE '%" & search & "%' OR EXISTS " & _
            "(SELECT * FROM ItemsSuppl AS sub WHERE sub.itsuItmId = itmId AND (itsuSupId1 LIKE '%" & search & "%' OR itsuSupId2 LIKE '%" & search & "%' OR itsuSupId3 LIKE '%" & search & "%'))) ORDER BY itmNo, itmDescr1 "

Response.CharSet = "ISO-8859-1"
Response.Write("[")
coma = ""
retVal = ""

rs.Open sql, con, 3, 3

Do While Not rs.EOF
    label = rs("itmNo") & " - " & Trim(Trim(rs("itmDescr1")) & " " & Trim(rs("itmDescr2")))
    retVal = retVal & coma & "{""id"":""" & rs("itmId") & """,""label"":""" & label & """,""value"":""" & label & """}"
    If coma = "" Then
        coma = ","
    End If
    rs.MoveNext
Loop

Response.Write(retVal)
Response.Write("]")

%>
</code>```

itemSearchAj2.asp - The same classic ASP response when using datatype: 'jsonp'

```<code><%@LANGUAGE="VBSCRIPT"%>
<%response.Expires=-1%>

<!-- #INCLUDE FILE="includes/global.inc" -->

<%
Dim errortextInternal, rs, con, search, sql
Dim coma, retVal, label

Set con = Server.CreateObject("ADODB.Connection")
Set rs = Server.CreateObject("ADODB.Recordset")

con.Open odbcname

search = Request.QueryString("term")
sql = "SELECT TOP 20 itmId, itmNo, itmDescr1, itmDescr2, itmInact, CASE WHEN itsuSupId1 IS NULL THEN '' ELSE itsuSupId1 END AS SupId1, " & _
        "CASE WHEN itsuSupId2 IS NULL THEN '' ELSE itsuSupId2 END AS SupId2, " & _
        "CASE WHEN itsuSupId3 IS NULL THEN '' ELSE itsuSupId3 END AS SupId3 " & _
        "FROM Items LEFT JOIN ItemsSuppl ON itmId = itsuItmId WHERE "
sql = sql & " (itmNo LIKE '%" & search & "%' OR itmDescr1 LIKE '%" & search & "%' OR itmDescr2 LIKE '%" & search & "%' OR EXISTS " & _
            "(SELECT * FROM ItemsSuppl AS sub WHERE sub.itsuItmId = itmId AND (itsuSupId1 LIKE '%" & search & "%' OR itsuSupId2 LIKE '%" & search & "%' OR itsuSupId3 LIKE '%" & search & "%'))) ORDER BY itmNo, itmDescr1 "

Response.CharSet = "ISO-8859-1"
Response.ContentType = "application/javascript"
Response.Write(Request.QueryString("callback") & "([")
coma = ""
retVal = ""

rs.Open sql, con, 3, 3

Do While Not rs.EOF
    label = rs("itmNo") & " - " & Trim(Trim(rs("itmDescr1")) & " " & Trim(rs("itmDescr2")))
    retVal = retVal & coma & "{""id"":""" & rs("itmId") & """,""label"":""" & label & """,""value"":""" & label & """}"
    If coma = "" Then
        coma = ","
    End If
    rs.MoveNext
Loop

Response.Write(retVal)
Response.Write("])")

%>
</code>```

Some of the problems I originally had might also have been, because I didn't specify <%response.Expires=-1%> in the ASP file at the beginning. So, I might have received cached responses because I always used similar search terms.

At the end I was mainly struggeling with character translation problems, since I'm using German expressions including Umlaute etc.
It didn't work for me when I tried using a Server.HTMLEncode together with Response.Write in the ASP file. What finally helped in there was the line Response.CharSet = "ISO-8859-1".

The second problem with characters was, when I typed Umlaute in the search field. Obviously data: { term: request.term } seems to automatically encodeURI the term, which then is not properly decoded again by the ASP file. The character 'ä' for instance is encoded as %C3%A4. When I instead use data: 'term=' + escape(request.term) the encoding is correct ('ä' becomes %E4). I know, escape() is deprecated, but again, encodeURI doesn't work for me.

Body:
This is driving me nuts. I've tried solving this two days already browsing through many webpages.

I'd like to use the jquery-ui autocomplete functionality just exactly as the sample in http://jqueryui.com/resources/demos/autocomplete/remote-jsonp.html, but instead of calling search.php I need to call an ASP file (Microsoft IIS environment). So, I created a local copy of above mentioned HTML file and adjusted only the URL.

$(function() {
  function log(message) {
    $("
").text(message).prependTo("#log");
    $("#log").scrollTop(0);
  }

  $("#birds").autocomplete({
    source: function(request, response) {
      $.ajax({
        url: "http://jqueryui.com/resources/demos/autocomplete/search.php",
        dataType: "jsonp",
        data: {
          term: request.term
        },
        success: function(data) {
          response(data);
        }
      });
    },
    minLength: 2,
    select: function(event, ui) {
      log("Selected: " + ui.item.value + " aka " + ui.item.id);
    }
  });
});

.ui-autocomplete-loading {
  background: white url("http://jqueryui.com/resources/demos/autocomplete/images/ui-anim_basic_16x16.gif") right center no-repeat;
}

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Remote JSONP datasource</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="http://jqueryui.com/resources/demos/style.css">

    Birds:
    <input id="birds">

    Result:

Now, when I set URL to search.php of jquery.com (cross-domain, from my web server to the file which is also used by the original HTML) it works a bit slow, but fine

When I try it with my local ASP file which is reading data from SQL it doesn't work although when I call the file directly in the browser it returns valid JSON data... I even changed the ASP file to do nothing than only a Response.Write with hard coded JSON data

I also tried it with Response.ContentType = "application/json", but this didn't help either

Then I loaded an own search.php file which again only does a echo of some hardcoded JSON data to https://softd4u.ch/search.php and tried to call this, but again without success

I found several samples in the Internet where the ASP file would be directly entered as source parameter (often older posts). I guess this might be working, but I think it makes sense to call the file via AJAX.

Trying to debug the jquery-1.12.4.js I at least found out that there is a 'parseerror' returned at one point, but I have no idea why and what I should do differently. At function ajaxHandleResponses( s, jqXHR, responses ) the variable responses was undefined in the case when it worked, but had content iin the case when it didn't work.

I'm sure the files are actually called (checked logs etc.) but they never trigger the success function of the AJAX call.

Does anyone have an idea what I'm missing here?

Source of classic asp file - version 1 (DB connection etc. handled in inc file):

<%
Dim errortextInternal, rs, search, sql
Dim coma

search = Request.QueryString("term")
sql = "SELECT TOP 20 itmId, itmNo, itmDescr1, itmDescr2, itmInact, CASE WHEN itsuSupId1 IS NULL THEN '' ELSE itsuSupId1 END AS SupId1, " & _
        "CASE WHEN itsuSupId2 IS NULL THEN '' ELSE itsuSupId2 END AS SupId2, " & _
        "CASE WHEN itsuSupId3 IS NULL THEN '' ELSE itsuSupId3 END AS SupId3 " & _
        "FROM Items LEFT JOIN ItemsSuppl ON itmId = itsuItmId WHERE "
sql = sql & " (itmNo LIKE '%" & search & "%' OR itmDescr1 LIKE '%" & search & "%' OR itmDescr2 LIKE '%" & search & "%' OR EXISTS " & _
            "(SELECT * FROM ItemsSuppl AS sub WHERE sub.itsuItmId = itmId AND (itsuSupId1 LIKE '%" & search & "%' OR itsuSupId2 LIKE '%" & search & "%' OR itsuSupId3 LIKE '%" & search & "%'))) ORDER BY itmNo, itmDescr1 "

'Response.ContentType = "application/json"
Response.Write("[")
coma = ""

Success = SelectDbRecords(errortextInternal, rs, sql)

If Success Then

    Do While Not rs.EOF
        Response.Write(coma & "{""id"":""" & rs("itmId") & """,""label"":""" & Server.HTMLEncode(rs("itmNo") & " - " & Trim(Trim(rs("itmDescr1")) & " " & Trim(rs("itmDescr2")))) & """,""value"":""" & Server.HTMLEncode(rs("itmNo") & " - " & Trim(Trim(rs("itmDescr1")) & " " & Trim(rs("itmDescr2")))) & """}")
        If coma = "" Then
            coma = ","
        End If
        rs.MoveNext
    Loop
    rs.ActiveConnection.Close

Else
    Response.Write("Fehler!")
End If

Response.Write("]")

%>

Source of classic asp file - version 2 (hardcoded response for test purpose; no need to retrieve querystring):

<%@LANGUAGE="VBSCRIPT"%>
<%
Response.Write("[{""id"":""Nycticorax nycticorax"",""label"":""Black-crowned Night Heron"",""value"":""Black-crowned Night Heron""},{""id"":""Ardea purpurea"",""label"":""Purple Heron"",""value"":""Purple Heron""},{""id"":""Tetrao tetrix"",""label"":""Black Grouse"",""value"":""Black Grouse""},{""id"":""Caprimulgus europaeus"",""label"":""European Nightjar"",""value"":""European Nightjar""},{""id"":""Picus viridis"",""label"":""European Green Woodpecker"",""value"":""European Green Woodpecker""},{""id"":""Saxicola rubicola"",""label"":""European Stonechat"",""value"":""European Stonechat""},{""id"":""Luscinia svecica"",""label"":""Bluethroat"",""value"":""Bluethroat""},{""id"":""Ardea cinerea"",""label"":""Grey Heron"",""value"":""Grey Heron""},{""id"":""Corvus cornix"",""label"":""Hooded Crow"",""value"":""Hooded Crow""},{""id"":""Sylvia curruca"",""label"":""Lesser Whitethroat"",""value"":""Lesser Whitethroat""},{""id"":""Pluvialis apricaria"",""label"":""European Golden Plover"",""value"":""European Golden Plover""},{""id"":""Sylvia communis"",""label"":""Common Whitethroat"",""value"":""Common Whitethroat""}]")
%>

Body:
So, this finally worked for me.

Form with search field:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>jQuery UI Autocomplete - Remote JSONP datasource</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="/resources/demos/style.css">
    <style>
    .ui-autocomplete-loading {
        background: white url("https://jqueryui.com/resources/demos/autocomplete/images/ui-anim_basic_16x16.gif") right center no-repeat;
    }
    </style>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script>
    $( function() {
        function log( message ) {
            $( "<div>" ).text( message ).prependTo( "#log" );
            $( "#log" ).scrollTop( 0 );
        }
        $( "#article" ).autocomplete({
            source: function( request, response ) {
                $.ajax( {
                    url: "itemSearchAj2.asp",
                    dataType: "json",
                    data: 'term=' + escape(request.term),
                    success: function( data ) {
                        console.log("Data: ", data)
                        response(data);
                    }
                } );
            },
            minLength: 2,
            select: function( event, ui ) {
                log( "Selected: " + ui.item.value + " aka " + ui.item.id );
            }
        } );
    } );
    </script>
</head>
<body>

<div class="ui-widget">
    <label for="article">Article: </label>
    <input id="article">
</div>

<div class="ui-widget" style="margin-top:2em; font-family:Arial">
    Result:
    <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>

</body>
</html>

itemSearchAj2.asp - The classic ASP response when using datatype: 'json'

 <%@LANGUAGE="VBSCRIPT"%>
<%response.Expires=-1%>

<!-- #INCLUDE FILE="includes/global.inc" -->

<%
Dim errortextInternal, rs, con, search, sql
Dim coma, retVal, label

Set con = Server.CreateObject("ADODB.Connection")
Set rs = Server.CreateObject("ADODB.Recordset")

con.Open odbcname

search = Request.QueryString("term")
sql = "SELECT TOP 20 itmId, itmNo, itmDescr1, itmDescr2, itmInact, CASE WHEN itsuSupId1 IS NULL THEN '' ELSE itsuSupId1 END AS SupId1, " & _
        "CASE WHEN itsuSupId2 IS NULL THEN '' ELSE itsuSupId2 END AS SupId2, " & _
        "CASE WHEN itsuSupId3 IS NULL THEN '' ELSE itsuSupId3 END AS SupId3 " & _
        "FROM Items LEFT JOIN ItemsSuppl ON itmId = itsuItmId WHERE "
sql = sql & " (itmNo LIKE '%" & search & "%' OR itmDescr1 LIKE '%" & search & "%' OR itmDescr2 LIKE '%" & search & "%' OR EXISTS " & _
            "(SELECT * FROM ItemsSuppl AS sub WHERE sub.itsuItmId = itmId AND (itsuSupId1 LIKE '%" & search & "%' OR itsuSupId2 LIKE '%" & search & "%' OR itsuSupId3 LIKE '%" & search & "%'))) ORDER BY itmNo, itmDescr1 "

Response.CharSet = "ISO-8859-1"
Response.Write("[")
coma = ""
retVal = ""

rs.Open sql, con, 3, 3

Do While Not rs.EOF
    label = rs("itmNo") & " - " & Trim(Trim(rs("itmDescr1")) & " " & Trim(rs("itmDescr2")))
    retVal = retVal & coma & "{""id"":""" & rs("itmId") & """,""label"":""" & label & """,""value"":""" & label & """}"
    If coma = "" Then
        coma = ","
    End If
    rs.MoveNext
Loop

Response.Write(retVal)
Response.Write("]")

%>

itemSearchAj2.asp - The same classic ASP response when using datatype: 'jsonp'

<%@LANGUAGE="VBSCRIPT"%>
<%response.Expires=-1%>

<!-- #INCLUDE FILE="includes/global.inc" -->

<%
Dim errortextInternal, rs, con, search, sql
Dim coma, retVal, label

Set con = Server.CreateObject("ADODB.Connection")
Set rs = Server.CreateObject("ADODB.Recordset")

con.Open odbcname

search = Request.QueryString("term")
sql = "SELECT TOP 20 itmId, itmNo, itmDescr1, itmDescr2, itmInact, CASE WHEN itsuSupId1 IS NULL THEN '' ELSE itsuSupId1 END AS SupId1, " & _
        "CASE WHEN itsuSupId2 IS NULL THEN '' ELSE itsuSupId2 END AS SupId2, " & _
        "CASE WHEN itsuSupId3 IS NULL THEN '' ELSE itsuSupId3 END AS SupId3 " & _
        "FROM Items LEFT JOIN ItemsSuppl ON itmId = itsuItmId WHERE "
sql = sql & " (itmNo LIKE '%" & search & "%' OR itmDescr1 LIKE '%" & search & "%' OR itmDescr2 LIKE '%" & search & "%' OR EXISTS " & _
            "(SELECT * FROM ItemsSuppl AS sub WHERE sub.itsuItmId = itmId AND (itsuSupId1 LIKE '%" & search & "%' OR itsuSupId2 LIKE '%" & search & "%' OR itsuSupId3 LIKE '%" & search & "%'))) ORDER BY itmNo, itmDescr1 "

Response.CharSet = "ISO-8859-1"
Response.ContentType = "application/javascript"
Response.Write(Request.QueryString("callback") & "([")
coma = ""
retVal = ""

rs.Open sql, con, 3, 3

Do While Not rs.EOF
    label = rs("itmNo") & " - " & Trim(Trim(rs("itmDescr1")) & " " & Trim(rs("itmDescr2")))
    retVal = retVal & coma & "{""id"":""" & rs("itmId") & """,""label"":""" & label & """,""value"":""" & label & """}"
    If coma = "" Then
        coma = ","
    End If
    rs.MoveNext
Loop

Response.Write(retVal)
Response.Write("])")

%>

Some of the problems I originally had might also have been, because I didn't specify <%response.Expires=-1%> in the ASP file at the beginning. So, I might have received cached responses because I always used similar search terms.

At the end I was mainly struggeling with character translation problems, since I'm using German expressions including Umlaute etc.
It didn't work for me when I tried using a Server.HTMLEncode together with Response.Write in the ASP file. What finally helped in there was the line Response.CharSet = "ISO-8859-1".

The second problem with characters was, when I typed Umlaute in the search field. Obviously data: { term: request.term } seems to automatically encodeURI the term, which then is not properly decoded again by the ASP file. The character 'ä' for instance is encoded as %C3%A4. When I instead use data: 'term=' + escape(request.term) the encoding is correct ('ä' becomes %E4). I know, escape() is deprecated, but again, encodeURI doesn't work for me.


问:
VBA runtime error 438 when generating emails
I have a problem where I get a runtime error 438 when trying to generate multiple emails in VBA. The first email generates fine, but additional emails when more than one cell in column F is 'yes' do not generate and the error happens. Here is the code in question below. Help appreciated, thanks</p>

```<code>Set OutApp = CreateObject("Outlook.Application")

On Error Resume Next
For Each cell In          ThisWorkbook.Sheets("Mailinfo").Columns("E").Cells.SpecialCells(xlCellTypeConstants)
If ThisWorkbook.Sheets("Mailinfo").cell.Value Like "?*@?*.?*" And _
   LCase(Cells(ThisWorkbook.Sheets("Mailinfo").cell.Row, "F").Value) = "yes" Then

    Set OutMail = OutApp.CreateItem(0)
    On Error Resume Next
    With OutMail
        .To = cell.Value
        .Subject = "Index Option RFQ"
        .CC = ThisWorkbook.Sheets("Mailinfo").Range("cc_email").Value
        .Importance = 2

        .HTMLBody = StrBody & RangetoHTML(rng) & "<br>" & "Thanks"

        'You can add files also like this
        '.Attachments.Add ("C:\test.txt")
        .Display  'Or use Send
    End With
    On Error GoTo 0
    Set OutMail = Nothing
End If
Next cell
</code>```

答:
Your For Each syntax is wrong. It should take this form (for example)

```<code>Dim r as range
For each r in ThisWorkbook.Worksheets("Sheet1").Range("A1:A10")
    r.Value = 1
Next r
</code>```

Notice how we've used r to represent each individual cell in A1:A10

```<code>For Each cell In ThisWorkbook.Sheets("Mailinfo").Columns("E").Cells.SpecialCells(xlCellTypeConstants)
    If cell.Value Like "?*@?*.?*" And LCase(cell.Offset(0, 1).Value) = "yes" Then
        Set OutMail = OutApp.CreateItem(0)
        On Error Resume Next
        With OutMail
            .To = cell.Value
            .Subject = "Index Option RFQ"
            .CC = ThisWorkbook.Sheets("Mailinfo").Range("cc_email").Value
            .Importance = 2

            .HTMLBody = StrBody & RangetoHTML(Rng) & "<br>" & "Thanks"

            'You can add files also like this
            '.Attachments.Add ("C:\test.txt")
            .Display  'Or use Send
        End With
        Set OutMail = Nothing
    End If
Next cell
</code>```

Note: as @MacroMan has pointed out below. Your error was confusing because you were masking previous errors with an On Error Resume Next statement. Using it in this way will cause more harm than good. My advice would always be to deal with each error specifically, rather than mask it.

Body:
I have a problem where I get a runtime error 438 when trying to generate multiple emails in VBA. The first email generates fine, but additional emails when more than one cell in column F is 'yes' do not generate and the error happens. Here is the code in question below. Help appreciated, thanks

Set OutApp = CreateObject("Outlook.Application")

On Error Resume Next
For Each cell In          ThisWorkbook.Sheets("Mailinfo").Columns("E").Cells.SpecialCells(xlCellTypeConstants)
If ThisWorkbook.Sheets("Mailinfo").cell.Value Like "?*@?*.?*" And _
   LCase(Cells(ThisWorkbook.Sheets("Mailinfo").cell.Row, "F").Value) = "yes" Then

    Set OutMail = OutApp.CreateItem(0)
    On Error Resume Next
    With OutMail
        .To = cell.Value
        .Subject = "Index Option RFQ"
        .CC = ThisWorkbook.Sheets("Mailinfo").Range("cc_email").Value
        .Importance = 2

        .HTMLBody = StrBody & RangetoHTML(rng) & "
" & "Thanks"

        'You can add files also like this
        '.Attachments.Add ("C:\test.txt")
        .Display  'Or use Send
    End With
    On Error GoTo 0
    Set OutMail = Nothing
End If
Next cell

Body:
Your For Each syntax is wrong. It should take this form (for example)

Dim r as range
For each r in ThisWorkbook.Worksheets("Sheet1").Range("A1:A10")
    r.Value = 1
Next r

Notice how we've used r to represent each individual cell in A1:A10

For Each cell In ThisWorkbook.Sheets("Mailinfo").Columns("E").Cells.SpecialCells(xlCellTypeConstants)
    If cell.Value Like "?*@?*.?*" And LCase(cell.Offset(0, 1).Value) = "yes" Then
        Set OutMail = OutApp.CreateItem(0)
        On Error Resume Next
        With OutMail
            .To = cell.Value
            .Subject = "Index Option RFQ"
            .CC = ThisWorkbook.Sheets("Mailinfo").Range("cc_email").Value
            .Importance = 2

            .HTMLBody = StrBody & RangetoHTML(Rng) & "<br>" & "Thanks"

            'You can add files also like this
            '.Attachments.Add ("C:\test.txt")
            .Display  'Or use Send
        End With
        Set OutMail = Nothing
    End If
Next cell

Note: as @MacroMan has pointed out below. Your error was confusing because you were masking previous errors with an On Error Resume Next statement. Using it in this way will cause more harm than good. My advice would always be to deal with each error specifically, rather than mask it.


问:
Interaction between Unlocked iPhone and iTunes
I just unlocked my iPhone 3G 4.1

My question is:
1) Can I sync the apps that I purchased previously before unlocking through iTunes?
2) Can this unlocked phone be used for iPhone development?
3) Will I be able to sync music through iTunes on this unlocked phone?

These questions may be silly. But I am a newbie.

Thanks!

答:
The answer is yes to all three questions.

I've done all three before I switched to android so I wouldn't have to!

However I don't think this is a stackoverflow question :)

ContentLicense: CC BY-SA 2.5


问:
C#: non-flag enum, is there any easier way for checking enum to match one of multiple values?
Here is the sample, CommandType is an enum. It's a none flag enum.

```<code>CommandType cmdType = CommandType.back;
if (cmdType == CommandType.back || cmdType == CommandType.forward || cmdType == CommandType.previous || cmdType == CommandType.home)
{
//do something
}
</code>```

Is there any way to simplify the "if" statement?

答:
How about a switch ?

```<code>switch(cmdType)
{
    case CommandType.back:
    case CommandType.forward:
    case CommandType.previous:
    case CommandType.home:
       // do something
       break;
}
</code>```

Body:
Here is the sample, CommandType is an enum. It's a none flag enum.

CommandType cmdType = CommandType.back;
if (cmdType == CommandType.back || cmdType == CommandType.forward || cmdType == CommandType.previous || cmdType == CommandType.home)
{
//do something
}

Is there any way to simplify the "if" statement?

Body:
How about a switch ?

switch(cmdType)
{
    case CommandType.back:
    case CommandType.forward:
    case CommandType.previous:
    case CommandType.home:
       // do something
       break;
}


问:
How to set different label for different view for a single model usign CreateView
I have a model that i am using in two view for two purpose.
how can i set different lebel for a field.

```<code>class ChapterCreate(CreateView):
model = models.Chapter
fields = [
    'title',
    'content',
    'order',
]
</code>```

I have tried with

```<code>class Chapter(models.Model):
    order = models.IntegerField(verbose_name= _('Chapter number'))
</code>```

but this changes to my model itself.
But i want to use same model in different view with different label field

答:
```<code>class ChapterCreate(CreateView):
    model = models.Chapter
    fields = [
        'title',
        'content',
        'order',
    ]
    labels = {
        'order' : 'Chapter number'
    }
</code>```

Body:
I have a model that i am using in two view for two purpose.
how can i set different lebel for a field.

class ChapterCreate(CreateView):
model = models.Chapter
fields = [
    'title',
    'content',
    'order',
]

I have tried with

class Chapter(models.Model):
    order = models.IntegerField(verbose_name= _('Chapter number'))

but this changes to my model itself.
But i want to use same model in different view with different label field


问:
How to share secret key for JWT in SSO
I wonder how to share secret key for my JWT between SSO and client? Does the secret key should be randomly generated whenever token is created?</p>

答:
If you want the client to verify the JWT, you can use an assymetric key pair (RSA) to issuing your JWT instead of a symmetric key (HMAC), then the token is signed with the private key and verified with the public.

The private key is stored securely in your server, and you provide the public key to the client. There is no security risk in sending the public key to the client or publish it. Avoid sharing a symmetric key (same key to sign and verify) with your client, because then he could create tokens

The secret key should generated randomly and be the same for all issued JWT

Title: How to share secret key for JWT in SSO


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答:
Started out in QBasic, so, I think it was something along:

```<code>INPUT "What's your name?", a$
PRINT "Hi, "; a$; "!"
</code>```

Being able to show something on the screen with PRINT was enough to get me excited about programming. Interactivity using INPUT was icing on the cake!

OwnerDisplayName: Michael Buen

LastEditorDisplayName: Triptych

Body:
Started out in QBasic, so, I think it was something along:

INPUT "What's your name?", a$
PRINT "Hi, "; a$; "!"

Being able to show something on the screen with PRINT was enough to get me excited about programming. Interactivity using INPUT was icing on the cake!

OwnerDisplayName: coobird


问:
one decimal for string format
I have below digits. I want to show one digit after to decimal. How to format it?

```<code>2.85
2
1.99
</code>```

I was using ("{0:0.0}". But data showing like

```<code>2.9 //It should be 2.8
2.0 //It should be 2
2.0 //It should be 1.9
</code>```

答:
```<code>Decimal[] decimals = { new Decimal(2.85), new Decimal(2), new Decimal(1.99) };

foreach (var x in decimals)
{
  Console.WriteLine(string.Format("{0:0.#}", Decimal.Truncate(x * 10) / 10));
}

// output
2.8
2
1.9
</code>```

Title: one decimal for string format

Body:
I have below digits. I want to show one digit after to decimal. How to format it?

2.85
2
1.99

I was using ("{0:0.0}". But data showing like

2.9 //It should be 2.8
2.0 //It should be 2
2.0 //It should be 1.9


问:
How to count sub data of customer in SQL
I have Customer table as following

```<code>CustomerId     CustomerName   CustomerEmail
1              AAA            AAA@AAA.com
2              BBB            BBB@BBB.BBB
</code>```

This is example data I have shown. Like this I have 50000 customer in customer table now their invoices are also stored in invoice table

```<code>InvoiceId      InvoiceAmount   InvoiceCustomerID
1              22.00           1
2              58.00           2
3              21.00           2
4              45.00           2
</code>```

Now I want to count the invoice for each customer when I show the customer listing, for example:

```<code>CustomerId     CustomerName   CustomerEmail  TotalInvoice
1              AAA            AAA@AAA.com    1
2              BBB            BBB@BBB.BBB    3
</code>```

I have used the following query but didnt worked

```<code>SELECT customer.*,COUNT(invoice.InvoiceId) FROM `customer` as customer INNER JOIN invoice as invoice ON customer.CustomerId= invoice.InvoiceCustomerID
</code>```

Can suggest any method to solve this ?

Also there is more then 5 lacks invoice so it's taking to much time to load.

答:
```<code>SELECT a.CustomerID, a.CustomerName, a.CustomerEmail,
SUM(CASE WHEN b.InvoiceID IS NOT NULL THEN 1 ELSE 0 END) as TotalInvoice
FROM `customer` a LEFT JOIN invoice b ON a.CustomerId= b.InvoiceCustomerID
GROUP BY a.CustomerId, a.CustomerName, a.CustomerEmail
</code>```

Just use GROUP BY
Also, do you need to display customers with no invoices? You're going to have to turn this into a left join if you do.

Body:
I have Customer table as following

CustomerId     CustomerName   CustomerEmail
1              AAA            AAA@AAA.com
2              BBB            BBB@BBB.BBB

This is example data I have shown. Like this I have 50000 customer in customer table now their invoices are also stored in invoice table

InvoiceId      InvoiceAmount   InvoiceCustomerID
1              22.00           1
2              58.00           2
3              21.00           2
4              45.00           2

Now I want to count the invoice for each customer when I show the customer listing, for example:

CustomerId     CustomerName   CustomerEmail  TotalInvoice
1              AAA            AAA@AAA.com    1
2              BBB            BBB@BBB.BBB    3

I have used the following query but didnt worked

SELECT customer.*,COUNT(invoice.InvoiceId) FROM `customer` as customer INNER JOIN invoice as invoice ON customer.CustomerId= invoice.InvoiceCustomerID

Can suggest any method to solve this ?

Also there is more then 5 lacks invoice so it's taking to much time to load.

Body:
SELECT a.CustomerID, a.CustomerName, a.CustomerEmail,
SUM(CASE WHEN b.InvoiceID IS NOT NULL THEN 1 ELSE 0 END) as TotalInvoice
FROM `customer` a LEFT JOIN invoice b ON a.CustomerId= b.InvoiceCustomerID
GROUP BY a.CustomerId, a.CustomerName, a.CustomerEmail

Just use GROUP BY
Also, do you need to display customers with no invoices? You're going to have to turn this into a left join if you do.


问:
Run jQuery after WooCommerce AJAX shipping method update
A jQuery function needs to initialize after shipping options have been updated, on the checkout page, through an ajax call, and the Woocommerce custom event updated_shipping_method has been triggered.

My jQuery snippet is set-up to listen to this event - but this is not functioning as intended.

```<code>jQuery( document.body ).on( 'updated_shipping_method', function(){
  // Code stuffs

  // has the function initialized after the event trigger?
  console.log('on updated_shipping_method: function fired');
});
</code>```

I've tried the updated_wc_div custom event as well to no avail.

I'm using a similar method, almost verbatim, on the cart page to listen to the custom event trigger for updated_cart_totals and it works perfectly. Not sure why this isn't the case for the checkout page.

答:
Correct Custom Event: updated_checkout

The code snippet in question was listening to the incorrect Woocommerce custom event.

The correct custom event to listen to in this case is updated_checkout.

When selecting a new shipping method, Woocommerce fires an ajax call to update the cart totals to reflect the price of the shipping method selected, then triggers updated_checkout.

So if updated_checkout is listened to, rather than updated_shipping_method, the script is fired as intended.

Body:
A jQuery function needs to initialize after shipping options have been updated, on the checkout page, through an ajax call, and the Woocommerce custom event updated_shipping_method has been triggered.

My jQuery snippet is set-up to listen to this event - but this is not functioning as intended.

jQuery( document.body ).on( 'updated_shipping_method', function(){
  // Code stuffs

  // has the function initialized after the event trigger?
  console.log('on updated_shipping_method: function fired');
});

I've tried the updated_wc_div custom event as well to no avail.

I'm using a similar method, almost verbatim, on the cart page to listen to the custom event trigger for updated_cart_totals and it works perfectly. Not sure why this isn't the case for the checkout page.


问:
Best way to iterate through a Perl array
Which is the best implementation(in terms of speed and memory usage) for iterating through a Perl array? Is there any better way? (@Array need not be retained).

Implementation 1

```<code>foreach (@Array)
{
      SubRoutine($_);
}
</code>```

Implementation 2

```<code>while($Element=shift(@Array))
{
      SubRoutine($Element);
}
</code>```

Implementation 3

```<code>while(scalar(@Array) !=0)
{
      $Element=shift(@Array);
      SubRoutine($Element);
}
</code>```

Implementation 4

```<code>for my $i (0 .. $#Array)
{
      SubRoutine($Array[$i]);
}
</code>```

Implementation 5

```<code>map { SubRoutine($_) } @Array ;
</code>```

答:
In single line to print the element or array.

print $_ for (@array);

NOTE: remember that $_ is internally referring to the element of @array in loop. Any changes made in $_ will reflect in @array;
ex.

```<code>my @array = qw( 1 2 3 );
for (@array) {
        $_ = $_ *2 ;
}
print "@array";
</code>```

output: 2 4 6

Body:
Which is the best implementation(in terms of speed and memory usage) for iterating through a Perl array? Is there any better way? (@Array need not be retained).

Implementation 1

foreach (@Array)
{
      SubRoutine($_);
}

Implementation 2

while($Element=shift(@Array))
{
      SubRoutine($Element);
}

Implementation 3

while(scalar(@Array) !=0)
{
      $Element=shift(@Array);
      SubRoutine($Element);
}

Implementation 4

for my $i (0 .. $#Array)
{
      SubRoutine($Array[$i]);
}

Implementation 5

map { SubRoutine($_) } @Array ;

Body:
In single line to print the element or array.

print $_ for (@array);

NOTE: remember that $_ is internally referring to the element of @array in loop. Any changes made in $_ will reflect in @array;
ex.

my @array = qw( 1 2 3 );
for (@array) {
        $_ = $_ *2 ;
}
print "@array";

output: 2 4 6


问:
How to pass class object in HttpActionContext.response?
I have created one API controller and implement ActionFilterAttribute and am trying to get result as a class object.</p>

```<code>public class AuthorizationAttribute : ActionFilterAttribute
{
    ErrorInformation objError = new ErrorInformation();

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (string.IsNullOrEmpty(token))
        {
            objError.ErrorMessage = "Missing Request Token";
            objError.StatusCode = Convert.ToInt16(HttpStatusCode.ExpectationFailed);
            objError.ErrorType = "";
            objError.ErrorCode = "E:101";

            actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest)
            {
                Content = new StringContent("Missing Request Token"),
            };

           // Here i want to pass my above class object 'objError' in 'actionContext.Response'
           // it is possible to pass 'objError' as a result ?**
            return;
        }
    }
}
</code>```

答:
After some research i have successfully resolved this issue as below.

```<code>public class AuthorizationAttribute : ActionFilterAttribute
{
    ErrorInformation objError = new ErrorInformation();

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (string.IsNullOrEmpty(token))
        {
            objError.ErrorMessage = "Missing Request Token";
            objError.StatusCode = Convert.ToInt16(HttpStatusCode.ExpectationFailed);
            objError.ErrorType = "";
            objError.ErrorCode = "E:101";

            //actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest)
            // {
            //    Content = new StringContent("Missing Request Token"),
            //};

           // For pass class object as a response
           var request = actionContext.Request;

           actionContext.Response = request.CreateResponse<ErrorInformation>(HttpStatusCode.BadRequest, objError);

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

Body:
I have created one API controller and implement ActionFilterAttribute and am trying to get result as a class object.

public class AuthorizationAttribute : ActionFilterAttribute
{
    ErrorInformation objError = new ErrorInformation();

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (string.IsNullOrEmpty(token))
        {
            objError.ErrorMessage = "Missing Request Token";
            objError.StatusCode = Convert.ToInt16(HttpStatusCode.ExpectationFailed);
            objError.ErrorType = "";
            objError.ErrorCode = "E:101";

            actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest)
            {
                Content = new StringContent("Missing Request Token"),
            };

           // Here i want to pass my above class object 'objError' in 'actionContext.Response'
           // it is possible to pass 'objError' as a result ?**
            return;
        }
    }
}

Body:
After some research i have successfully resolved this issue as below.

public class AuthorizationAttribute : ActionFilterAttribute
{
    ErrorInformation objError = new ErrorInformation();

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (string.IsNullOrEmpty(token))
        {
            objError.ErrorMessage = "Missing Request Token";
            objError.StatusCode = Convert.ToInt16(HttpStatusCode.ExpectationFailed);
            objError.ErrorType = "";
            objError.ErrorCode = "E:101";

            //actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest)
            // {
            //    Content = new StringContent("Missing Request Token"),
            //};

           // For pass class object as a response
           var request = actionContext.Request;

           actionContext.Response = request.CreateResponse<ErrorInformation>(HttpStatusCode.BadRequest, objError);

           return;
        }
    }
}


问:
How to include sharppcap library into Visual Studio?
Sorry for the noob question. I don't really know how to make sharppcap library working in my project. I'm using Visual Studio 2010.</p>

答:
In your application find Reference option, right click on it and select Add Reference. Choose your sharppacp.dll and add it.

At last write using sharppacp ; in your application.


答:
You can't use a grouping function without GROUP BY:</p>

```<code>SELECT customer.CustomerID, customer.Customer.Name, customer.CustomerEmail
    ,COUNT(invoice.InvoiceId) AS RC
FROM `customer` AS customer
INNER JOIN invoice AS invoice ON customer.CustomerId = invoice.InvoiceCustomerID
GROUP BY  customer.CustomerID, customer.Customer.Name, customer.CustomerEmail
</code>```

Title: How to count sub data of customer in SQL

Body:
You can't use a grouping function without GROUP BY:

SELECT customer.CustomerID, customer.Customer.Name, customer.CustomerEmail
    ,COUNT(invoice.InvoiceId) AS RC
FROM `customer` AS customer
INNER JOIN invoice AS invoice ON customer.CustomerId = invoice.InvoiceCustomerID
GROUP BY  customer.CustomerID, customer.Customer.Name, customer.CustomerEmail


问:
Vue 2.0 with click event handler
How do use vue2.0 with jquery onclick event method ? As i research on the particular question with defining an mounted of this.$el.addEventListener('click', this.onClick) on vue . but seems not really clear for me . I need an help from here. Kindly advise

As my code below jquery :

```<code>$(document).on("click",".ballNum li",function(){
        var robj = $(this);
        var value = robj.text();
            var bit = $(this).parents(".ballNum").attr("id");
            if(robj.attr("name")=="choice"){
                robj.removeAttr("name");
            }else{
                robj.attr("name","choice");
            }
            var isSave = saveNum(value,bit,"reverse");
            if(isSave==1){
                $(this).addClass("active");
            }else if(isSave==-1){
                $(this).removeClass("active");
            }else{
                layer.alert('Error',{icon: 0, title:'Alert'});
        }
</code>```

答:
I would guess something like this:

    <button v-on:click="greet">Greet</button>

Then in a Vue component:

```<code><script>
export default {

    methods: {
        greet:function(){

              }

    }//methods
}

</script>
</code>```

Then put your code from your method into the greet method.

But, I would start with learning some Vue.js by working through their documentation.

Mick

Title: Vue 2.0 with click event handler

Body:
How do use vue2.0 with jquery onclick event method ? As i research on the particular question with defining an mounted of this.$el.addEventListener('click', this.onClick) on vue . but seems not really clear for me . I need an help from here. Kindly advise

As my code below jquery :

$(document).on("click",".ballNum li",function(){
        var robj = $(this);
        var value = robj.text();
            var bit = $(this).parents(".ballNum").attr("id");
            if(robj.attr("name")=="choice"){
                robj.removeAttr("name");
            }else{
                robj.attr("name","choice");
            }
            var isSave = saveNum(value,bit,"reverse");
            if(isSave==1){
                $(this).addClass("active");
            }else if(isSave==-1){
                $(this).removeClass("active");
            }else{
                layer.alert('Error',{icon: 0, title:'Alert'});
        }

Body:
I would guess something like this:

    <button v-on:click="greet">Greet</button>

Then in a Vue component:

<script>
export default {

    methods: {
        greet:function(){

              }

    }//methods
}

</script>

Then put your code from your method into the greet method.

But, I would start with learning some Vue.js by working through their documentation.

Mick


问:
How to draw a chart with nonlinear x-axis (logarithmic scale)?
I am  trying to draw a Critical Power Chart like this:

The data I get is linear. One value for every second from 1 up to 18000.
I have no clue how to teach flot to draw an non-linear x-axis.
I tried to set custom ticks, but this seems to just have impact to the labels, not the line.

The x axis ticks will always be the same and don't need to be calculated:

```<code>[1s,5s,15s,30s,1m,2m,3m,5m,10m,20m30m,1h,2h,3h,5h]
</code>```

Playground including tons of data: https://jsfiddle.net/ogeo2ygx/6/

Code:

```<code>$.plot($("#cpChart"), [{data: data,label: "Critical Power", labelBoxBorderColor: 0, color: '#cbcbcb',yaxis:1,lines: { show: true, fill: true } }], {
        xaxes: [{
            //here should be some Magic to Draw an nice Critical Power Chart
            tickFormatter: (t, v) => {
                return t + "s";
            }
        }],
        yaxes: [{
            alignTicksWithAxis: 1,
            position: "left",
            tickFormatter: (t, v) => {
                return t.toFixed(0) + " Watt"
            }
        }],
        legend: {
            position: 'sw',
            labelBoxBorderColor: 0
        },
        colors: ["#1ab394"],
        grid: {
            color: "#999999",
            clickable: true,
            tickColor: "#D4D4D4",
            borderWidth: 0,
            hoverable: true
        }
    });
</code>```

答:
You can achieve that (which is called logarithmic scale) with two steps:

Transform the x-axis values using the Math.log function (with a +1 because the logarithm of zero is -infinity).

Define a custom ticks array with your ticks.

See the documentation for more information.
Relevant code:

```<code>xaxes: [{
    ticks: [[1, '1s'],[5, '5s'], [15, '15s'],[30, '30s'],[60, '1m'],[120, '2m'],[180, '3m'], [300, '5m'], [600, '10m'], [1200, '20m'], [1800, '30m'],[3600, '1h'], [7200, '2h'], [10800, '3h'], [18000, '5h']],
    transform: (x) => { return Math.log(1 + x); },
    inverseTransform: (x) => { return Math.exp(x) - 1; }
}],
</code>```

Updated fiddle: https://jsfiddle.net/ogeo2ygx/8/

ContentLicense: CC BY-SA 4.0

Body:
I am  trying to draw a Critical Power Chart like this:

The data I get is linear. One value for every second from 1 up to 18000.
I have no clue how to teach flot to draw an non-linear x-axis.
I tried to set custom ticks, but this seems to just have impact to the labels, not the line.

The x axis ticks will always be the same and don't need to be calculated:

[1s,5s,15s,30s,1m,2m,3m,5m,10m,20m30m,1h,2h,3h,5h]

Playground including tons of data: https://jsfiddle.net/ogeo2ygx/6/

Code:

$.plot($("#cpChart"), [{data: data,label: "Critical Power", labelBoxBorderColor: 0, color: '#cbcbcb',yaxis:1,lines: { show: true, fill: true } }], {
        xaxes: [{
            //here should be some Magic to Draw an nice Critical Power Chart
            tickFormatter: (t, v) => {
                return t + "s";
            }
        }],
        yaxes: [{
            alignTicksWithAxis: 1,
            position: "left",
            tickFormatter: (t, v) => {
                return t.toFixed(0) + " Watt"
            }
        }],
        legend: {
            position: 'sw',
            labelBoxBorderColor: 0
        },
        colors: ["#1ab394"],
        grid: {
            color: "#999999",
            clickable: true,
            tickColor: "#D4D4D4",
            borderWidth: 0,
            hoverable: true
        }
    });

Body:
You can achieve that (which is called logarithmic scale) with two steps:

Transform the x-axis values using the Math.log function (with a +1 because the logarithm of zero is -infinity).

Define a custom ticks array with your ticks.

See the documentation for more information.
Relevant code:

xaxes: [{
    ticks: [[1, '1s'],[5, '5s'], [15, '15s'],[30, '30s'],[60, '1m'],[120, '2m'],[180, '3m'], [300, '5m'], [600, '10m'], [1200, '20m'], [1800, '30m'],[3600, '1h'], [7200, '2h'], [10800, '3h'], [18000, '5h']],
    transform: (x) => { return Math.log(1 + x); },
    inverseTransform: (x) => { return Math.exp(x) - 1; }
}],

Updated fiddle: https://jsfiddle.net/ogeo2ygx/8/


问:
Android project cannot run why

I download the project from https://developer.android.com/training/implementing-navigation/nav-drawer.html Its name is NavigationDrawer.zip

答:
You can follow this step

```<code>1) press CTRL+ALT+SHIFT+S.
2) Under Project Setting go to Facets.
3) click + button and add Android-gradle.
4) select your project name.
5) Apply and ok.
6) Goto File and Invalidate cache / restart
</code>```

or you can check first either sdk-path is correct.

```<code>Open local.properties file and make sure it same with your path sdk.
</code>```

Example:

```<code># change the SDK path below to match the folder on your system
sdk.dir=D\:\\Android\\android-sdk
</code>```

Title: Android project cannot run why

Body:
You can follow this step

1) press CTRL+ALT+SHIFT+S.
2) Under Project Setting go to Facets.
3) click + button and add Android-gradle.
4) select your project name.
5) Apply and ok.
6) Goto File and Invalidate cache / restart

or you can check first either sdk-path is correct.

Open local.properties file and make sure it same with your path sdk.

Example:

# change the SDK path below to match the folder on your system
sdk.dir=D\:\\Android\\android-sdk


答:
You can always use a switch statement. It performs better and can be more readable:</p>

```<code>switch (cmdType)
{
    case CommandType.back:
    case CommandType.forward:
    case CommandType.previous:
    case CommandType.home:
        //do somehting
        break;
    default:
        //do something else
        break;
}
</code>```

Title: C#: non-flag enum, is there any easier way for checking enum to match one of multiple values?

Body:
Here is the sample, CommandType is an enum. It's a none flag enum.

CommandType cmdType = CommandType.back;
if (cmdType == CommandType.back || cmdType == CommandType.forward || cmdType == CommandType.previous || cmdType == CommandType.home)
{
//do something
}

Is there any way to simplify the "if" statement?

Body:
You can always use a switch statement. It performs better and can be more readable:

switch (cmdType)
{
    case CommandType.back:
    case CommandType.forward:
    case CommandType.previous:
    case CommandType.home:
        //do somehting
        break;
    default:
        //do something else
        break;
}


问:
Regex email check not working correctly
I have a problem with my regex. I didn't test this before. I have the following regex:

```<code>^(?:(?:[a-z])+(.|_)?(?!\.))*\w@(?:(?:[a-z])+(-|.)?(?!\.))*\w\.\w{2,}$
</code>```

Now, my email validation halfly works. Here are some tests (according to regex101):

```<code>test -- invalid
test@ -- invalid
test@test -- invalid
test@test. -- invalid
test@test.de -- valid
test@test.de. -- invalid
test@test@test.com -- valid
test...test@test.com -- invalid
</code>```

So, more than one @ can be used which is invalid for an email.

I kind of cannot see what I'm doing wrong.

NOTE:

I know there's a stackoverflow question that has a method on how to validate email with regex, HOWEVER: I'd like to know what I did wrong so I can learn from it.

答:
I found out the problem myself. The following regex does work:

```<code>^(?:(?:\w)+(\.|_)?(?!\.))*\w@(?:(?:[a-z])+(-|\.)?(?!\.))*[a-z]\.[a-z]{2,}$
</code>```

I changed (.|_) into (\.|_) and (-|.) into (-|\.) to use . literally as a period and not as an 'all character "wildcard"'. I changed \w\.\w{2,} in [a-z]\.[a-z]{2,} to disallow _ in the last part.

Title: Regex email check not working correctly

Body:
I have a problem with my regex. I didn't test this before. I have the following regex:

^(?:(?:[a-z])+(.|_)?(?!\.))*\w@(?:(?:[a-z])+(-|.)?(?!\.))*\w\.\w{2,}$

Now, my email validation halfly works. Here are some tests (according to regex101):

test -- invalid
test@ -- invalid
test@test -- invalid
test@test. -- invalid
test@test.de -- valid
test@test.de. -- invalid
test@test@test.com -- valid
test...test@test.com -- invalid

So, more than one @ can be used which is invalid for an email.

I kind of cannot see what I'm doing wrong.

NOTE:

I know there's a stackoverflow question that has a method on how to validate email with regex, HOWEVER: I'd like to know what I did wrong so I can learn from it.

Body:
I found out the problem myself. The following regex does work:

^(?:(?:\w)+(\.|_)?(?!\.))*\w@(?:(?:[a-z])+(-|\.)?(?!\.))*[a-z]\.[a-z]{2,}$

I changed (.|_) into (\.|_) and (-|.) into (-|\.) to use . literally as a period and not as an 'all character "wildcard"'. I changed \w\.\w{2,} in [a-z]\.[a-z]{2,} to disallow _ in the last part.


问:
why can't I get the string while scraping with python?
here is my code i want to scrape a list of words from a website,
but when i call the .string on the

```<code>import requests
from bs4 import BeautifulSoup

url = "https://www.merriam-webster.com/browse/thesaurus/a"
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "html.parser")
entry_view = soup.find_all('div', {'class': 'entries'})
view = entry_view[0]
list = view.ul

for m in list:
    for x in m:
        title = x.string
        print(title)
</code>```

what I want is a list printing the text from the website but what I get is an error

```<code>Traceback (most recent call last):
  File "/home/vidu/PycharmProjects/untitled/hello.py", line 14, in <module>
    title = x.string
AttributeError: 'str' object has no attribute 'string'
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook
    from apport.fileutils import likely_packaged, get_recent_crashes
  File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
    from apport.report import Report
  File "/usr/lib/python3/dist-packages/apport/report.py", line 30, in <module>
    import apport.fileutils
  File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 23, in <module>
    from apport.packaging_impl import impl as packaging
  File "/usr/lib/python3/dist-packages/apport/packaging_impl.py", line 23, in <module>
    import apt
  File "/usr/lib/python3/dist-packages/apt/__init__.py", line 23, in <module>
    import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'

Original exception was:
Traceback (most recent call last):
  File "/home/vidu/PycharmProjects/untitled/hello.py", line 14, in <module>
    title = x.string
AttributeError: 'str' object has no attribute 'string'
</code>```

答:
AttributeError: 'str' object has no attribute 'string'

This is telling you that the object is already a string. Try removing that and it should work.

It also tells you that the proper syntax of the string data type is str not string.

Another thing to take home from this is that you convert using title = str(x), but since it is already a string in this case it is redundant.

To quote Google:

Python has a built-in string class named "str" with many handy features (there is an older module named "string" which you should not use)

Body:
here is my code i want to scrape a list of words from a website,
but when i call the .string on the

import requests
from bs4 import BeautifulSoup

url = "https://www.merriam-webster.com/browse/thesaurus/a"
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "html.parser")
entry_view = soup.find_all('div', {'class': 'entries'})
view = entry_view[0]
list = view.ul

for m in list:
    for x in m:
        title = x.string
        print(title)

what I want is a list printing the text from the website but what I get is an error

Traceback (most recent call last):
  File "/home/vidu/PycharmProjects/untitled/hello.py", line 14, in <module>
    title = x.string
AttributeError: 'str' object has no attribute 'string'
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook
    from apport.fileutils import likely_packaged, get_recent_crashes
  File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
    from apport.report import Report
  File "/usr/lib/python3/dist-packages/apport/report.py", line 30, in <module>
    import apport.fileutils
  File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 23, in <module>
    from apport.packaging_impl import impl as packaging
  File "/usr/lib/python3/dist-packages/apport/packaging_impl.py", line 23, in <module>
    import apt
  File "/usr/lib/python3/dist-packages/apt/__init__.py", line 23, in <module>
    import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'

Original exception was:
Traceback (most recent call last):
  File "/home/vidu/PycharmProjects/untitled/hello.py", line 14, in <module>
    title = x.string
AttributeError: 'str' object has no attribute 'string'


问:
How to make a step-by-step choice?
There is a task. It is necessary to give the user a choice in the first step between 3 (input radio). After he chose one of the items he needed, a second column appears with the new column (input radio). And also after the choice in the second step appears the third step with the final choice (input radio).

It is important that the second step and the third for each selected item are new.

Help solve this problem.

I found a similar task, but it's a little unsuitable for my purposes.
Updating button content based on selection
for example

$(document).ready(function(){
  var selects = $('.drop-down');
  selects.not(':eq(0)').prop('disabled', true);
  selects.on('change', function() {
    var select = $(this),
        currentIndex = selects.index(select),
        nextIndex = currentIndex + 1;

    if (currentIndex != selects.length - 1) {
      selects.slice(nextIndex)
             .val('')
             .prop('disabled', true);

      selects.eq(nextIndex).prop('disabled', select.val() === '');
    }

  })

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="v1" class="drop-down">
  <option value="">--Выберите Вид рекламы--</option>
  <option value="1">Объявление [Товар / Услуга]</option>
  <option value="2">Визитная карточка</option>
  <option value="3">Статический баннер</option>
</select><br>
<select name="v2" class="drop-down">
  <option value="">--Выберите раздел--</option>
  <option value="1">Товары</option>
  <option value="2">Услуги</option>
  <option value="3">Компании</option>
  <option value="4">Биржа</option>
  <option value="5">Публикации</option>
</select><br>
<select name="v3" class="drop-down">
  <option value="">--Конечная категория--</option>
  <option value="1">Весь раздел</option>
  <option value="2">Главная страница</option>
  <option value="3">Категория товара</option>
  <option value="4">Отдельный товар</option>
</select></code>```

答:
Try this:

jsFiddle example: https://jsfiddle.net/7c297a3w/

Javascript

```<code>$('input[type="radio"][name^="group-"]').change(function() {
  var container = $(this).parent().parent();
  var nextSiblings = container.nextAll();
  nextSiblings.removeClass('valid');
  nextSiblings.find('input[type="radio"]').attr('checked', false);
  container.addClass('valid');
});
</code>```

CSS

```<code>[id^="step-"] {
  display: table-cell;
  width: 1%;
}

[id^="step-"]:not(:first-child) label {
  opacity: .3;
  pointer-events: none;
}

[id^="step-"].valid+[id^="step-"] label {
  opacity: 1;
  pointer-events: auto;
}

label {
  display: block;
}
</code>```

HTML

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="step-1">
  Step 1
  <label><input type="radio" name="group-1" value="1" required>1</label>
  <label><input type="radio" name="group-1" value="2">2</label>
  <label><input type="radio" name="group-1" value="3">3</label>
  <label><input type="radio" name="group-1" value="4">4</label>
  <label><input type="radio" name="group-1" value="5">5</label>
</div>
<div id="step-2">
  Step 2
  <label><input type="radio" name="group-2" value="a" required>a</label>
  <label><input type="radio" name="group-2" value="b">b</label>
  <label><input type="radio" name="group-2" value="c">c</label>
  <label><input type="radio" name="group-2" value="d">d</label>
  <label><input type="radio" name="group-2" value="e">e</label>
</div>
<div id="step-3">
  Step 3
  <label><input type="radio" name="group-3" value="i" required>i</label>
  <label><input type="radio" name="group-3" value="ii">ii</label>
  <label><input type="radio" name="group-3" value="iii">iii</label>
  <label><input type="radio" name="group-3" value="iv">iv</label>
  <label><input type="radio" name="group-3" value="v">v</label>
</div>
</code>```

Title: How to make a step-by-step choice?

Body:
There is a task. It is necessary to give the user a choice in the first step between 3 (input radio). After he chose one of the items he needed, a second column appears with the new column (input radio). And also after the choice in the second step appears the third step with the final choice (input radio).

It is important that the second step and the third for each selected item are new.

Help solve this problem.

I found a similar task, but it's a little unsuitable for my purposes.
Updating button content based on selection
for example

$(document).ready(function(){
  var selects = $('.drop-down');
  selects.not(':eq(0)').prop('disabled', true);
  selects.on('change', function() {
    var select = $(this),
        currentIndex = selects.index(select),
        nextIndex = currentIndex + 1;

    if (currentIndex != selects.length - 1) {
      selects.slice(nextIndex)
             .val('')
             .prop('disabled', true);

      selects.eq(nextIndex).prop('disabled', select.val() === '');
    }

  })

});

<select name="v1" class="drop-down">
  <option value="">--Выберите Вид рекламы--</option>
  <option value="1">Объявление [Товар / Услуга]</option>
  <option value="2">Визитная карточка</option>
  <option value="3">Статический баннер</option>
</select>

<select name="v2" class="drop-down">
  <option value="">--Выберите раздел--</option>
  <option value="1">Товары</option>
  <option value="2">Услуги</option>
  <option value="3">Компании</option>
  <option value="4">Биржа</option>
  <option value="5">Публикации</option>
</select>

<select name="v3" class="drop-down">
  <option value="">--Конечная категория--</option>
  <option value="1">Весь раздел</option>
  <option value="2">Главная страница</option>
  <option value="3">Категория товара</option>
  <option value="4">Отдельный товар</option>
</select>

Body:
Try this:

jsFiddle example: https://jsfiddle.net/7c297a3w/

Javascript

$('input[type="radio"][name^="group-"]').change(function() {
  var container = $(this).parent().parent();
  var nextSiblings = container.nextAll();
  nextSiblings.removeClass('valid');
  nextSiblings.find('input[type="radio"]').attr('checked', false);
  container.addClass('valid');
});

CSS

[id^="step-"] {
  display: table-cell;
  width: 1%;
}

[id^="step-"]:not(:first-child) label {
  opacity: .3;
  pointer-events: none;
}

[id^="step-"].valid+[id^="step-"] label {
  opacity: 1;
  pointer-events: auto;
}

label {
  display: block;
}

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="step-1">
  Step 1
  <label><input type="radio" name="group-1" value="1" required>1</label>
  <label><input type="radio" name="group-1" value="2">2</label>
  <label><input type="radio" name="group-1" value="3">3</label>
  <label><input type="radio" name="group-1" value="4">4</label>
  <label><input type="radio" name="group-1" value="5">5</label>
</div>
<div id="step-2">
  Step 2
  <label><input type="radio" name="group-2" value="a" required>a</label>
  <label><input type="radio" name="group-2" value="b">b</label>
  <label><input type="radio" name="group-2" value="c">c</label>
  <label><input type="radio" name="group-2" value="d">d</label>
  <label><input type="radio" name="group-2" value="e">e</label>
</div>
<div id="step-3">
  Step 3
  <label><input type="radio" name="group-3" value="i" required>i</label>
  <label><input type="radio" name="group-3" value="ii">ii</label>
  <label><input type="radio" name="group-3" value="iii">iii</label>
  <label><input type="radio" name="group-3" value="iv">iv</label>
  <label><input type="radio" name="group-3" value="v">v</label>
</div>


问:
php imagecropauto() not working
I've written some code that copies a chunk of a big image to a new smaller image and saves it to the server. That all works just fine

However, I would like it to trim off any white background around the text and this is the part that doesn't work

Here is my code

```<code>$sourceImage = imagecreatefromjpeg($image);
$tempImg = imagecreatetruecolor($data[2],$data[3]);
imagecopy($tempImg,$sourceImage, 0, 0, $data[0], $data[1], $data[2], $data[3]);
imagejpeg($tempImg,$destImage,90);
imagedestroy($tempImg);
chmod($destImage,0775);
// these next two lines don't work
$original_img = imagecreatefromjpeg($destImage);
$cropped_destImage = imagecropauto($original_img , IMG_CROP_THRESHOLD, 2, 16777215);
</code>```

Can anyone see what I'm doing wrong here ?

Thanks

答:
I have looked for you and this is what i found:
PHP GD Text with Transparency/Alpha background

This person had a similar problem. It could be worthwhile to read this topic because it has useful pieces of codes to deal with text that already has a background in it.

Title: php imagecropauto() not working

Body:
I've written some code that copies a chunk of a big image to a new smaller image and saves it to the server. That all works just fine

However, I would like it to trim off any white background around the text and this is the part that doesn't work

Here is my code

$sourceImage = imagecreatefromjpeg($image);
$tempImg = imagecreatetruecolor($data[2],$data[3]);
imagecopy($tempImg,$sourceImage, 0, 0, $data[0], $data[1], $data[2], $data[3]);
imagejpeg($tempImg,$destImage,90);
imagedestroy($tempImg);
chmod($destImage,0775);
// these next two lines don't work
$original_img = imagecreatefromjpeg($destImage);
$cropped_destImage = imagecropauto($original_img , IMG_CROP_THRESHOLD, 2, 16777215);

Can anyone see what I'm doing wrong here ?

Thanks


问:
Maintaining GlobalProtractorConf and multiple config files
In my project, I created a protractor.config.js file and driving it with grunt. I would like to have one globalProtractor.conf and multiple config.js and maintain them like a child conf for executing different test suites and to skip the common things like On prepare function or multi capacities or global variables in all the conf.

In my globalprotractor.conf I have the

```<code>seleniumAddress: {
         selenium: 'http:......'
     },
</code>```

I need to override this in the child conf. Is there any specific way to do this?

答:
That's a great question and I guess that's a pretty reasonable requirement in huge test projects. I came up with below approach. Let me know if that works !!

Have global config at one place - globalConf.js

```<code>//Declare all your global configuration here which is common across all suites

var globalConf = {
    seleniumAddress: 'http://localhost:4444/wd/hub',
    localSeleniumStandaloneOpts: {
        jvmArgs: ["-Dwebdriver.ie.driver=C://IEDriverServer_x64_2.53.1.exe"]
    },
    framework: 'jasmine',
    jasmineNodeOpts: {
        showColors: true,
        defaultTimeoutInterval: 120000,
        includeStackTrace: true,
        isVerbose: true,
    },
    capabilities: {
        browserName: 'chrome',
    },
    onPrepare: function () {
        browser.getProcessedConfig().then(function(data){
            console.log(data);
        });
    },
    allScriptsTimeout: 120000,
    getPageTimeout: 120000,
    afterLaunch: function (exitCode) {
    }
}

//Export the global configuration to be called in local config files
module.exports = globalConf;
</code>```

Then have multiple conf files which will import the globalConf and have suite specific changes

conf1.js

```<code>//Import Global Configuration file
var globalConf = require('./globalConf.js');

//Clone the global configuration object. You can follow any cloning mechanism
var localConf = JSON.parse(JSON.stringify(globalConf));

//Make custom changes to suit your suite. May be add Suites or anything thats at suite level
localConf['specs'] = 'test.js';

// Set the value of exports.config based on
exports.config = localConf;
</code>```

conf2.js

```<code>//Import Global Configuration file
var globalConf = require('./globalConf.js');

//Clone the global configuration object. You can follow any cloning mechanism
var localConf = JSON.parse(JSON.stringify(globalConf));

//Make custom changes to suit your suite. May be add Suites or anything thats at suite level
localConf['specs'] = 'test2.js';

// Set the value of exports.config based on
exports.config = localConf;
</code>```

Body:
In my project, I created a protractor.config.js file and driving it with grunt. I would like to have one globalProtractor.conf and multiple config.js and maintain them like a child conf for executing different test suites and to skip the common things like On prepare function or multi capacities or global variables in all the conf.

In my globalprotractor.conf I have the

seleniumAddress: {
         selenium: 'http:......'
     },

I need to override this in the child conf. Is there any specific way to do this?

Body:
That's a great question and I guess that's a pretty reasonable requirement in huge test projects. I came up with below approach. Let me know if that works !!

Have global config at one place - globalConf.js

//Declare all your global configuration here which is common across all suites

var globalConf = {
    seleniumAddress: 'http://localhost:4444/wd/hub',
    localSeleniumStandaloneOpts: {
        jvmArgs: ["-Dwebdriver.ie.driver=C://IEDriverServer_x64_2.53.1.exe"]
    },
    framework: 'jasmine',
    jasmineNodeOpts: {
        showColors: true,
        defaultTimeoutInterval: 120000,
        includeStackTrace: true,
        isVerbose: true,
    },
    capabilities: {
        browserName: 'chrome',
    },
    onPrepare: function () {
        browser.getProcessedConfig().then(function(data){
            console.log(data);
        });
    },
    allScriptsTimeout: 120000,
    getPageTimeout: 120000,
    afterLaunch: function (exitCode) {
    }
}

//Export the global configuration to be called in local config files
module.exports = globalConf;

Then have multiple conf files which will import the globalConf and have suite specific changes

conf1.js

//Import Global Configuration file
var globalConf = require('./globalConf.js');

//Clone the global configuration object. You can follow any cloning mechanism
var localConf = JSON.parse(JSON.stringify(globalConf));

//Make custom changes to suit your suite. May be add Suites or anything thats at suite level
localConf['specs'] = 'test.js';

// Set the value of exports.config based on
exports.config = localConf;

conf2.js

//Import Global Configuration file
var globalConf = require('./globalConf.js');

//Clone the global configuration object. You can follow any cloning mechanism
var localConf = JSON.parse(JSON.stringify(globalConf));

//Make custom changes to suit your suite. May be add Suites or anything thats at suite level
localConf['specs'] = 'test2.js';

// Set the value of exports.config based on
exports.config = localConf;


问:
PHP Array Select Random Value on Refresh
I have Submit button on Page. Once I click each time it should give random different result.

I have below array code

```<code>$qty = 10;
$array = array(4 => 2, 6 => 5, 7 => 10, 8 => 1, 10 => 5);
$array = arsort($array);
echo "```";
print_r($array);
//array_rand($array);
exit;
```

<p>Array pair is Customer & It's Quantity. I need to compare <code>$qty</code> with array's highest value. If it matches then take that value out & print out final result.</p>

<p>It is not necessary to assign 100% qty to each customer. But in the end 10 qty should assign overall.</p>

<p>So output can be</p>

<p>1st Click on Submit Button</p>

```Array
(
    [7] => 10
)
```

<p>2nd Click on Submit Button</p>

```Array
(
    [7] => 2
    [6] => 2
    [10] => 2
    [4] => 2
    [8] => 2
)
```

<p>3rd Click on Submit Button</p>

```Array
(
    [7] => 5
    [6] => 2
    [10] => 3
)
```

答:
I have added inline comments that might help you to get:

Demo here

```<code><?php
$qty   = 10;
$array = array(4 => 2, 6 => 5, 7 => 10, 8 => 1, 10 => 5);

$final_array = [];

while ($qty > 0) {
    $rand_index = array_rand($array);  // Get random customer
    $max_val    = $array[$rand_index]; // Get the maximum qty available for the customer

    if (!$max_val) {
        continue;
    }

    if ($max_val > $qty) {
        $max_val = $qty;
    }

    $possible_val = rand(1, $max_val); // Assign random qty to the customer but not more than allowed

    // Check if customer is added with qty already, if not add
    if (array_key_exists($rand_index, $final_array)) {
        $final_array[$rand_index] += $possible_val;
    } else {
        $final_array[$rand_index] = $possible_val;
    }

    $array[$rand_index] -= $possible_val;
    $qty -= $possible_val;
}

print_r($final_array); // Your final desired combination
</code>```

Body:
I have Submit button on Page. Once I click each time it should give random different result.

I have below array code

$qty = 10;
$array = array(4 => 2, 6 => 5, 7 => 10, 8 => 1, 10 => 5);
$array = arsort($array);
echo "
";
print_r($array);
//array_rand($array);
exit;

Array pair is Customer & It's Quantity. I need to compare $qty with array's highest value. If it matches then take that value out & print out final result.

It is not necessary to assign 100% qty to each customer. But in the end 10 qty should assign overall.

So output can be

1st Click on Submit Button

Array
(
    [7] => 10
)

2nd Click on Submit Button

Array
(
    [7] => 2
    [6] => 2
    [10] => 2
    [4] => 2
    [8] => 2
)

3rd Click on Submit Button

Array
(
    [7] => 5
    [6] => 2
    [10] => 3
)

Body:
I have added inline comments that might help you to get:

Demo here

<?php
$qty   = 10;
$array = array(4 => 2, 6 => 5, 7 => 10, 8 => 1, 10 => 5);

$final_array = [];

while ($qty > 0) {
    $rand_index = array_rand($array);  // Get random customer
    $max_val    = $array[$rand_index]; // Get the maximum qty available for the customer

    if (!$max_val) {
        continue;
    }

    if ($max_val > $qty) {
        $max_val = $qty;
    }

    $possible_val = rand(1, $max_val); // Assign random qty to the customer but not more than allowed

    // Check if customer is added with qty already, if not add
    if (array_key_exists($rand_index, $final_array)) {
        $final_array[$rand_index] += $possible_val;
    } else {
        $final_array[$rand_index] = $possible_val;
    }

    $array[$rand_index] -= $possible_val;
    $qty -= $possible_val;
}

print_r($final_array); // Your final desired combination