问:
Why is this select so slow (SqlServer)?
We have 3 nested selects that are each creating temporary table. The outer two go very fast. But the inner one (below takes about 1/4 second sometimes to execute. It's creating a table with 7 rows, each holding a date:

```<code>declare @StartDate datetime
declare @EndDate datetime
select @StartDate = cast(@Weeks_Loop_TheDate as date),  @EndDate = cast((@Weeks_Loop_TheDate + 6) as date)

declare @temp3  table
(
TheDate datetime
)
while (@StartDate<=@EndDate)
begin
insert into @temp3
values (@StartDate )
select @StartDate=DATEADD(dd,1,@StartDate)
end
select * from @temp3
</code>```

The params are set with a DateTime variable so the cast shouldn't be significant. And the populating should be trivial and fast. So any ideas why it's slow?

And is there a better way to do this? We need to get back a result set that is 7 dates in this range.

thanks - dave

答: Rather than using a variable such as @temp use a temp table (#) instead. The query analyser doesn't do optimizing well when using @temp.</p>

Title: Why is this select so slow (SqlServer)?

Body:
We have 3 nested selects that are each creating temporary table. The outer two go very fast. But the inner one (below takes about 1/4 second sometimes to execute. It's creating a table with 7 rows, each holding a date:

declare @StartDate datetime
declare @EndDate datetime
select @StartDate = cast(@Weeks_Loop_TheDate as date),  @EndDate = cast((@Weeks_Loop_TheDate + 6) as date)

declare @temp3  table
(
TheDate datetime
)
while (@StartDate<=@EndDate)
begin
insert into @temp3
values (@StartDate )
select @StartDate=DATEADD(dd,1,@StartDate)
end
select * from @temp3

The params are set with a DateTime variable so the cast shouldn't be significant. And the populating should be trivial and fast. So any ideas why it's slow?

And is there a better way to do this? We need to get back a result set that is 7 dates in this range.

thanks - dave


来源: stackexchange

问:
converting date format to yyyy-mm-dd sql server c#
I am creating a web app in which i want to convert the date format into yyyy-mm-dd

currently i am getting date in the following format Saturday, July 1, 2017

here is my full select query

```<code>SELECT
    ROW_NUMBER() OVER (ORDER BY D.D_ID ) AS SL,
    D.D_DATE, D.USER_TP, D_ITEM_TYPE,D_AUTH_REF,D.D_ID, D.SUR_REFNO, D.REF_NO_DT,
    M.PART_NO,
    S.D_NAME,
    PART_DESC, DENOM, QTY_DEM, STORE_TYPE, ITEM_TYPE, EQUIPMENT,D_NO
FROM SURVEY_HDR D, DEMAND_STATUS S, STORE_MASTER M
WHERE
    M.STORE_ID=D.PART_NO_ID
    AND S.D_ID=D.D_STATUS
    AND D_DATE >= CONVERT(VarChar, 'Saturday, July 1, 2017',1)
    AND D_DATE <= CONVERT(VarChar, 'Monday, July 31, 2017',1)
ORDER BY D.D_ID
</code>```

but i am getting the following error

Msg 241, Level 16, State 1, Line 3 Conversion failed when converting
  date and/or time from character string.

NOTE

D_DATE is in Date format and date is being stored as '2011-01-01'

how can i convert the date?

答:
You are converting String to date but first you have to parse it in date than format it as you want :

Example:

1) Parse string to date :

```<code>DateTime _date;
string strDate = "";
_date = DateTime.Parse("dddd, MMMM dd, yyyy"); // Saturday, July 1, 2017
</code>```

2) Now convert this date to format you want :

```<code>strDate = _date.ToString("yyyy-mm-dd"); // YOUR CASE

strDate = _date.ToString("MM/dd/yyyy");   // 07/21/2017
strDate = _date.ToString("dddd, dd MMMM yyyy");   //Saturday, 21 July 2017
strDate = _date.ToString("dddd, dd MMMM yyyy HH:mm"); // Saturday, 21 July 2017 14:58
strDate = _date.ToString("HH:mm"); // 15:14
strDate = _date.ToString("hh:mm tt"); // 03:14 PM
strDate = _date.ToString("H:mm"); // 5:15
strDate = _date.ToString("h:mm tt"); // 3:16 PM
strDate = _date.ToString("HH:mm:ss"); // 15:16:29
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am creating a web app in which i want to convert the date format into yyyy-mm-dd

currently i am getting date in the following format Saturday, July 1, 2017

here is my full select query

SELECT
    ROW_NUMBER() OVER (ORDER BY D.D_ID ) AS SL,
    D.D_DATE, D.USER_TP, D_ITEM_TYPE,D_AUTH_REF,D.D_ID, D.SUR_REFNO, D.REF_NO_DT,
    M.PART_NO,
    S.D_NAME,
    PART_DESC, DENOM, QTY_DEM, STORE_TYPE, ITEM_TYPE, EQUIPMENT,D_NO
FROM SURVEY_HDR D, DEMAND_STATUS S, STORE_MASTER M
WHERE
    M.STORE_ID=D.PART_NO_ID
    AND S.D_ID=D.D_STATUS
    AND D_DATE >= CONVERT(VarChar, 'Saturday, July 1, 2017',1)
    AND D_DATE <= CONVERT(VarChar, 'Monday, July 31, 2017',1)
ORDER BY D.D_ID

but i am getting the following error

Msg 241, Level 16, State 1, Line 3 Conversion failed when converting
  date and/or time from character string.

NOTE

D_DATE is in Date format and date is being stored as '2011-01-01'

how can i convert the date?

Body:
You are converting String to date but first you have to parse it in date than format it as you want :

Example:

1) Parse string to date :

DateTime _date;
string strDate = "";
_date = DateTime.Parse("dddd, MMMM dd, yyyy"); // Saturday, July 1, 2017

2) Now convert this date to format you want :

strDate = _date.ToString("yyyy-mm-dd"); // YOUR CASE

strDate = _date.ToString("MM/dd/yyyy");   // 07/21/2017
strDate = _date.ToString("dddd, dd MMMM yyyy");   //Saturday, 21 July 2017
strDate = _date.ToString("dddd, dd MMMM yyyy HH:mm"); // Saturday, 21 July 2017 14:58
strDate = _date.ToString("HH:mm"); // 15:14
strDate = _date.ToString("hh:mm tt"); // 03:14 PM
strDate = _date.ToString("H:mm"); // 5:15
strDate = _date.ToString("h:mm tt"); // 3:16 PM
strDate = _date.ToString("HH:mm:ss"); // 15:16:29


问:
jq split array into two arrays
I am new to jq and still trying to learn the basics of JSON, so please, excuse my lack of knowledge.
I find the tool amazingly fast, but I am struggling to get the results I need. I am sure it's possible as I've made it once by accident :(
I have input data, such as

```<code>[
  {"time":1499150456,"data":{"power":{"bus":3.88,"shunt":6.98,"load":3.89,"current":76.00},"light":{"light":21}}},
  {"time":1499150516,"data":{"power":{"bus":3.93,"shunt":1.67,"load":3.93,"current":16.20},"light":{"light":21}}},
  {"time":1499150576,"data":{"power":{"bus":3.92,"shunt":5.58,"load":3.93,"current":25.30},"light":{"light":21}}},
  {}
]
</code>```

I want to extract it into something like

```<code>  [
   1499150456,
   1499150516,
   1499150576
  ]
  [
   76.00,
   16.20,
   25.30
  ]
</code>```

What I used so far was:

```<code>cat inputFile.json | jq -C '.[] | select (length > 0)'
</code>```

which outputs nice initial array without the last empty record.
Next, I am able to do

```<code>cat inputFile.json | jq -C '.[] | select (length > 0) | .time, .data.power.current'
</code>```

The result is very close, but not exactly what I need.
I wanted to use map(.time) that I found in some example, but that resulted in an error - not sure how to use it and the examples did not work for me so far.

答:
The following filter produces the output exactly as described:

```<code>map(select(.time))
| map(.time), map(.data.power.current)
</code>```

This is parsed as map(...) | ( map(...), map(...) ), thus resulting in a stream consisting of two JSON arrays.

Title: jq split array into two arrays

Body:
I am new to jq and still trying to learn the basics of JSON, so please, excuse my lack of knowledge.
I find the tool amazingly fast, but I am struggling to get the results I need. I am sure it's possible as I've made it once by accident :(
I have input data, such as

[
  {"time":1499150456,"data":{"power":{"bus":3.88,"shunt":6.98,"load":3.89,"current":76.00},"light":{"light":21}}},
  {"time":1499150516,"data":{"power":{"bus":3.93,"shunt":1.67,"load":3.93,"current":16.20},"light":{"light":21}}},
  {"time":1499150576,"data":{"power":{"bus":3.92,"shunt":5.58,"load":3.93,"current":25.30},"light":{"light":21}}},
  {}
]

I want to extract it into something like

  [
   1499150456,
   1499150516,
   1499150576
  ]
  [
   76.00,
   16.20,
   25.30
  ]

What I used so far was:

cat inputFile.json | jq -C '.[] | select (length > 0)'

which outputs nice initial array without the last empty record.
Next, I am able to do

cat inputFile.json | jq -C '.[] | select (length > 0) | .time, .data.power.current'

The result is very close, but not exactly what I need.
I wanted to use map(.time) that I found in some example, but that resulted in an error - not sure how to use it and the examples did not work for me so far.

Body:
The following filter produces the output exactly as described:

map(select(.time))
| map(.time), map(.data.power.current)

This is parsed as map(...) | ( map(...), map(...) ), thus resulting in a stream consisting of two JSON arrays.


问:
How to do JavaScript alert in static method server side code in Asp.net?
I want to do JavaScript alert in static method server side code in asp.net with C#. I tried many ways, but it's not working.

For example, I tried

```<code>[WebMethod]
public static void EntrySave(string schoolName)
{
      Response.Write("<script>alert('Hello');</script>");
}
</code>```

and

```<code>[WebMethod]
public static void EntrySave(string schoolName)
{
      ScriptManager.RegisterStartupScript(this, GetType(), "showalert",
       "alert('Only alert Message');", true);
}
</code>```

and many more. But it's not showing alert in webstatic method.

答:
you can use

```<code>    [WebMethod]
    public static void EntrySave(string schoolName)
    {Response.Write("alert('Hello')");
}
</code>```

More can be found here

Body:
I want to do JavaScript alert in static method server side code in asp.net with C#. I tried many ways, but it's not working.

For example, I tried

[WebMethod]
public static void EntrySave(string schoolName)
{
      Response.Write("");
}

and

[WebMethod]
public static void EntrySave(string schoolName)
{
      ScriptManager.RegisterStartupScript(this, GetType(), "showalert",
       "alert('Only alert Message');", true);
}

and many more. But it's not showing alert in webstatic method.

Body:
you can use

    [WebMethod]
    public static void EntrySave(string schoolName)
    {Response.Write("alert('Hello')");
}

More can be found here


问:
Replacing DIV content based on variable sent from another HTML file
I'm trying to get this JavaScript working:

I have an HTML email which links to this page which contains a variable in the link (index.html?content=email1). The JavaScript should replace the DIV content depending on what the variable for 'content' is.

```<code><!-- ORIGINAL DIV -->
<div id="Email">

</div>

<!-- DIV replacement function -->

<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>

<!-- Email 1 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 1 content</div>';

ReplaceContentInContainer('Email1',content);
}
</script>

<!-- Email 2 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 2 content</div>';

ReplaceContentInContainer('Email2',content);
}
</script>
</code>```

Any ideas what I've done wrong that is causing it not to work?

答: The ReplaceContentInContainer calls specify ID's which are not present, the only ID is Email and also, how are the two scripts called, if they are in the same apge like in the example the second (with a corrected ID) would always overwrite the first and also you declare the content variable twice which is not permitted, multiple script blocks in a page share the same global namespace so any global variables has to be named uniquely.</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to get this JavaScript working:

I have an HTML email which links to this page which contains a variable in the link (index.html?content=email1). The JavaScript should replace the DIV content depending on what the variable for 'content' is.

Any ideas what I've done wrong that is causing it not to work?


问:
Search in datagrid using value in textbox
How can I display value in msgbox. In the first column in datagrid is looking value based on textbox and I want display value from second column and the same row in msgbox. Now I have only "Item found"

Here are columns

```<code>Private Sub PictureBox12_Click(sender As Object, e As EventArgs) Handles PictureBox12.Click

        Dim temp As Integer = 0
        For i As Integer = 0 To List2DataGridView.RowCount - 1
            For j As Integer = 0 To List2DataGridView.ColumnCount - 1
                If List2DataGridView.Rows(i).Cells(j).Value.ToString = TextBox2.Text Then
                    MsgBox("Intem found")
                    temp = 1
                End If
            Next
        Next
        If temp = 0 Then
            MsgBox("Item not found")
        End If
    End Sub
</code>```

答:
```<code> Private Sub PictureBox12_Click(sender As Object, e As EventArgs) Handles PictureBox12.Click

        Dim barcode As String
        Dim rowindex As String
        Dim found As Boolean = False
        barcode = InputBox("Naskenujte čárový kód ||||||||||||||||||||||||||||||||||||")
        If Len(Trim(barcode)) = 0 Then Exit Sub   'Pressed cancel

        For Each row As DataGridViewRow In List2DataGridView.Rows
            If row.Cells.Item("DataGridViewTextBoxColumn1").Value = barcode Then
                rowindex = row.Index.ToString()
                found = True
                Dim actie As String = row.Cells("DataGridViewTextBoxColumn2").Value.ToString()
                MsgBox("Čárový kód:  " & barcode & vbNewLine & "Číslo dílu je:  " & actie, , "Vyhledání dílu")

                Exit For
            End If
        Next
        If Not found Then
            MsgBox("Item not found")
        End If
    End Sub
</code>```

Body:
How can I display value in msgbox. In the first column in datagrid is looking value based on textbox and I want display value from second column and the same row in msgbox. Now I have only "Item found"

Here are columns

Private Sub PictureBox12_Click(sender As Object, e As EventArgs) Handles PictureBox12.Click

        Dim temp As Integer = 0
        For i As Integer = 0 To List2DataGridView.RowCount - 1
            For j As Integer = 0 To List2DataGridView.ColumnCount - 1
                If List2DataGridView.Rows(i).Cells(j).Value.ToString = TextBox2.Text Then
                    MsgBox("Intem found")
                    temp = 1
                End If
            Next
        Next
        If temp = 0 Then
            MsgBox("Item not found")
        End If
    End Sub


问:
Prevent page reload when blank link is clicked?
I have a web page to download files using a button.But for some cases the files does not exit and download links are blank...So whenever the user clicks the link page just reloads.It would have been great if i could somehow disable the page reload and display an alert that says file not yet available..

This is the download link button code.row["slink"] gives the download link and may become empty sometime.

```<code>'<a href="'+row["slink"]+'"><button type="button" class="btn btn-info " data-row-id="' + row.id + '">Download</buttn></a> ';
</code>```

答:
Simple Solution

You can set target to blank:

```<code><a ... ... target="_blank" > ... </a>
</code>```

This will open it in a new tab instead of refreshing.

More Sophisticated Approach:

You can also use a conditional to build your anchor tag.

```<code>if (row["slink"] == "")
{
    var atag = '<a href="javascript:void(0)" onclick="alert("No File Available")"><button type="button" class="btn btn-info " data-row-id="' + row.id + '">Download</button></a> ';
}
</code>```

This will give an alert if there is no file.

Body:
I have a web page to download files using a button.But for some cases the files does not exit and download links are blank...So whenever the user clicks the link page just reloads.It would have been great if i could somehow disable the page reload and display an alert that says file not yet available..

This is the download link button code.row["slink"] gives the download link and may become empty sometime.

'<button type="button" class="btn btn-info " data-row-id="' + row.id + '">Download</buttn> ';

Body:
Simple Solution

You can set target to blank:

<a ... ... target="_blank" > ... </a>

This will open it in a new tab instead of refreshing.

More Sophisticated Approach:

You can also use a conditional to build your anchor tag.

if (row["slink"] == "")
{
    var atag = '<a href="javascript:void(0)" onclick="alert(&quot;No File Available&quot;)"><button type="button" class="btn btn-info " data-row-id="' + row.id + '">Download</button></a> ';
}

This will give an alert if there is no file.


问:
Beginner Java - Changing String from First Middle Last to Last, First Middle
Trying to work out a homework problem that demands:
Changes a name so that the last name comes first.
Example: "Mary Jane Lee" will return "Lee, Mary Jane".
If name has no spaces, it is returned without change.

After doing some research it seems I can do this with the Split method, but we've not learned that yet.

The thing is I've worked out the code and it seems to work when spaces
 and a full name is entered, but when there's no middle name or no spaces to separate the character, I get the error:

when the name entered is simply: Harry Smith

```<code>java.lang.StringIndexOutOfBoundsException: String index out of range: -7
</code>```

and

```<code>java.lang.StringIndexOutOfBoundsException: String index out of range: -1
</code>```

when the name is Sarah

This is my code, but I'm not sure how to fix it:

```<code>public class Names {
    public static String lastNameFirst(String name) {
        int firstIndex = name.indexOf(" ");
        int secondIndex = name.indexOf(" ", firstIndex + 1);
        String firstName = name.substring(0, name.indexOf(" "));
        String middleName = name.substring(firstIndex + 1, secondIndex);
        String lastName = name.substring(secondIndex + 1);
        String result = "";
        result = lastName + ", " + firstName + " " + middleName;
        return result;
    }
}
</code>```

Thanks in advance!!

答:
A more robust way is to use lastIndexOf to find the last space:

```<code>int lastSpace = name.lastIndexOf(' ');
if (lastSpace != -1) {
  String lastName = name.substring(lastSpace + 1);
  String partBeforeLastName = name.substring(0, lastSpace);
  return lastName + ", " + partBeforeLastName;
} else {
  return name;
}
</code>```

You don't actually really care about the other space (if it's there at all), since the first and middle names stay in the same relative order.

(Generally, there are lots of falsehoods that programmers believe about names; but let's put those aside for the purpose of the exercise.)

Body:
Trying to work out a homework problem that demands:
Changes a name so that the last name comes first.
Example: "Mary Jane Lee" will return "Lee, Mary Jane".
If name has no spaces, it is returned without change.

After doing some research it seems I can do this with the Split method, but we've not learned that yet.

The thing is I've worked out the code and it seems to work when spaces
 and a full name is entered, but when there's no middle name or no spaces to separate the character, I get the error:

when the name entered is simply: Harry Smith

java.lang.StringIndexOutOfBoundsException: String index out of range: -7

and

java.lang.StringIndexOutOfBoundsException: String index out of range: -1

when the name is Sarah

This is my code, but I'm not sure how to fix it:

public class Names {
    public static String lastNameFirst(String name) {
        int firstIndex = name.indexOf(" ");
        int secondIndex = name.indexOf(" ", firstIndex + 1);
        String firstName = name.substring(0, name.indexOf(" "));
        String middleName = name.substring(firstIndex + 1, secondIndex);
        String lastName = name.substring(secondIndex + 1);
        String result = "";
        result = lastName + ", " + firstName + " " + middleName;
        return result;
    }
}

Thanks in advance!!

Body:
A more robust way is to use lastIndexOf to find the last space:

int lastSpace = name.lastIndexOf(' ');
if (lastSpace != -1) {
  String lastName = name.substring(lastSpace + 1);
  String partBeforeLastName = name.substring(0, lastSpace);
  return lastName + ", " + partBeforeLastName;
} else {
  return name;
}

You don't actually really care about the other space (if it's there at all), since the first and middle names stay in the same relative order.

(Generally, there are lots of falsehoods that programmers believe about names; but let's put those aside for the purpose of the exercise.)


问:
Python - apply_async doesn't execute function
Hi I'm trying to use multiprocessing to speed up my code. However, the apply_async doesn't work for me. I tried to do a simple example like:

```<code>from multiprocessing.pool import Pool
t = [0, 1, 2, 3, 4, 5]
def cube(x):
    t[x] = x**3
pool = Pool(processes=4)
for i in range(6):
    pool.apply_async(cube, args=(i, ))
for x in t:
    print(x)
</code>```

It does not really change t as I would expect.

My real code is like:

```<code>from multiprocessing.pool import Pool
def func(a, b, c, d):
    #some calculations
    #save result to files
    #no return value
lt = #list of possible value of a
#set values to b, c, d
p = Pool()
for i in lt:
    p.apply_async(func, args=(i, b, c, d, ))
</code>```

Where are the problems here?

Thank you!

Update: Thanks to the comments and answers, now I understand why my simple example won't work. However, I'm still in trouble with my real code. I have checked that my func does not rely on any global variable, so it seems not to be the same problem as my example code.

As suggested, I added a return value to my func, now my code is:

```<code>f = Flux("reactor")
d = Detector("Ge")
mv = arange(-6, 1.5, 0.5)
p = Pool()
lt = ["uee", "dee"]
for i in lt:
    re = p.apply_async(res, args=(i, d, f, mv, ))
    print(re.get())
p.close()
p.join()
</code>```

Now I get the following error:

```<code>Traceback (most recent call last):
  File "/Users/Shu/Documents/Programming/Python/Research/debug.py", line 35, in <module>
print(re.get())
  File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/pool.py", line 608, in get
raise self._value
  File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/pool.py", line 385, in _handle_tasks
put(task)
  File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/connection.py", line 206, in send
self._send_bytes(_ForkingPickler.dumps(obj))
  File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
AttributeError: Can't pickle local object 'Flux.__init__.<locals>.<lambda>'
</code>```

答:
EDIT: the first example you provided will not work for a simple reason: processes do not share memory. Therefore, the change t[x] = x**3 will not be applied to the parent process leaving the values of the list t unchanged.

You need to actually return the value from the computation and build a new list from that.

```<code>def cube(x):
    return x**3

t = [0, 1, 2, 3, 4, 5]

p = Pool()
t = p.map(cube, t)

print(t)
</code>```

If, as you claim in the second example, the results are supposed not to be returned but to be independently stored within files and this does not happen, I'd recommend to check the return value of your function to see whether the function itself is raising an exception or not.

I'd recommend you to get the actual results and see what happens:

```<code>p = Pool()
for i in lt:
    res = p.apply_async(func, args=(i, b, c, d, ))
    print(res.get())  # this will raise an exception if it happens within func

p.close()  # do not accept any more tasks
p.join()  # wait for the completion of all scheduled jobs
</code>```

Body:
Hi I'm trying to use multiprocessing to speed up my code. However, the apply_async doesn't work for me. I tried to do a simple example like:

from multiprocessing.pool import Pool
t = [0, 1, 2, 3, 4, 5]
def cube(x):
    t[x] = x**3
pool = Pool(processes=4)
for i in range(6):
    pool.apply_async(cube, args=(i, ))
for x in t:
    print(x)

It does not really change t as I would expect.

My real code is like:

from multiprocessing.pool import Pool
def func(a, b, c, d):
    #some calculations
    #save result to files
    #no return value
lt = #list of possible value of a
#set values to b, c, d
p = Pool()
for i in lt:
    p.apply_async(func, args=(i, b, c, d, ))

Where are the problems here?

Thank you!

Update: Thanks to the comments and answers, now I understand why my simple example won't work. However, I'm still in trouble with my real code. I have checked that my func does not rely on any global variable, so it seems not to be the same problem as my example code.

As suggested, I added a return value to my func, now my code is:

f = Flux("reactor")
d = Detector("Ge")
mv = arange(-6, 1.5, 0.5)
p = Pool()
lt = ["uee", "dee"]
for i in lt:
    re = p.apply_async(res, args=(i, d, f, mv, ))
    print(re.get())
p.close()
p.join()

Now I get the following error:

Traceback (most recent call last):
  File "/Users/Shu/Documents/Programming/Python/Research/debug.py", line 35, in <module>
print(re.get())
  File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/pool.py", line 608, in get
raise self._value
  File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/pool.py", line 385, in _handle_tasks
put(task)
  File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/connection.py", line 206, in send
self._send_bytes(_ForkingPickler.dumps(obj))
  File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
AttributeError: Can't pickle local object 'Flux.__init__.<locals>.<lambda>'

Body:
EDIT: the first example you provided will not work for a simple reason: processes do not share memory. Therefore, the change t[x] = x**3 will not be applied to the parent process leaving the values of the list t unchanged.

You need to actually return the value from the computation and build a new list from that.

def cube(x):
    return x**3

t = [0, 1, 2, 3, 4, 5]

p = Pool()
t = p.map(cube, t)

print(t)

If, as you claim in the second example, the results are supposed not to be returned but to be independently stored within files and this does not happen, I'd recommend to check the return value of your function to see whether the function itself is raising an exception or not.

I'd recommend you to get the actual results and see what happens:

p = Pool()
for i in lt:
    res = p.apply_async(func, args=(i, b, c, d, ))
    print(res.get())  # this will raise an exception if it happens within func

p.close()  # do not accept any more tasks
p.join()  # wait for the completion of all scheduled jobs


问:
How to get RecordID from CNContactStore ios
This is my code to get the device's Contacts and save to MutableArray.

But I need to get the recordID for all contacts individually and save into the same Array for further use. (For example, to delete Contacts using recordId).

Please help me, I'm stuck for 4 days on that.

```<code>[contactStore enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact* __nonnull contact, BOOL* __nonnull stop){
           if( contact.phoneNumbers)
                phoneNumber = [[[contact.phoneNumbers firstObject] value]];
           if( contact.emailAddresses)
                emailAddress = [[contact.emailAddresses firstObject] value];
           contactValue=[[NSMutableDictionary alloc] init];
                [contactValue setValue:phoneNumber ?:@"" forKey:@"phoneNumber"];
                [contactValue setValue:emailAddress ?:@"" forKey:@"emailAddress"];
                [contactValue setObject:contact.identifier forKey:@"phoneIdentifier"];
                [contactValue setObject:contact.givenName ?:@"" forKey:@"firstName"];
                [contactValue setObject:contact.familyName ?:@"" forKey:@"lastName"];

           [_totalContact addObject:contactValue];
      }]
</code>```

答:
Use this simple extension, if you really need to read recordID (for old API).

recordID always fetched.

This code never submit into App Store. It use a private API!

CNContact+PrivateExtension.h :

```<code>NS_ASSUME_NONNULL_BEGIN

@interface CNContact (PrivateExtension)

@property (readonly) NSNumber *privateRecordID;

@end

NS_ASSUME_NONNULL_END
</code>```

CNContact+PrivateExtension.m :

```<code>@implementation CNContact (PrivateExtension)

- (NSNumber *)privateRecordID
{
    return [self valueForKey:@"recordID"];
}

@end
</code>```

Body:
This is my code to get the device's Contacts and save to MutableArray.

But I need to get the recordID for all contacts individually and save into the same Array for further use. (For example, to delete Contacts using recordId).

Please help me, I'm stuck for 4 days on that.

[contactStore enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact* __nonnull contact, BOOL* __nonnull stop){
           if( contact.phoneNumbers)
                phoneNumber = [[[contact.phoneNumbers firstObject] value]];
           if( contact.emailAddresses)
                emailAddress = [[contact.emailAddresses firstObject] value];
           contactValue=[[NSMutableDictionary alloc] init];
                [contactValue setValue:phoneNumber ?:@"" forKey:@"phoneNumber"];
                [contactValue setValue:emailAddress ?:@"" forKey:@"emailAddress"];
                [contactValue setObject:contact.identifier forKey:@"phoneIdentifier"];
                [contactValue setObject:contact.givenName ?:@"" forKey:@"firstName"];
                [contactValue setObject:contact.familyName ?:@"" forKey:@"lastName"];

           [_totalContact addObject:contactValue];
      }]

Body:
Use this simple extension, if you really need to read recordID (for old API).

recordID always fetched.

This code never submit into App Store. It use a private API!

CNContact+PrivateExtension.h :

NS_ASSUME_NONNULL_BEGIN

@interface CNContact (PrivateExtension)

@property (readonly) NSNumber *privateRecordID;

@end

NS_ASSUME_NONNULL_END

CNContact+PrivateExtension.m :

@implementation CNContact (PrivateExtension)

- (NSNumber *)privateRecordID
{
    return [self valueForKey:@"recordID"];
}

@end


问:
FullText In Microsoft Sql Server - Returning exactly word
Can anyone tell me how to query a fulltext table in Sql Server, and get only exactly matches? Example:

I have those records in a table named "Items":

Bath

  Bathroom

  Test

  Testing

I need to query for Bath and get only 1 record, "bath", excluding the word Bathroom. The same to the word "Test", wich in my context is different to "Testing".

答:
Have you tried

```<code>SELECT column1, column2, ...
FROM [itens] AS FT_TBL INNER JOIN
   CONTAINSTABLE([itens], *, 'Bath') AS KEY_TBL
   ON FT_TBL.unique_key_column = KEY_TBL.[KEY]
</code>```

http://msdn.microsoft.com/en-us/library/ms189760.aspx

or

```<code>SELECT columnname
FROM [itens]
WHERE CONTAINS(somecolumn, 'Bath')
</code>```

http://msdn.microsoft.com/en-us/library/ms187787.aspx

Just noticed the updated questions (formatting applied).
If you column holds keywords (single word) then you could just select column = 'keyword'.

```<code>SELECT columnname
FROM [itens]
WHERE somecolumn = 'Bath'
</code>```

Body:
Have you tried

SELECT column1, column2, ...
FROM [itens] AS FT_TBL INNER JOIN
   CONTAINSTABLE([itens], *, 'Bath') AS KEY_TBL
   ON FT_TBL.unique_key_column = KEY_TBL.[KEY]

http://msdn.microsoft.com/en-us/library/ms189760.aspx

or

SELECT columnname
FROM [itens]
WHERE CONTAINS(somecolumn, 'Bath')

http://msdn.microsoft.com/en-us/library/ms187787.aspx

Just noticed the updated questions (formatting applied).
If you column holds keywords (single word) then you could just select column = 'keyword'.

SELECT columnname
FROM [itens]
WHERE somecolumn = 'Bath'


问:
How do I pass value from Jquery to PHP ? HTML is a hidden input form field
I have a form:

```<code><form action="post.php" method="POST">
 <p class="select1">Northern Cape</p>
 <p class="select1">Eastern Cape</p>

 <p class="select2" >New Goods</p>
 <p class="select2" >Used Goods</p>

<input id="submt" type="submit" name="submit" value="Submit">
</form>
</code>```

JQUERY .... appends input/value to the selected items:

```<code>$(document).ready(function() {
    $('.select1').click(function() {
      if ($(this).text() == "Northern Cape"){
          $(this).append("<input id='firstloc' type='hidden' name='province'
          value='Northern Cape' />");
          $("#firstloc").val('Northern Cape');
     }; // end of if statement

      if ($(this).text() == "Eastern Cape"){
          $(this).append("<input id='firstloc' type='hidden' name='province'
          value='Eastern Cape' />");
          $("#firstloc").val('Eastern Cape');
     }; // end of if statement
}); // end of click function
}); // end of document ready

 $(document).ready(function() {
    $('.select2').click(function() {
        if ($(this).text() == "New Goods"){
            $(this).append("<input id='category' type='hidden' name='cat'
            value='New Goods' />");
            $(this).val('New Goods');
         };

        if ($(this).text() == "Used Goods"){
            $(this).append("<input id='category' type='hidden' name='cat'
            value='Used Goods' />");
            $("#category").val('Used Goods');
         };

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

How do I pass the values to PHP ie. first value Province second value Category?

```<code><?php

$province = $_POST['province'];
$category = $_POST['cat'];
echo $province;
echo $category;
?>
</code>```

I get a message Undefined index:cat when passing to PHP.
User must select 2 items and values must be passed to PHP,I do not want to use a drop down menu with "options"

答:
PHP does not set $_POST for all post operations, for example for text/xml:

Try adding adding application/x-www-form-urlencoded or multipart/form-data to your form just to make sure.

```<code><form action="post.php" method="POST" enctype="multipart/form-data">
</code>```

Also make sure you don't have broken HTML that is causing your form tag to be close prematurely. Verify what is getting posted and the content type using web developer tools.

You should also be using isset to check the existence of a variable:

```<code>if (isset($_POST["cat"])) {
    $cat = $_POST["cat"];
    echo $cat;
    echo " is the category";
}
else
{
    $cat = null;
    echo "no category supplied";
}
</code>```

Body:
I have a form:

<form action="post.php" method="POST">

Northern Cape

Eastern Cape

New Goods

Used Goods

<input id="submt" type="submit" name="submit" value="Submit">
</form>

JQUERY .... appends input/value to the selected items:

$(document).ready(function() {
    $('.select1').click(function() {
      if ($(this).text() == "Northern Cape"){
          $(this).append("<input id='firstloc' type='hidden' name='province'
          value='Northern Cape' />");
          $("#firstloc").val('Northern Cape');
     }; // end of if statement

      if ($(this).text() == "Eastern Cape"){
          $(this).append("<input id='firstloc' type='hidden' name='province'
          value='Eastern Cape' />");
          $("#firstloc").val('Eastern Cape');
     }; // end of if statement
}); // end of click function
}); // end of document ready

 $(document).ready(function() {
    $('.select2').click(function() {
        if ($(this).text() == "New Goods"){
            $(this).append("<input id='category' type='hidden' name='cat'
            value='New Goods' />");
            $(this).val('New Goods');
         };

        if ($(this).text() == "Used Goods"){
            $(this).append("<input id='category' type='hidden' name='cat'
            value='Used Goods' />");
            $("#category").val('Used Goods');
         };

});
});

How do I pass the values to PHP ie. first value Province second value Category?

<?php

$province = $_POST['province'];
$category = $_POST['cat'];
echo $province;
echo $category;
?>

I get a message Undefined index:cat when passing to PHP.
User must select 2 items and values must be passed to PHP,I do not want to use a drop down menu with "options"

Body:
PHP does not set $_POST for all post operations, for example for text/xml:

Try adding adding application/x-www-form-urlencoded or multipart/form-data to your form just to make sure.

<form action="post.php" method="POST" enctype="multipart/form-data">

Also make sure you don't have broken HTML that is causing your form tag to be close prematurely. Verify what is getting posted and the content type using web developer tools.

You should also be using isset to check the existence of a variable:

if (isset($_POST["cat"])) {
    $cat = $_POST["cat"];
    echo $cat;
    echo " is the category";
}
else
{
    $cat = null;
    echo "no category supplied";
}


问:
Setting readonly using ng-readonly dynamically is not working
I am fetching some data from the database server and displaying the same in tabular format on my GUI. I want to achieve the following in my GUI design

(a) Any cell in the table should be editable except the first column in the table.
(b) The first row of the table, if added newly to the GUI for accepting new inputs from the user, should be exempted from the above rule i.e., all columns of the first row should be editable.

To achieve this I wrote the following code.

HTML Code

```<code>    <tbody>
           <tr ng-repeat="x in sensordata">
           <td>
             <input class="form-control" type="text" ng-model="x.name" placeholder="Sensor name" ng-readonly="namereadonly" ng-init="ctrl2.setReadOnly(x.name,$index)"/>
           </td>
           <td>
              <input class="form-control" type="text" ng-model="x.unit" placeholder="Measurement Unit" required/>
           </td>
           <td>
                <input class="form-control" type="text" ng-model="x.type" placeholder="Sensor Type" required/>
           </td>
           <td>
                <input class="form-control" type="text" ng-model="x.periodicity" placeholder="Periodicity" required/>
           </td>
           <td>
                <input class="form-control" type="text" ng-model="x.formula" placeholder="Formula" required/>
           </td>
           <td>
               <input class="form-control" type="email" ng-model="x.vendor" placeholder="Email Id" required/>
           </td>
           </tr>
   </tbody>
</code>```

Controller code is as follows.

```<code>this.setReadOnly = function(name,idx) {
        console.log('name ' + name + ' idx ' + idx);
        if (name === undefined || name === null || name === '') $scope.namereadonly = false;
        if (name !== '' || name !== undefined || name !== null) $scope.namereadonly = true;
    };
</code>```

When I am executing above code the first column of all the rows are getting uneditable as expected. But when I am adding new row to the (by adding new empty JSON object in the sensordata array in another function of the same controller) GUI, the first column of the row is getting uneditable which should not be the case as per the first if statement in the above method. I am unable to figure out why it is happening.

答:
a) Any cell in the table should be editable except the first column in
  the table. (b) The first row of the table, if added newly to the GUI
  for accepting new inputs from the user, should be exempted from
  the above rule i.e., all columns of the first row should be editable.

There are plenty solutions but it depends on you/your needs. Here I would like to share you 2 logics :

adding new key for the new object entered by user and use this new key to distinct them with old object ng-readonly="x.new"  and new object should have this key: {name:"", new: true}

Store the length of main array, and use this to distinct the new object entered  ng-readonly="$index < mainlength" and mainlength is something like:  $scope.mainlength = angular.copy($scope.sensordata.length) (use of angular.copy ) see http://plnkr.co/edit/zCcyPTG3EybL4IjsOpz4?p=preview

Body:
I am fetching some data from the database server and displaying the same in tabular format on my GUI. I want to achieve the following in my GUI design

(a) Any cell in the table should be editable except the first column in the table.
(b) The first row of the table, if added newly to the GUI for accepting new inputs from the user, should be exempted from the above rule i.e., all columns of the first row should be editable.

To achieve this I wrote the following code.

HTML Code

             <input class="form-control" type="text" ng-model="x.name" placeholder="Sensor name" ng-readonly="namereadonly" ng-init="ctrl2.setReadOnly(x.name,$index)"/>

              <input class="form-control" type="text" ng-model="x.unit" placeholder="Measurement Unit" required/>

                <input class="form-control" type="text" ng-model="x.type" placeholder="Sensor Type" required/>

                <input class="form-control" type="text" ng-model="x.periodicity" placeholder="Periodicity" required/>

                <input class="form-control" type="text" ng-model="x.formula" placeholder="Formula" required/>

               <input class="form-control" type="email" ng-model="x.vendor" placeholder="Email Id" required/>

Controller code is as follows.

this.setReadOnly = function(name,idx) {
        console.log('name ' + name + ' idx ' + idx);
        if (name === undefined || name === null || name === '') $scope.namereadonly = false;
        if (name !== '' || name !== undefined || name !== null) $scope.namereadonly = true;
    };

When I am executing above code the first column of all the rows are getting uneditable as expected. But when I am adding new row to the (by adding new empty JSON object in the sensordata array in another function of the same controller) GUI, the first column of the row is getting uneditable which should not be the case as per the first if statement in the above method. I am unable to figure out why it is happening.


问:
How to show google map with Latitude and Longtitude data from parse JSON?
I already parse data json and got Latitude and Longtitude so then how to use them to show Google map?
Any reference for that? Or sample code?

I just tried to search in google but I'm confused.

答:
try this

pass data using intent to your maps activity like this

```<code>Intent i = new Intent(MainActivity.this, MapsActivity.class);
i.putExtra("longitude",longitude);
i.putExtra("latitude",latitude);
i.putExtra("title", "title");
startActivity(i);
</code>```

now retrive your data in your maps activity like this

```<code>Intent i = getIntent();
latitude = Double.valueOf(i.getStringExtra("latitude"))
longitude = Double.valueOf(i.getStringExtra("longitude"));
title = i.getStringExtra("title");
</code>```

now in your onMapReady method set lat long and title like this

```<code> LatLng location = new LatLng(latitude, longitude);
 mMap.addMarker(new MarkerOptions().position(location).title(title));
 mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
 mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 14.0f));
</code>```

Body:
try this

pass data using intent to your maps activity like this

Intent i = new Intent(MainActivity.this, MapsActivity.class);
i.putExtra("longitude",longitude);
i.putExtra("latitude",latitude);
i.putExtra("title", "title");
startActivity(i);

now retrive your data in your maps activity like this

Intent i = getIntent();
latitude = Double.valueOf(i.getStringExtra("latitude"))
longitude = Double.valueOf(i.getStringExtra("longitude"));
title = i.getStringExtra("title");

now in your onMapReady method set lat long and title like this

 LatLng location = new LatLng(latitude, longitude);
 mMap.addMarker(new MarkerOptions().position(location).title(title));
 mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
 mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 14.0f));


问:
why my crawledURL is null?
I am following a tutorial to create a web crawler in java. When I run the code my crawledURL is null. *** Malformed URL :null in a infinite loop.

Can anyone explain to me why is this happening?

Here is the whole code:

```<code>import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;
import java.net.*;

public class WebCrawler {

public static Queue<String> Queue = new LinkedList<>();
public static Set<String> marked = new HashSet<>();
public static String regex = "http[s]://(\\w+\\.)*(\\w+)";

public static void bfsAlgorithm(String root) throws IOException {

    Queue.add(root);

    while (!Queue.isEmpty()) {

        String crawledURL = Queue.poll();
        System.out.println("\n=== Site crawled : " + crawledURL + "===");

        //Limiting to a 100 websites here

        if(marked.size() > 100)
            return;

        boolean ok = false;
        URL url = null;
        BufferedReader br = null;

        while (!ok) {
            try {
                url = new URL(crawledURL);
                br = new BufferedReader(new InputStreamReader(url.openStream()));
                ok = true;

            } catch (MalformedURLException e) {
                System.out.println("*** Malformed URL :" + crawledURL);
                crawledURL = Queue.poll();
                ok = false;

            } catch (IOException ioe) {
                System.out.println("*** IOException for URL :" + crawledURL);
                crawledURL = Queue.poll();
                ok = false;

        }

    }

        StringBuilder sb = new StringBuilder();

        while((crawledURL = br.readLine()) != null) {
            sb.append(crawledURL);
        }

        crawledURL = sb.toString();
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(crawledURL);

        while (matcher.find()){

            String w = matcher.group();

            if (!marked.contains(w)) {
                marked.add(w);
                System.out.println("Site added for crawling : " + w);
                Queue.add(w);
            }
        }

    }

}

public static void showResults() {
    System.out.println("\n\nResults :");
    System.out.print("Web sites craweled: " + marked.size() + "\n");

    for (String s : marked) {
        System.out.println("* " + s);
    }

}

public static void main(String[] args) {

    try {

        bfsAlgorithm("http://www.ssaurel.com/blog");
        showResults();

    } catch (IOException e) {

        //TODO Auto-generated catch block
        e.printStackTrace();
    }
}
</code>```

}

答:
```<code>while (!Queue.isEmpty()) {
    String crawledURL = Queue.poll();
...
        } catch (MalformedURLException e) {
            crawledURL = Queue.poll();
</code>```

second time you do not check is queue empty

Title: why my crawledURL is null?

Body:
I am following a tutorial to create a web crawler in java. When I run the code my crawledURL is null. *** Malformed URL :null in a infinite loop.

Can anyone explain to me why is this happening?

Here is the whole code:

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;
import java.net.*;

public class WebCrawler {

public static Queue<String> Queue = new LinkedList<>();
public static Set<String> marked = new HashSet<>();
public static String regex = "http[s]://(\\w+\\.)*(\\w+)";

public static void bfsAlgorithm(String root) throws IOException {

    Queue.add(root);

    while (!Queue.isEmpty()) {

        String crawledURL = Queue.poll();
        System.out.println("\n=== Site crawled : " + crawledURL + "===");

        //Limiting to a 100 websites here

        if(marked.size() > 100)
            return;

        boolean ok = false;
        URL url = null;
        BufferedReader br = null;

        while (!ok) {
            try {
                url = new URL(crawledURL);
                br = new BufferedReader(new InputStreamReader(url.openStream()));
                ok = true;

            } catch (MalformedURLException e) {
                System.out.println("*** Malformed URL :" + crawledURL);
                crawledURL = Queue.poll();
                ok = false;

            } catch (IOException ioe) {
                System.out.println("*** IOException for URL :" + crawledURL);
                crawledURL = Queue.poll();
                ok = false;

        }

    }

        StringBuilder sb = new StringBuilder();

        while((crawledURL = br.readLine()) != null) {
            sb.append(crawledURL);
        }

        crawledURL = sb.toString();
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(crawledURL);

        while (matcher.find()){

            String w = matcher.group();

            if (!marked.contains(w)) {
                marked.add(w);
                System.out.println("Site added for crawling : " + w);
                Queue.add(w);
            }
        }

    }

}

public static void showResults() {
    System.out.println("\n\nResults :");
    System.out.print("Web sites craweled: " + marked.size() + "\n");

    for (String s : marked) {
        System.out.println("* " + s);
    }

}

public static void main(String[] args) {

    try {

        bfsAlgorithm("http://www.ssaurel.com/blog");
        showResults();

    } catch (IOException e) {

        //TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

Body:
while (!Queue.isEmpty()) {
    String crawledURL = Queue.poll();
...
        } catch (MalformedURLException e) {
            crawledURL = Queue.poll();

second time you do not check is queue empty


问:
TemplateDoesNotExist at django hosting
in the localhost , my code is running good on http://127.0.0.1:8000/twitter/  ,

but in the django hosting : http://zjm1126.alwaysdata.net/twitter/, it is show error :

```<code>TemplateDoesNotExist at /twitter/

home.html
</code>```

home.html  is in

```<code>mysite:
   twitter
       templates
            home.html
</code>```

and i set this is settings.py

```<code>TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)
</code>```

and

```<code>INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.admin',
    'django.contrib.comments',

    'twitter',
)
</code>```

so what can i do ,

thanks

答:
Try to add this in settings.py

```<code>TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__), 'templates').replace('\\', '/'),
)
</code>```

These lines says django to find templates in folders with names 'templates'.
Although in book author said this default behaviour without this code.

Title: TemplateDoesNotExist at django hosting

Body:
in the localhost , my code is running good on http://127.0.0.1:8000/twitter/  ,

but in the django hosting : http://zjm1126.alwaysdata.net/twitter/, it is show error :

TemplateDoesNotExist at /twitter/

home.html

home.html  is in

mysite:
   twitter
       templates
            home.html

and i set this is settings.py

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

and

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.admin',
    'django.contrib.comments',

    'twitter',
)

so what can i do ,

thanks

Body:
Try to add this in settings.py

TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__), 'templates').replace('\\', '/'),
)

These lines says django to find templates in folders with names 'templates'.
Although in book author said this default behaviour without this code.


问:
How do I create Long Press menu on RelativeLayout?
I have created 50 relative layouts dynamically in "MainActivity.java".

```<code>public class MainActivity extends AppCompatActivity  {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
     RelativeLayout big=new RelativeLayout(this);
     RelativeLayout mini;
     setContentView(big);
     for(int i=0; i<50; i++)
     {
         //just a sample example. Accept that the code is completely correct.

         mini=new RelativeLayout(this);
         big.addView(mini);
     }
  }
}
</code>```

Now, I want, when each "mini" is long pressed a pop up or context menu will appear containing two options (1.Open and 2.Hide). This, Open/Hide actions will be done by me when one is chosen.

I searched internet and found some suggestions to create a *.xml in menu directiory and attach to MainActivity.java using onCreateContextMenu event.

But, i didn't understand that. As I am new in adnroid, please give me the full code to create context menu when long pressed on a view with instructions (like "add menu_all.xml to menu directory", "create new .*java file" etc.)

N.B. The app I want to build at API 19.

Thanks in advance.

答:
You can use

```<code>registerForContextMenu(mini);
</code>```

This func take a view as an Argument and generates the context menu for you.

Override the onCreateContextMenu func of your activity and do whatever you want to do.

Here's a sample code

```<code>public class MainActivity extends Activity {
    ListView listView1;
    String contacts[]={"Ajay","Sachin","Sumit","Tarun","Yogesh"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView1=(ListView)findViewById(R.id.listView1);
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,contacts);
        listView1.setAdapter(adapter);
        // Register the ListView  for Context menu
        registerForContextMenu(listView1);
    }
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
    {
            super.onCreateContextMenu(menu, v, menuInfo);
            menu.setHeaderTitle("Select The Action");
            menu.add(0, v.getId(), 0, "Call");//groupId, itemId, order, title
            menu.add(0, v.getId(), 0, "SMS");
    }
    @Override
    public boolean onContextItemSelected(MenuItem item){
            if(item.getTitle()=="Call"){
                Toast.makeText(getApplicationContext(),"calling code",Toast.LENGTH_LONG).show();
            }
            else if(item.getTitle()=="SMS"){
                Toast.makeText(getApplicationContext(),"sending sms code",Toast.LENGTH_LONG).show();
            }else{
               return false;
            }
          return true;
      }
    }
</code>```

Body:
I have created 50 relative layouts dynamically in "MainActivity.java".

public class MainActivity extends AppCompatActivity  {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
     RelativeLayout big=new RelativeLayout(this);
     RelativeLayout mini;
     setContentView(big);
     for(int i=0; i<50; i++)
     {
         //just a sample example. Accept that the code is completely correct.

         mini=new RelativeLayout(this);
         big.addView(mini);
     }
  }
}

Now, I want, when each "mini" is long pressed a pop up or context menu will appear containing two options (1.Open and 2.Hide). This, Open/Hide actions will be done by me when one is chosen.

I searched internet and found some suggestions to create a *.xml in menu directiory and attach to MainActivity.java using onCreateContextMenu event.

But, i didn't understand that. As I am new in adnroid, please give me the full code to create context menu when long pressed on a view with instructions (like "add menu_all.xml to menu directory", "create new .*java file" etc.)

N.B. The app I want to build at API 19.

Thanks in advance.

Body:
You can use

registerForContextMenu(mini);

This func take a view as an Argument and generates the context menu for you.

Override the onCreateContextMenu func of your activity and do whatever you want to do.

Here's a sample code

public class MainActivity extends Activity {
    ListView listView1;
    String contacts[]={"Ajay","Sachin","Sumit","Tarun","Yogesh"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView1=(ListView)findViewById(R.id.listView1);
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,contacts);
        listView1.setAdapter(adapter);
        // Register the ListView  for Context menu
        registerForContextMenu(listView1);
    }
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
    {
            super.onCreateContextMenu(menu, v, menuInfo);
            menu.setHeaderTitle("Select The Action");
            menu.add(0, v.getId(), 0, "Call");//groupId, itemId, order, title
            menu.add(0, v.getId(), 0, "SMS");
    }
    @Override
    public boolean onContextItemSelected(MenuItem item){
            if(item.getTitle()=="Call"){
                Toast.makeText(getApplicationContext(),"calling code",Toast.LENGTH_LONG).show();
            }
            else if(item.getTitle()=="SMS"){
                Toast.makeText(getApplicationContext(),"sending sms code",Toast.LENGTH_LONG).show();
            }else{
               return false;
            }
          return true;
      }
    }


问:
Angular 4 async data storage
I'm creating a testing application that has 1000s of questions hosted on firebase. To prevent downloading the questions multiple times, I've implemented a questions service where in the constructor I download the questions:

```<code>this.db.list("questions/", { preserveSnapshot: true}).subscribe(snapshots => {...}
</code>```

This downloads the questions and pushes them to a questions array so that I don't have to re download until the next session. I also have a function to serve the questions:

```<code>getQuestion(){
    return this.questions[0];
}
</code>```

However, because of the asynchronous nature of firebase, often times the data is not yet downloaded before getQuestion() is called, so it returns  undefined.

Is there a proper way to implement this data store type pattern in angular, and make sure the async call in the constructor finishes before getQuestion() gets called?

I've tried adding a variable ready, initializing it to false, and setting it to true when the async call returns. Then, getQuestions() is modified to look like:

```<code>getQuestion(){
    while(!this.ready()){}
    return this.questions[0];
}
</code>```

However this just causes the app to hang.

答:
Call getQuestion() function after Data from FireBase was downloaded.
Use blow code:

```<code>this.db.list("questions/").subscribe(list => {...} //etc
</code>```

Title: Angular 4 async data storage

Body:
I'm creating a testing application that has 1000s of questions hosted on firebase. To prevent downloading the questions multiple times, I've implemented a questions service where in the constructor I download the questions:

this.db.list("questions/", { preserveSnapshot: true}).subscribe(snapshots => {...}

This downloads the questions and pushes them to a questions array so that I don't have to re download until the next session. I also have a function to serve the questions:

getQuestion(){
    return this.questions[0];
}

However, because of the asynchronous nature of firebase, often times the data is not yet downloaded before getQuestion() is called, so it returns  undefined.

Is there a proper way to implement this data store type pattern in angular, and make sure the async call in the constructor finishes before getQuestion() gets called?

I've tried adding a variable ready, initializing it to false, and setting it to true when the async call returns. Then, getQuestions() is modified to look like:

getQuestion(){
    while(!this.ready()){}
    return this.questions[0];
}

However this just causes the app to hang.

Body:
Call getQuestion() function after Data from FireBase was downloaded.
Use blow code:

this.db.list("questions/").subscribe(list => {...} //etc


问:
How are same hash vs same key handled?
This question is not specific to any programming language, I am more interested in a generic logic.

Generally, associative maps take a key and map it to a value. As far as I know, implementations require the keys to be unique otherwise values get overwritten. Alright.

So let us assume that the above is done by some hash implementation.
What if two DIFFERENT keys get the same hash value? I am thinking of this in the form of an underlying array whose indices are in a result of hash on said keys. It could be possible that more than one unique key gets mapped to the same value yes? If so, how does such an implementation handle this?
How is handling same hash different from handling same key? Since same key results in overwriting and same hash HAS to retain the value.

I understand hashing with collision, so I know chaining and probing. Do implementations iterate over the current values which are hashed to a particular index and determine if the key is the same?

While I was searching for the answer I came across these links:

1. What happens when a duplicate key is put into a HashMap?

2. HashMap with multiple values under the same key

They don't answer my question however. How do we distinguish between same hash vs same key?

答:
By comparing the keys. If you look at object-oriented implementations of hash maps, you'll find that they usually require two methods to be implemented on the key type:

```<code>bool equal(Key key1, Key key2);
int hash(Key key);
</code>```

If only the hash function can be given and no equality function, that restricts the hash map to be based on the language's default equality. This is not always desirable as sometimes keys need to be compared with a different equality function. For example, if the keys are strings, an application may need to do a case-insensitive comparison, and then it would pass a hash function that converts to lowercase before hashing, and an equal function that ignores case.

The hash map stores the key alongside each corresponding value. (Usually, that's a pointer to the key object that was originally stored.) Any lookup into the hash map has to make a key comparison after finding a matching hash, to verify that the key actually matches.

For example, for a very simple hash map that stores a list in each bucket, the list would be a list of (key, value) pairs, and any lookup compares the keys of each list entry until it finds a match. In pseudocode:

```<code>Array<List<Pair<Key, Value>>> buckets;
Value lookup(Key k_sought) {
    int h = hash(k_sought);
    List<Pair<Key, Value>> bucket = buckets[h];
    for (kv in bucket) {
        Key k_found = kv.0;
        Value v_found = kv.1;
        if (equal(k_sought, k_found)) {
            return v_found;
        }
    }
    throw Not_found;
}
</code>```

Title: How are same hash vs same key handled?

Body:
By comparing the keys. If you look at object-oriented implementations of hash maps, you'll find that they usually require two methods to be implemented on the key type:

bool equal(Key key1, Key key2);
int hash(Key key);

If only the hash function can be given and no equality function, that restricts the hash map to be based on the language's default equality. This is not always desirable as sometimes keys need to be compared with a different equality function. For example, if the keys are strings, an application may need to do a case-insensitive comparison, and then it would pass a hash function that converts to lowercase before hashing, and an equal function that ignores case.

The hash map stores the key alongside each corresponding value. (Usually, that's a pointer to the key object that was originally stored.) Any lookup into the hash map has to make a key comparison after finding a matching hash, to verify that the key actually matches.

For example, for a very simple hash map that stores a list in each bucket, the list would be a list of (key, value) pairs, and any lookup compares the keys of each list entry until it finds a match. In pseudocode:

Array<List<Pair<Key, Value>>> buckets;
Value lookup(Key k_sought) {
    int h = hash(k_sought);
    List<Pair<Key, Value>> bucket = buckets[h];
    for (kv in bucket) {
        Key k_found = kv.0;
        Value v_found = kv.1;
        if (equal(k_sought, k_found)) {
            return v_found;
        }
    }
    throw Not_found;
}


问:
How to get the inner array from json in android?
```<code>{"Suggestions":[{"Itinerary_1":[{"Cities":"Madurai - Pazhamudir Cholai (Madurai) - Pillayarpatti - Chennai","Citieids":"14-85-114-2","Kms":595}],"Itinerary_2":[{"Cities":"Madurai - Pillayarpatti - Pillayarpatti - Chennai","Citieids":"14-114-114-2","Kms":560}],"Itinerary_3":[{"Cities":"Madurai - Pillayarpatti - Pillayarpatti - Chennai","Citieids":"14-114-114-2","Kms":560}]}]}
</code>```

This my json response.This json have a inner array how can i get the value

This my code:

```<code>class itinerarydetails extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         */
        boolean failure = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
            // Check for success tag
            int success;

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("orgin", "14"));
            params.add(new BasicNameValuePair("destination", "2"));
            params.add(new BasicNameValuePair("orgin_date", "28/06/2017"));
            params.add(new BasicNameValuePair("destination_date", "07/07/2017"));

             json = jsonParser.makeHttpRequest(itineraryurl, "GET",
                    params);
            try {

                //Suggestions
                jsonarray = json.getJSONArray("Suggestions");
               // JSONArray list = mainObj.getJSONArray("prodCat_list");

                String check;
                if(jsonarray != null) {
                   // Toast.makeText(getApplicationCon                                                                                text(), "MAIN ARRAY IS NOT EMPTY ITS HAVE A VALUE",
                    //  Toast.LENGTH_SHORT).show();

                    Log.d("check","MAIN ARRAY IS NOT EMPTY ITS HAVE A VALUE");

                    for (int i = 0; i < jsonarray.length(); i++) {
                        //   JSONObject elem = list.getJSONObject(i);

                        JSONObject object = jsonarray.getJSONObject(i);

                        //JSONArray prods = elem.getJSONArray("prods");

                        jsoninsidearray = object.getJSONArray("Itinerary_1");

                        if(jsoninsidearray != null) {

                            Log.d("check","INSIDE ARRAY IS NOT EMPTY ITS HAVE A VALUE");

                            for (int j = 0; j < jsoninsidearray.length(); j++) {
                                JSONObject innerElem = jsoninsidearray.getJSONObject(j);

                                if(innerElem != null) {

                                    Log.d("check","innerElement ARRAY IS NOT EMPTY ITS HAVE A VALUE");
                                    cityjson = innerElem.getString("Cities");
                                    itinerary = innerElem.getString("Citieids");
                                    totalkms = innerElem.getString("Kms");

                                }
                               else
                                {
                                    Log.d("check","innerElement ARRAY IS EMPTY");

                                }

                            }
                        }
                        else
                        {
                           Toast.makeText(getApplicationContext(), "INSIDE ARRAY IS EMPTY",
                                   Toast.LENGTH_SHORT).show();

                            Log.d("check","INSIDE ARRAY IS EMPTY");
                        }

                    }
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "MAIN ARRAY IS EMPTY",
                            Toast.LENGTH_SHORT).show();

                    Log.d("check","MAIN ARRAY IS EMPTY");
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        protected void onPostExecute(String file_url) {

            Toast.makeText(getApplicationContext(), "hai",
                    Toast.LENGTH_SHORT).show();
            Toast.makeText(getApplicationContext(), cityjson, Toast.LENGTH_SHORT).show();

        }

    }
</code>```

I am Vignesh i have a doubt so pls help in this below
but empty values has displayed.how can i get the values from inner array from json.

答:
here you have to create jsonobject first try this  </p>

```<code>JSONObject object = new JSONObject(json);
JSONArray data = object.getJSONArray("Suggestions");

        JSONObject obj1 = data.getJSONObject(0);

            JSONArray inner = obj1.getJSONArray("Itinerary_1");
            String Cities=inner.getString(0);
            String Citiesids=inner.getString(1);
            String Kms=inner.getString(2);
//and so on copy and change the name of Itinerary_*

}
</code>```

Body:
{"Suggestions":[{"Itinerary_1":[{"Cities":"Madurai - Pazhamudir Cholai (Madurai) - Pillayarpatti - Chennai","Citieids":"14-85-114-2","Kms":595}],"Itinerary_2":[{"Cities":"Madurai - Pillayarpatti - Pillayarpatti - Chennai","Citieids":"14-114-114-2","Kms":560}],"Itinerary_3":[{"Cities":"Madurai - Pillayarpatti - Pillayarpatti - Chennai","Citieids":"14-114-114-2","Kms":560}]}]}

This my json response.This json have a inner array how can i get the value

This my code:

class itinerarydetails extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         */
        boolean failure = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
            // Check for success tag
            int success;

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("orgin", "14"));
            params.add(new BasicNameValuePair("destination", "2"));
            params.add(new BasicNameValuePair("orgin_date", "28/06/2017"));
            params.add(new BasicNameValuePair("destination_date", "07/07/2017"));

             json = jsonParser.makeHttpRequest(itineraryurl, "GET",
                    params);
            try {

                //Suggestions
                jsonarray = json.getJSONArray("Suggestions");
               // JSONArray list = mainObj.getJSONArray("prodCat_list");

                String check;
                if(jsonarray != null) {
                   // Toast.makeText(getApplicationCon                                                                                text(), "MAIN ARRAY IS NOT EMPTY ITS HAVE A VALUE",
                    //  Toast.LENGTH_SHORT).show();

                    Log.d("check","MAIN ARRAY IS NOT EMPTY ITS HAVE A VALUE");

                    for (int i = 0; i < jsonarray.length(); i++) {
                        //   JSONObject elem = list.getJSONObject(i);

                        JSONObject object = jsonarray.getJSONObject(i);

                        //JSONArray prods = elem.getJSONArray("prods");

                        jsoninsidearray = object.getJSONArray("Itinerary_1");

                        if(jsoninsidearray != null) {

                            Log.d("check","INSIDE ARRAY IS NOT EMPTY ITS HAVE A VALUE");

                            for (int j = 0; j < jsoninsidearray.length(); j++) {
                                JSONObject innerElem = jsoninsidearray.getJSONObject(j);

                                if(innerElem != null) {

                                    Log.d("check","innerElement ARRAY IS NOT EMPTY ITS HAVE A VALUE");
                                    cityjson = innerElem.getString("Cities");
                                    itinerary = innerElem.getString("Citieids");
                                    totalkms = innerElem.getString("Kms");

                                }
                               else
                                {
                                    Log.d("check","innerElement ARRAY IS EMPTY");

                                }

                            }
                        }
                        else
                        {
                           Toast.makeText(getApplicationContext(), "INSIDE ARRAY IS EMPTY",
                                   Toast.LENGTH_SHORT).show();

                            Log.d("check","INSIDE ARRAY IS EMPTY");
                        }

                    }
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "MAIN ARRAY IS EMPTY",
                            Toast.LENGTH_SHORT).show();

                    Log.d("check","MAIN ARRAY IS EMPTY");
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        protected void onPostExecute(String file_url) {

            Toast.makeText(getApplicationContext(), "hai",
                    Toast.LENGTH_SHORT).show();
            Toast.makeText(getApplicationContext(), cityjson, Toast.LENGTH_SHORT).show();

        }

    }

I am Vignesh i have a doubt so pls help in this below
but empty values has displayed.how can i get the values from inner array from json.

Body:
here you have to create jsonobject first try this

JSONObject object = new JSONObject(json);
JSONArray data = object.getJSONArray("Suggestions");

        JSONObject obj1 = data.getJSONObject(0);

            JSONArray inner = obj1.getJSONArray("Itinerary_1");
            String Cities=inner.getString(0);
            String Citiesids=inner.getString(1);
            String Kms=inner.getString(2);
//and so on copy and change the name of Itinerary_*

}


问:
Move file downloaded in Dockerfile to harddrive
First off, I really lack a lot of knowledge regarding Docker itself and its structure. I know that it'd be way more beneficial to learn the basics first, but I do require this to work in order to move on to other things for now.

So within a Dockerfile I installed wget & used it to download a file from a website, authentification & download are successful. However, when I later try move said file it can't be found, and it doesn't show up using e.g explorer either (path was specified)
I thought it might have something to do with RUN & how it executes the wget command; I read that the Id can be used to copy it to harddrive, but how'd I do that within a Dockerfile?

```<code>RUN wget -P ./path/to/somewhere http://something.com/file.txt --username xyz --password bluh

ADD ./path/to/somewhere/file.txt /mainDirectory
</code>```

Download is shown & log-in is successful, but as I mentioned I am having trouble using that file later on as it's not to be located on the harddrive. Probably a basic error, but I'd really appreciate some input that might lead to a solution.

Obviously the error is produced when trying to execute ADD as there is no file to move. I am trying to find a way to mount a volume in order to store it, but so far in vain.

Edit:
Though the question is similiar to the "move to harddrive" one, I am searching for ways to get the id of the container created within the Dockerfile in order to move it; while the thread provides such answers, I haven't had any luck using them within the Dockerfile itself.

答:
Short answer is that it's not possible.

The Dockerfile builds an image, which you can run as a short-lived container. During the build, you don't have (write) access to the host and its file system. Which kinda makes sense, since you want to build an immutable image from which to run ephemeral containers.

What you can do is run a container, and mount a path from your host as a volume into the container. This is the only way how you can share files between the host and a container.

Here is an example how you could do this with the sherylynn/wget image:

```<code>docker run -v /path/on/host:/path/in/container sherylynn/wget wget -O /path/in/container/file http://my.url.com
</code>```

The -v HOST:CONTAINER parameter allows you to specify a path on the host that is mounted inside the container at a specified location.

For wget, I would prefer -O over -P when downloading a single file, since it makes it really explicit where your download ends up. When you point -O to the location of the volume, the downloaded file ends up on the host system (in the folder you mounted).

Since I have no idea what your image or your environment looks like, you might need to tweak one or two things to work well with your own image. As a general recommendation: For basic commands like wget or curl, you can find pre-made images on Docker Hub. This can be quite useful when you need to set up a Continuous Integration pipeline or so, where you want to use wget or curl but can't execute it directly.

Body:
First off, I really lack a lot of knowledge regarding Docker itself and its structure. I know that it'd be way more beneficial to learn the basics first, but I do require this to work in order to move on to other things for now.

So within a Dockerfile I installed wget & used it to download a file from a website, authentification & download are successful. However, when I later try move said file it can't be found, and it doesn't show up using e.g explorer either (path was specified)
I thought it might have something to do with RUN & how it executes the wget command; I read that the Id can be used to copy it to harddrive, but how'd I do that within a Dockerfile?

RUN wget -P ./path/to/somewhere http://something.com/file.txt --username xyz --password bluh

ADD ./path/to/somewhere/file.txt /mainDirectory

Download is shown & log-in is successful, but as I mentioned I am having trouble using that file later on as it's not to be located on the harddrive. Probably a basic error, but I'd really appreciate some input that might lead to a solution.

Obviously the error is produced when trying to execute ADD as there is no file to move. I am trying to find a way to mount a volume in order to store it, but so far in vain.

Edit:
Though the question is similiar to the "move to harddrive" one, I am searching for ways to get the id of the container created within the Dockerfile in order to move it; while the thread provides such answers, I haven't had any luck using them within the Dockerfile itself.

Body:
Short answer is that it's not possible.

The Dockerfile builds an image, which you can run as a short-lived container. During the build, you don't have (write) access to the host and its file system. Which kinda makes sense, since you want to build an immutable image from which to run ephemeral containers.

What you can do is run a container, and mount a path from your host as a volume into the container. This is the only way how you can share files between the host and a container.

Here is an example how you could do this with the sherylynn/wget image:

docker run -v /path/on/host:/path/in/container sherylynn/wget wget -O /path/in/container/file http://my.url.com

The -v HOST:CONTAINER parameter allows you to specify a path on the host that is mounted inside the container at a specified location.

For wget, I would prefer -O over -P when downloading a single file, since it makes it really explicit where your download ends up. When you point -O to the location of the volume, the downloaded file ends up on the host system (in the folder you mounted).

Since I have no idea what your image or your environment looks like, you might need to tweak one or two things to work well with your own image. As a general recommendation: For basic commands like wget or curl, you can find pre-made images on Docker Hub. This can be quite useful when you need to set up a Continuous Integration pipeline or so, where you want to use wget or curl but can't execute it directly.


问:
Calculate time duration using python
```<code>>>> M1
['month:12;year:2006', 'month:7;year:2010']
>>> M2
['month:5;year:2006', 'month:3;year:2010']
>>> M3
['year:2006'; 'month:4;year:2010']
</code>```

I have 3 list item M1, M2, M3

```<code>M1[0] is the Start date
M2[0] is the End date
</code>```

is it possible to convert the list this way and perform computations

```<code>M1 = 12/2006, 7/2010
M2 = 5/2006, 3/2010
M3 = 0/2006, 4/2010
</code>```

What i want is to calculate the difference between them in months like,

```<code>M1Diff = 43 months
M2Diff =  52 months
M3Diff = 51 months
</code>```

答:
I will show how to do it, for the first, in same way you can implement

```<code>def diff_month(d1, d2):
    return abs((d1.year - d2.year) * 12 + d1.month - d2.month)

M1=['month:12;year:2006', 'month:7;year:2010']
d1 = datetime.strptime(M1[0], 'month:%m;year:%Y')
d2 = datetime.strptime(M1[1], 'month:%m;year:%Y')

diff_month(d1, d2)
</code>```

In this method just use for loop for all the date collection.

Hope this helps

Title: Calculate time duration using python

Body:
>>> M1
['month:12;year:2006', 'month:7;year:2010']
>>> M2
['month:5;year:2006', 'month:3;year:2010']
>>> M3
['year:2006'; 'month:4;year:2010']

I have 3 list item M1, M2, M3

M1[0] is the Start date
M2[0] is the End date

is it possible to convert the list this way and perform computations

M1 = 12/2006, 7/2010
M2 = 5/2006, 3/2010
M3 = 0/2006, 4/2010

What i want is to calculate the difference between them in months like,

M1Diff = 43 months
M2Diff =  52 months
M3Diff = 51 months

Body:
I will show how to do it, for the first, in same way you can implement

def diff_month(d1, d2):
    return abs((d1.year - d2.year) * 12 + d1.month - d2.month)

M1=['month:12;year:2006', 'month:7;year:2010']
d1 = datetime.strptime(M1[0], 'month:%m;year:%Y')
d2 = datetime.strptime(M1[1], 'month:%m;year:%Y')

diff_month(d1, d2)

In this method just use for loop for all the date collection.

Hope this helps


问:
converting date format to yyyy-mm-dd sql server c#
I am creating a web app in which i want to convert the date format into yyyy-mm-dd

currently i am getting date in the following format Saturday, July 1, 2017

here is my full select query

```<code>SELECT
    ROW_NUMBER() OVER (ORDER BY D.D_ID ) AS SL,
    D.D_DATE, D.USER_TP, D_ITEM_TYPE,D_AUTH_REF,D.D_ID, D.SUR_REFNO, D.REF_NO_DT,
    M.PART_NO,
    S.D_NAME,
    PART_DESC, DENOM, QTY_DEM, STORE_TYPE, ITEM_TYPE, EQUIPMENT,D_NO
FROM SURVEY_HDR D, DEMAND_STATUS S, STORE_MASTER M
WHERE
    M.STORE_ID=D.PART_NO_ID
    AND S.D_ID=D.D_STATUS
    AND D_DATE >= CONVERT(VarChar, 'Saturday, July 1, 2017',1)
    AND D_DATE <= CONVERT(VarChar, 'Monday, July 31, 2017',1)
ORDER BY D.D_ID
</code>```

but i am getting the following error

Msg 241, Level 16, State 1, Line 3 Conversion failed when converting
  date and/or time from character string.

NOTE

D_DATE is in Date format and date is being stored as '2011-01-01'

how can i convert the date?

答:
Convert both into the same format as "MM/dd/yyyy".

Change

```<code>CONVERT(VarChar, 'Saturday, July 1, 2017',1) To cast(SUBSTRING ( CONVERT(VarChar, 'Saturday, July 1, 2017',1) ,CHARINDEX ( ',',CONVERT(VarChar, 'Saturday, July 1, 2017',1) )+1 , Len(CONVERT(VarChar, 'Saturday, July 1, 2017',1)) ) as date)
</code>```

and

```<code>CONVERT(VarChar, 'Monday, July 31, 2017',1) To cast(SUBSTRING ( CONVERT(VarChar, 'Monday, July 31, 2017',1) ,CHARINDEX ( ',',CONVERT(VarChar, 'Monday, July 31, 2017',1) )+1 , Len(CONVERT(VarChar, 'Monday, July 31, 2017',1)) ) as date)
</code>```

And Here is your query

```<code> SELECT
        ROW_NUMBER() OVER (ORDER BY D.D_ID ) AS SL,
        D.D_DATE, D.USER_TP, D_ITEM_TYPE,D_AUTH_REF,D.D_ID, D.SUR_REFNO, D.REF_NO_DT,
        M.PART_NO,
        S.D_NAME,
        PART_DESC, DENOM, QTY_DEM, STORE_TYPE, ITEM_TYPE, EQUIPMENT,D_NO
    FROM SURVEY_HDR D, DEMAND_STATUS S, STORE_MASTER M
    WHERE
        M.STORE_ID=D.PART_NO_ID
        AND S.D_ID=D.D_STATUS
        AND Cast(D_DATE as Date) >= cast(SUBSTRING ( CONVERT(VarChar, 'Saturday, July 1, 2017',1) ,CHARINDEX ( ',',CONVERT(VarChar, 'Saturday, July 1, 2017',1) )+1 , Len(CONVERT(VarChar, 'Saturday, July 1, 2017',1)) ) as date)
        AND Cast(D_DATE as Date) <= cast(SUBSTRING ( CONVERT(VarChar, 'Monday, July 31, 2017',1) ,CHARINDEX ( ',',CONVERT(VarChar, 'Monday, July 31, 2017',1) )+1 , Len(CONVERT(VarChar, 'Monday, July 31, 2017',1)) ) as date)
    ORDER BY D.D_ID
</code>```

Body:
I am creating a web app in which i want to convert the date format into yyyy-mm-dd

currently i am getting date in the following format Saturday, July 1, 2017

here is my full select query

SELECT
    ROW_NUMBER() OVER (ORDER BY D.D_ID ) AS SL,
    D.D_DATE, D.USER_TP, D_ITEM_TYPE,D_AUTH_REF,D.D_ID, D.SUR_REFNO, D.REF_NO_DT,
    M.PART_NO,
    S.D_NAME,
    PART_DESC, DENOM, QTY_DEM, STORE_TYPE, ITEM_TYPE, EQUIPMENT,D_NO
FROM SURVEY_HDR D, DEMAND_STATUS S, STORE_MASTER M
WHERE
    M.STORE_ID=D.PART_NO_ID
    AND S.D_ID=D.D_STATUS
    AND D_DATE >= CONVERT(VarChar, 'Saturday, July 1, 2017',1)
    AND D_DATE <= CONVERT(VarChar, 'Monday, July 31, 2017',1)
ORDER BY D.D_ID

but i am getting the following error

Msg 241, Level 16, State 1, Line 3 Conversion failed when converting
  date and/or time from character string.

NOTE

D_DATE is in Date format and date is being stored as '2011-01-01'

how can i convert the date?

Body:
Convert both into the same format as "MM/dd/yyyy".

Change

CONVERT(VarChar, 'Saturday, July 1, 2017',1) To cast(SUBSTRING ( CONVERT(VarChar, 'Saturday, July 1, 2017',1) ,CHARINDEX ( ',',CONVERT(VarChar, 'Saturday, July 1, 2017',1) )+1 , Len(CONVERT(VarChar, 'Saturday, July 1, 2017',1)) ) as date)

and

CONVERT(VarChar, 'Monday, July 31, 2017',1) To cast(SUBSTRING ( CONVERT(VarChar, 'Monday, July 31, 2017',1) ,CHARINDEX ( ',',CONVERT(VarChar, 'Monday, July 31, 2017',1) )+1 , Len(CONVERT(VarChar, 'Monday, July 31, 2017',1)) ) as date)

And Here is your query

 SELECT
        ROW_NUMBER() OVER (ORDER BY D.D_ID ) AS SL,
        D.D_DATE, D.USER_TP, D_ITEM_TYPE,D_AUTH_REF,D.D_ID, D.SUR_REFNO, D.REF_NO_DT,
        M.PART_NO,
        S.D_NAME,
        PART_DESC, DENOM, QTY_DEM, STORE_TYPE, ITEM_TYPE, EQUIPMENT,D_NO
    FROM SURVEY_HDR D, DEMAND_STATUS S, STORE_MASTER M
    WHERE
        M.STORE_ID=D.PART_NO_ID
        AND S.D_ID=D.D_STATUS
        AND Cast(D_DATE as Date) >= cast(SUBSTRING ( CONVERT(VarChar, 'Saturday, July 1, 2017',1) ,CHARINDEX ( ',',CONVERT(VarChar, 'Saturday, July 1, 2017',1) )+1 , Len(CONVERT(VarChar, 'Saturday, July 1, 2017',1)) ) as date)
        AND Cast(D_DATE as Date) <= cast(SUBSTRING ( CONVERT(VarChar, 'Monday, July 31, 2017',1) ,CHARINDEX ( ',',CONVERT(VarChar, 'Monday, July 31, 2017',1) )+1 , Len(CONVERT(VarChar, 'Monday, July 31, 2017',1)) ) as date)
    ORDER BY D.D_ID


问:
Mysql Select Empty Cells not showing [WHERE part]
I'm doing a software for payment control as a freelance, but I have a few issues about mysql.
I have a table that works as a log, called "Bitacora". In the table I have a column named idCliente, that it is the id of a person in its own table, because I have another table named "Cliente" with a column named "idCliente" so when i do the select I expect to show the name of the client.

The example below shows how the table "Bitacora" works with 3 rows.

```<code>idBitacora, tipoBitacora, **idCliente**, idPago, idPagoVario, fecha, razon

'1', '1', **'6',** '-1', '-1', '2017-05-06 21:52:53', ''

'2', '1', **'7',** '-1', '-1', '2017-05-06 21:53:01', ''

'3', '1', **'-1',** '-1', '-1', '2017-05-06 22:19:33', ''
</code>```

So I made a select query

```<code>> SELECT **IF(bitacora.tipoBitacora = 1, 'Cliente Agregado',
> IF(bitacora.tipoBitacora = 2, 'Cliente Borrado',
> IF(bitacora.tipoBitacora = 3, 'Cliente Editado',
> IF(bitacora.tipoBitacora = 4, 'Pago Mensual', IF(bitacora.tipoBitacora
> = 5, 'Pago Vario', IF(bitacora.tipoBitacora = 6, 'Intento Clave Fallida', 'Desconocido')))))) AS Suceso** , IF(bitacora.idCliente =
> -1, '', cliente.idCliente) as idCliente FROM bitacora, cliente where cliente.idCliente=bitacora.idCliente ;
</code>```

The bold above its a conditional to know what kind of log it is.

```<code>> SELECT IF(bitacora.tipoBitacora = 1, 'Cliente Agregado',
> IF(bitacora.tipoBitacora = 2, 'Cliente Borrado',
> IF(bitacora.tipoBitacora = 3, 'Cliente Editado',
> IF(bitacora.tipoBitacora = 4, 'Pago Mensual', IF(bitacora.tipoBitacora
> = 5, 'Pago Vario', IF(bitacora.tipoBitacora = 6, 'Intento Clave Fallida', 'Desconocido')))))) AS Suceso , **IF(bitacora.idCliente =
> -1, '', cliente.idCliente) as idCliente** FROM bitacora, cliente where cliente.idCliente=bitacora.idCliente ;
</code>```

And the bold above its a conditional I made to make sure that if there is no client in cliente.idCliente the row can still show up, but in my results the one with the bitacora.idCliente that doesnt appear in Cliente (-1) doesnt show, so with the example of the first table shown, the query only return

```<code>> Cliente Agregado |Mark
> Cliente Agregado |Zack
</code>```

But I want to get

```<code>> Cliente Agregado |Mark
>
> Cliente Agregado |Zack
>
> Cliente Agregado |(nothing)
</code>```

And I have tried, but still can't get what I want, I think its because the WHERE part. But still cant figure it out, after days, I think a need some help please.

答:
```<code>SELECT IF(bitacora.tipoBitacora = 1, 'Cliente Agregado', IF(bitacora.tipoBitacora = 2, 'Cliente Borrado', IF(bitacora.tipoBitacora = 3, 'Cliente Editado', IF(bitacora.tipoBitacora = 4, 'Pago Mensual', IF(bitacora.tipoBitacora = 5, 'Pago Vario', IF(bitacora.tipoBitacora = 6, 'Intento Clave Fallida', 'Desconocido')))))) AS Suceso , IF(bitacora.idCliente = -1, '', cliente.idCliente) as idCliente
FROM bitacora
LEFT JOIN cliente ON cliente.idCliente=bitacora.idCliente;
</code>```

You should use like above because If we join tables with comma separated then INNER JOIN will be applied. Try as above! Hope this will help you.

For well understanding visit this link - SQL left join vs multiple tables on FROM line?

Body:
I'm doing a software for payment control as a freelance, but I have a few issues about mysql.
I have a table that works as a log, called "Bitacora". In the table I have a column named idCliente, that it is the id of a person in its own table, because I have another table named "Cliente" with a column named "idCliente" so when i do the select I expect to show the name of the client.

The example below shows how the table "Bitacora" works with 3 rows.

idBitacora, tipoBitacora, **idCliente**, idPago, idPagoVario, fecha, razon

'1', '1', **'6',** '-1', '-1', '2017-05-06 21:52:53', ''

'2', '1', **'7',** '-1', '-1', '2017-05-06 21:53:01', ''

'3', '1', **'-1',** '-1', '-1', '2017-05-06 22:19:33', ''

So I made a select query

> SELECT **IF(bitacora.tipoBitacora = 1, 'Cliente Agregado',
> IF(bitacora.tipoBitacora = 2, 'Cliente Borrado',
> IF(bitacora.tipoBitacora = 3, 'Cliente Editado',
> IF(bitacora.tipoBitacora = 4, 'Pago Mensual', IF(bitacora.tipoBitacora
> = 5, 'Pago Vario', IF(bitacora.tipoBitacora = 6, 'Intento Clave Fallida', 'Desconocido')))))) AS Suceso** , IF(bitacora.idCliente =
> -1, '', cliente.idCliente) as idCliente FROM bitacora, cliente where cliente.idCliente=bitacora.idCliente ;

The bold above its a conditional to know what kind of log it is.

> SELECT IF(bitacora.tipoBitacora = 1, 'Cliente Agregado',
> IF(bitacora.tipoBitacora = 2, 'Cliente Borrado',
> IF(bitacora.tipoBitacora = 3, 'Cliente Editado',
> IF(bitacora.tipoBitacora = 4, 'Pago Mensual', IF(bitacora.tipoBitacora
> = 5, 'Pago Vario', IF(bitacora.tipoBitacora = 6, 'Intento Clave Fallida', 'Desconocido')))))) AS Suceso , **IF(bitacora.idCliente =
> -1, '', cliente.idCliente) as idCliente** FROM bitacora, cliente where cliente.idCliente=bitacora.idCliente ;

And the bold above its a conditional I made to make sure that if there is no client in cliente.idCliente the row can still show up, but in my results the one with the bitacora.idCliente that doesnt appear in Cliente (-1) doesnt show, so with the example of the first table shown, the query only return

> Cliente Agregado |Mark
> Cliente Agregado |Zack

But I want to get

> Cliente Agregado |Mark
>
> Cliente Agregado |Zack
>
> Cliente Agregado |(nothing)

And I have tried, but still can't get what I want, I think its because the WHERE part. But still cant figure it out, after days, I think a need some help please.

Body:
SELECT IF(bitacora.tipoBitacora = 1, 'Cliente Agregado', IF(bitacora.tipoBitacora = 2, 'Cliente Borrado', IF(bitacora.tipoBitacora = 3, 'Cliente Editado', IF(bitacora.tipoBitacora = 4, 'Pago Mensual', IF(bitacora.tipoBitacora = 5, 'Pago Vario', IF(bitacora.tipoBitacora = 6, 'Intento Clave Fallida', 'Desconocido')))))) AS Suceso , IF(bitacora.idCliente = -1, '', cliente.idCliente) as idCliente
FROM bitacora
LEFT JOIN cliente ON cliente.idCliente=bitacora.idCliente;

You should use like above because If we join tables with comma separated then INNER JOIN will be applied. Try as above! Hope this will help you.

For well understanding visit this link - SQL left join vs multiple tables on FROM line?


问:
How to do JavaScript alert in static method server side code in Asp.net?
I want to do JavaScript alert in static method server side code in asp.net with C#. I tried many ways, but it's not working.

For example, I tried

```<code>[WebMethod]
public static void EntrySave(string schoolName)
{
      Response.Write("<script>alert('Hello');</script>");
}
</code>```

and

```<code>[WebMethod]
public static void EntrySave(string schoolName)
{
      ScriptManager.RegisterStartupScript(this, GetType(), "showalert",
       "alert('Only alert Message');", true);
}
</code>```

and many more. But it's not showing alert in webstatic method.

答:
Some examples may help you

https://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx

https://www.aspsnippets.com/Articles/Send-and-receive-JavaScript-Array-to-Web-Service-Web-Method-using-ASP.Net-AJAX.aspx

Response.Write() in WebService

Body:
I want to do JavaScript alert in static method server side code in asp.net with C#. I tried many ways, but it's not working.

For example, I tried

[WebMethod]
public static void EntrySave(string schoolName)
{
      Response.Write("");
}

and

[WebMethod]
public static void EntrySave(string schoolName)
{
      ScriptManager.RegisterStartupScript(this, GetType(), "showalert",
       "alert('Only alert Message');", true);
}

and many more. But it's not showing alert in webstatic method.