问:
How is "rax" different from "eax"?
I'm reading "Hacking: The Art of Exploitation".

In the book the registers are different from the registers that I can see on my pc. These are my cpu registers:

rax,
rbx,
rcx,
rdx,
rsi,
rdi,
rbp,
rsp,
r8,
r9,
r10,
r11,
r12,
r13,
r14,
r15,
rip,
eflags,
cs,
ss,
ds,
es,
fs,
gs

while in the book the registers are:

eax,
ecx,
edx,
ebx,
esp,
ebp,
esi,
edi,
eip,
eflags,
cs,
ss,
ds,
es,
fs,
gs

Can someone explain why they are different? I'm running on an AMD cpu; does AMD have different CPU registers from Intel?

In this case can someone explain me the correspondence between the registers of the two architecture?

答:
The registers starting with r as in rax, rbx, etc, are the 64-bit registers introduced with the AMD64 extension to the existing 32-bit x86 ISA. That ISA extension was subsequently adopted by Intel and is often known by the more neutral name x86-64. Essentially all x86 chips released in the last decade from AMD and Intel support this ISA.

Registers like eax, ebx, etc are the 32-bit registers which exist both in the original 32-bit x86 ISA, as well as the 64-bit x86-64. If your book refers only to those registers, it is likely that it doesn't cover the 64-bit extension (perhaps it was written before it).

Note that the 32-bit and the 64-bit registers are not separate registers since they overlap: the 64-bit rax, for example, has eax as its bottom 32-bits, and so on for rbx and ebx, r8 and r8d and so on. Therefore, modifications to a 32-bit register are reflected in the corresponding 64-bit register, and vice versa.

A similar relationship exists among the 16-bit (ax, etc) and 8-bit (al, etc) registers. You can find all the gory details in many places.

ContentLicense: CC BY-SA 4.0

Title: How is "rax" different from "eax"?


来源: stackexchange

问:
Excel time format auto-change issue
I'm currently working on an Excel application that can get info from my Form worksheet and display it into Display worksheet. So far the data can transfer perfectly, except for one tiny quirk.

The Display worksheet will display data when Execute is clicked.

Here is the screenshot:

Before I execute the Display, the Time field in the Form worksheet is formatted as h:mm AM/PM. However, when I click Execute in Display worksheet, the Time format suddenly changed in the Form Worksheet as seen here:

Furthermore the change in format is also seen in the Display table as well. I tried setting the format to be identical for both worksheets and the result is still the same.

Is it the issue of the SQL1 statement or the coding in general? here is the code sample.

```<code>Public Sub QueryWorksheet(szSQL As String, rgStart As Range, wbWorkBook As String, AB As String)
Dim rsData As ADODB.Recordset
Dim szConnect As String
On Error GoTo ErrHandler

If AB = "1st" Then
wbWorkBook = ActiveWorkbook.Sheets("Inner Workings").Range("B9").Text
End If

Application.StatusBar = "Retrieving data ....."
'Set up the connection string to excel - thisworkbook
szConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
            "Data Source=" & wbWorkBook & ";" & _
            "Extended Properties=Excel 8.0;"

Set rsData = New ADODB.Recordset
'Run the query as adCmdText
rsData.Open szSQL, szConnect, adOpenForwardOnly, adLockReadOnly, adCmdText

'Check if data is returned
If Not rsData.EOF Then
    'if the recordset contains data put them on the worksheet
    rgStart.CopyFromRecordset rsData
Else

End If
'Close connection
rsData.Close
'Clean up and get out
Set rsData = Nothing
Application.StatusBar = False
Exit Sub
ErrHandler:
'an error occured in the SQL-statement
MsgBox "Your query could not be executed, the SQL-statement is incorrect."
Set rsData = Nothing
Application.StatusBar = False
End Sub

Sub process()
Call clear
Call testsql("1st")  ' populate 1st Summary
Call testsql("2nd")  ' find Date+Time
Call testsql("3rd")   ' GET LATEST RECORD
End Sub

Sub testsql(AB As String)

Dim rgPlaceOutput As Range       'first cell for the output of the query
Dim stSQLstring As String     'text of the cell containing the SQL statement
Dim rg As String, SQL As String

If AB = "1st" Then
stSQLstring = ActiveWorkbook.Sheets("Inner Workings").Range("B2").Text
Set rgPlaceOutput = ActiveWorkbook.Sheets("1st Summary").Range("A2")
End If
If AB = "2nd" Then
stSQLstring = ActiveWorkbook.Sheets("Inner Workings").Range("B3").Text
Set rgPlaceOutput = ActiveWorkbook.Sheets("2nd Summary").Range("A2")
End If
If AB = "3rd" Then
stSQLstring = ActiveWorkbook.Sheets("Inner Workings").Range("B4").Text
Set rgPlaceOutput = ActiveWorkbook.Sheets("Final Summary").Range("A5")
End If

QueryWorksheet stSQLstring, rgPlaceOutput, ThisWorkbook.FullName, AB

End Sub

Sub clear()
ActiveWorkbook.Sheets("1st Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("2nd Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("Final Summary").Range("A2:BR5000").Value = Empty
End Sub
</code>```

If anyone can help with this, I greatly appreciate it.

Update:

Apparently, this quirk is larger than I thought. After more testing I found out that the second summary sheet is also affected as well as seen here. . Albeit the lower half at least. The mystery keeps piling up...

答: I think you have to look at NumberFormat iirc add something like "DD/MM/YYYY" to a Range (columns in your case). I'm on a Mac with Office 365, and although VBA is now in the app, the sort of intellisense is absent so unless you know the Excel Object model by heart it's a royal PITA!</p>

ContentLicense: CC BY-SA 3.0

Title: Excel time format auto-change issue

Body:
I'm currently working on an Excel application that can get info from my Form worksheet and display it into Display worksheet. So far the data can transfer perfectly, except for one tiny quirk.

The Display worksheet will display data when Execute is clicked.

Here is the screenshot:

Before I execute the Display, the Time field in the Form worksheet is formatted as h:mm AM/PM. However, when I click Execute in Display worksheet, the Time format suddenly changed in the Form Worksheet as seen here:

Furthermore the change in format is also seen in the Display table as well. I tried setting the format to be identical for both worksheets and the result is still the same.

Is it the issue of the SQL1 statement or the coding in general? here is the code sample.

Public Sub QueryWorksheet(szSQL As String, rgStart As Range, wbWorkBook As String, AB As String)
Dim rsData As ADODB.Recordset
Dim szConnect As String
On Error GoTo ErrHandler

If AB = "1st" Then
wbWorkBook = ActiveWorkbook.Sheets("Inner Workings").Range("B9").Text
End If

Application.StatusBar = "Retrieving data ....."
'Set up the connection string to excel - thisworkbook
szConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
            "Data Source=" & wbWorkBook & ";" & _
            "Extended Properties=Excel 8.0;"

Set rsData = New ADODB.Recordset
'Run the query as adCmdText
rsData.Open szSQL, szConnect, adOpenForwardOnly, adLockReadOnly, adCmdText

'Check if data is returned
If Not rsData.EOF Then
    'if the recordset contains data put them on the worksheet
    rgStart.CopyFromRecordset rsData
Else

End If
'Close connection
rsData.Close
'Clean up and get out
Set rsData = Nothing
Application.StatusBar = False
Exit Sub
ErrHandler:
'an error occured in the SQL-statement
MsgBox "Your query could not be executed, the SQL-statement is incorrect."
Set rsData = Nothing
Application.StatusBar = False
End Sub

Sub process()
Call clear
Call testsql("1st")  ' populate 1st Summary
Call testsql("2nd")  ' find Date+Time
Call testsql("3rd")   ' GET LATEST RECORD
End Sub

Sub testsql(AB As String)

Dim rgPlaceOutput As Range       'first cell for the output of the query
Dim stSQLstring As String     'text of the cell containing the SQL statement
Dim rg As String, SQL As String

If AB = "1st" Then
stSQLstring = ActiveWorkbook.Sheets("Inner Workings").Range("B2").Text
Set rgPlaceOutput = ActiveWorkbook.Sheets("1st Summary").Range("A2")
End If
If AB = "2nd" Then
stSQLstring = ActiveWorkbook.Sheets("Inner Workings").Range("B3").Text
Set rgPlaceOutput = ActiveWorkbook.Sheets("2nd Summary").Range("A2")
End If
If AB = "3rd" Then
stSQLstring = ActiveWorkbook.Sheets("Inner Workings").Range("B4").Text
Set rgPlaceOutput = ActiveWorkbook.Sheets("Final Summary").Range("A5")
End If

QueryWorksheet stSQLstring, rgPlaceOutput, ThisWorkbook.FullName, AB

End Sub

Sub clear()
ActiveWorkbook.Sheets("1st Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("2nd Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("Final Summary").Range("A2:BR5000").Value = Empty
End Sub

If anyone can help with this, I greatly appreciate it.

Update:

Apparently, this quirk is larger than I thought. After more testing I found out that the second summary sheet is also affected as well as seen here. . Albeit the lower half at least. The mystery keeps piling up...


问:
Pandas dataframe of tuples?
I have a pandas dataframe that I create from a list (which is created from a spark rdd) by calling:

newRdd = rdd.map(lambda row: Row(row.__fields__ + ["tag"])(row + (tagScripts(row), ))).collect() and then df = pd.DataFrame(newRdd)

My data ends up looking like a dataframe of tuples as shown below:

```<code>0  (2017-06-21, Sun, ATL, 10)
1  (2017-06-21, Sun, ATL, 11)
2  (2017-06-21, Sun, ATL, 11)
</code>```

but I need it to look like a standard table with column headers as such:

```<code>date       dayOfWeek    airport   val1
2017-06-11    Sun         ATL     11
</code>```

I'm honestly out of ideas on this one and need some help. I've tried a lot of different things and nothing has seemed to work. Any help would be greatly appreciated. Thank you for your time.

答:
You can do it like this:

```<code>df = pd.DataFrame([*df.A],columns = ['date','dayOfWeek','airport','val1','val2','val3','val4','val5','val6'])
</code>```

i supposed the column name in the dataframe you already have is A.

you can check here for tuples unpacking.

Hope this was helpful. in there are any questions please let me know.

Title: Pandas dataframe of tuples?

Body:
I have a pandas dataframe that I create from a list (which is created from a spark rdd) by calling:

newRdd = rdd.map(lambda row: Row(row.__fields__ + ["tag"])(row + (tagScripts(row), ))).collect() and then df = pd.DataFrame(newRdd)

My data ends up looking like a dataframe of tuples as shown below:

0  (2017-06-21, Sun, ATL, 10)
1  (2017-06-21, Sun, ATL, 11)
2  (2017-06-21, Sun, ATL, 11)

but I need it to look like a standard table with column headers as such:

date       dayOfWeek    airport   val1
2017-06-11    Sun         ATL     11

I'm honestly out of ideas on this one and need some help. I've tried a lot of different things and nothing has seemed to work. Any help would be greatly appreciated. Thank you for your time.

Body:
You can do it like this:

df = pd.DataFrame([*df.A],columns = ['date','dayOfWeek','airport','val1','val2','val3','val4','val5','val6'])

i supposed the column name in the dataframe you already have is A.

you can check here for tuples unpacking.

Hope this was helpful. in there are any questions please let me know.


问:
Converting python, numpy, and scipy code into C++ compatible code?
I have a segment of code that uses several functions from numpy and scipy that I need to use in C++, but my knowledge of C++ is much too limited to be able to transfer this code into this language.

What C++ functions should I need to have something like this:

```<code>import numpy as np
from scipy.integrate import quad
from scipy.optimize import minimize

minor = 2.23
major = 3.05
encoderdistance = 2.53141952655
print minimize(lambda x: abs(quad(func, 0, x)[0] - encoderdistance), 1).x
min = 90-((180/np.pi) * np.arctan(((np.tan(minimize(lambda x: abs(quad(func, 0, x)[0] - encoderdistance), 1).x))*minor)/major))
print min
</code>```

Thanks!

答: I just know Cython which can steer you the right direction. Quad http://quadpackpp.sourceforge.net can easily call from C++. Most of the numpy functions are in libc.math (abs, probably arctan, etc.). Pi you can just hardcode the value to a double. Minimize you'll have to search for the scipy source code https://github.com/scipy/scipy/blob/master/scipy/optimize/optimize.py to see what libs are called. Most numpy / scipy functions rely on Blas / Lapack or use the MKL C++ variants.</p>

Body:
I have a segment of code that uses several functions from numpy and scipy that I need to use in C++, but my knowledge of C++ is much too limited to be able to transfer this code into this language.

What C++ functions should I need to have something like this:

import numpy as np
from scipy.integrate import quad
from scipy.optimize import minimize

minor = 2.23
major = 3.05
encoderdistance = 2.53141952655
print minimize(lambda x: abs(quad(func, 0, x)[0] - encoderdistance), 1).x
min = 90-((180/np.pi) * np.arctan(((np.tan(minimize(lambda x: abs(quad(func, 0, x)[0] - encoderdistance), 1).x))*minor)/major))
print min

Thanks!


问:
rake db:schema:load loads schema.rb multiple times?
After upgrading from Rails 3 to Rails 4 the db:schema:load task is failing.  I did some digging into it and found that after the upgrade when I run bundle exec rake db:schema:load the db/schema.rb file is being loaded twice.  The first time it runs fine; then the second time through it fails due to a create_table force: true fails due to there being a dependency constraint on the table.

I've stripped out every additional rake task and enhance to try and rule out any of my code, but still this loads the schema.rb twice.  It is always exactly twice as I am able to run it successfully on SQLite and see the same behavior there, but it runs to completion due to SQLite not enforcing the table constraints.

答: You might check to be sure your Rakefile isn't loading tasks twice. When Rake registers a task with the same name as an existing task, it will run both in sequence rather than replace the old definition with the new one.</p>


问:
Threads and access to a shared list
I'm encountering (I hope) a deadlocking issue with a WCF service I'm trying to write.

I have the following lock on a function that "locates" a particular item im the list:

```<code> CIPRecipe FindRecipe_ByUniqueID(string uniqueID)
    {
        lock (_locks[LOCK_RECIPES])
        {
            foreach (var r in _recipes.Keys)
            {
                if (_recipes[r].UniqueID == uniqueID)
                {
                    return _recipes[r];
                }
            }
        }
        return null;
    }
</code>```

However, various functions reiterate through this list and always apply the same LOCK for example ....

```<code> lock (_locks[LOCK_RECIPES_NO_ADD_OR_REMOVE])
            {
                foreach (var r in _recipes)
                {
                    r.Value.UpdateSummary();
                    summaries.Add((RecipeSummary)r.Value.Summary);
                }
            }
</code>```

What I suspect is,  an item in _recipes in the above example has suddenly called a function which ultimately calls the first function - "CIPRecipe FindRecipe_ByUniqueID(string uniqueID)" and this is causing a deadlock when it is reached in the iteration.

I need to stop this list changing whilst I'm iterating through it. Can someone advise me the best practice?

Thanks

答:
What you want is to use a ReaderWriterLockSlim, this will let unlimited concurrent readers through but only a single writer through and block all readers while the writer is writing.

This assumes _locks has been chagned from a object[] to a ReaderWriterSlim[]

```<code>//On Read
CIPRecipe FindRecipe_ByUniqueID(string uniqueID)
{
    var lockObj = _locks[LOCK_RECIPES];
    lockObj.EnterReadLock();
    try
    {
        foreach (var r in _recipes.Keys)
        {
            if (_recipes[r].UniqueID == uniqueID)
            {
                return _recipes[r];
            }
        }
    }
    finally
    {
        lockObj.ExitReadLock();
    }
    return null;
}

//On write
var lockObject = _locks[LOCK_RECIPES]; //Note this now uses the same lock object as the other method.
lockObj.EnterWriteLock();
try
{
    foreach (var r in _recipes)
    {
        r.Value.UpdateSummary();
        summaries.Add((RecipeSummary)r.Value.Summary);
    }
}
finally
{
    lockObj.ExitWriteLock();
}
</code>```

I don't know if it will solve your deadlock issue, if it is caused by you allowing reads during a write it may.

Title: Threads and access to a shared list

Body:
I'm encountering (I hope) a deadlocking issue with a WCF service I'm trying to write.

I have the following lock on a function that "locates" a particular item im the list:

 CIPRecipe FindRecipe_ByUniqueID(string uniqueID)
    {
        lock (_locks[LOCK_RECIPES])
        {
            foreach (var r in _recipes.Keys)
            {
                if (_recipes[r].UniqueID == uniqueID)
                {
                    return _recipes[r];
                }
            }
        }
        return null;
    }

However, various functions reiterate through this list and always apply the same LOCK for example ....

 lock (_locks[LOCK_RECIPES_NO_ADD_OR_REMOVE])
            {
                foreach (var r in _recipes)
                {
                    r.Value.UpdateSummary();
                    summaries.Add((RecipeSummary)r.Value.Summary);
                }
            }

What I suspect is,  an item in _recipes in the above example has suddenly called a function which ultimately calls the first function - "CIPRecipe FindRecipe_ByUniqueID(string uniqueID)" and this is causing a deadlock when it is reached in the iteration.

I need to stop this list changing whilst I'm iterating through it. Can someone advise me the best practice?

Thanks

Body:
What you want is to use a ReaderWriterLockSlim, this will let unlimited concurrent readers through but only a single writer through and block all readers while the writer is writing.

This assumes _locks has been chagned from a object[] to a ReaderWriterSlim[]

//On Read
CIPRecipe FindRecipe_ByUniqueID(string uniqueID)
{
    var lockObj = _locks[LOCK_RECIPES];
    lockObj.EnterReadLock();
    try
    {
        foreach (var r in _recipes.Keys)
        {
            if (_recipes[r].UniqueID == uniqueID)
            {
                return _recipes[r];
            }
        }
    }
    finally
    {
        lockObj.ExitReadLock();
    }
    return null;
}

//On write
var lockObject = _locks[LOCK_RECIPES]; //Note this now uses the same lock object as the other method.
lockObj.EnterWriteLock();
try
{
    foreach (var r in _recipes)
    {
        r.Value.UpdateSummary();
        summaries.Add((RecipeSummary)r.Value.Summary);
    }
}
finally
{
    lockObj.ExitWriteLock();
}

I don't know if it will solve your deadlock issue, if it is caused by you allowing reads during a write it may.


问:
More elegant way than using rawQuery for single results?
To get multiple results of a query I use Cursor c = mydatabase.rawQuery("command", null); and then while (c.moveToNext()) { ... }. Works as advertised.

But if I just want to have one result as in SELECT rowSomething FROM table WHERE [row] = 'Test' and I know that it will be one result, a string, can I do something like
String result = mydatabase.StringQuery("Command");?

答: Yes, for example with DatabaseUtils#stringForQuery().


问:
Can't pass html into tinymce editor
I have saved raw html content into my database
And I will like to load them into my tinymce editor so that users can just edit the content and submit again. Below is the form;

```<code> <textarea id="postfullOnEditPop" type="text" class="validate" placeholder="Enter full post here" required>
 </textarea>
</code>```

I tried to pass the content into TinyMCE like this;

```<code>tinymce.get('postfullOnEditPop').setContent(postfull);
</code>```

but I get raw html tags instead of formatted text in the TinyMCE editor

Please does anyone knows what I am doing wrong?

答:
Try:
tinymce.get('postfullOnEditPop').setContent(postfull, {format: 'raw'});

The API isn't super helpful here, unfortunately.

Title: Can't pass html into tinymce editor

Body:
I have saved raw html content into my database
And I will like to load them into my tinymce editor so that users can just edit the content and submit again. Below is the form;

 <textarea id="postfullOnEditPop" type="text" class="validate" placeholder="Enter full post here" required>
 </textarea>

I tried to pass the content into TinyMCE like this;

tinymce.get('postfullOnEditPop').setContent(postfull);

but I get raw html tags instead of formatted text in the TinyMCE editor

Please does anyone knows what I am doing wrong?


问:
if error == nil parse swift
I'm trying to check when I save an object to my parse serve if something goes wrong. But I have two options and I have three options and I don't know the difference. I have these three options (if error == nil, or if object != nil, or if error == nil and object != nil). Which one should I use. Thanks

Option #1

```<code>let user = PFUser.current()!
user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in
    if error == nil{
    }
)}
</code>```

Option #2

```<code>let user = PFUser.current()!
user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in
    if object != nil{
    }
)}
</code>```

Option #3

```<code>let user = PFUser.current()!
user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in
    if error == nil && object != nil{
    }
)}
</code>```

答:
Better to use different handlers for success and for failure:</p>

```<code>func saveInBackground(success: () -> Void, failure: (Error?) -> Void) {
    /* do whatever you need */
    if saved {
        success()
    } else {
        failure(saveError)
    }
}

saveInBackground(success: {
    /* saving was succeed */
}, failure: { (error) in
    /* saving was failed */
})
</code>```

Title: if error == nil parse swift

Body:
I'm trying to check when I save an object to my parse serve if something goes wrong. But I have two options and I have three options and I don't know the difference. I have these three options (if error == nil, or if object != nil, or if error == nil and object != nil). Which one should I use. Thanks

Option #1

let user = PFUser.current()!
user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in
    if error == nil{
    }
)}

Option #2

let user = PFUser.current()!
user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in
    if object != nil{
    }
)}

Option #3

let user = PFUser.current()!
user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in
    if error == nil && object != nil{
    }
)}

Body:
Better to use different handlers for success and for failure:

func saveInBackground(success: () -> Void, failure: (Error?) -> Void) {
    /* do whatever you need */
    if saved {
        success()
    } else {
        failure(saveError)
    }
}

saveInBackground(success: {
    /* saving was succeed */
}, failure: { (error) in
    /* saving was failed */
})


问:
How to read the filename of a csv file in ruby
I need to read the filename of a csv file to extract some information about what to do with the data inside the file. How do I read the filename?

e.g. I will get a file called 200_SomeTestName.csv. The file will contain details of the test to be created. I'm required to create a test called SomeTestName for the student who has an id of 200.

答:
You can list all the CSV files in the dropbox folder and check if they match the pattern. Then extract the information you need and create the test:

```<code>Dir.glob('yourdropboxfolder/*.csv').each do |filename|
  name = File.basename(filename, '.csv')
  if (match = /(\d+)_(.*).csv/.match(name))
    student_id = match[1]
    test_name = match[2]
    create_test_for(student_id, test_name, File.read(filename))
  end
end
</code>```

Not sure if you need to extract the values from the filename or if this information is also in the file.

Body:
You can list all the CSV files in the dropbox folder and check if they match the pattern. Then extract the information you need and create the test:

Dir.glob('yourdropboxfolder/*.csv').each do |filename|
  name = File.basename(filename, '.csv')
  if (match = /(\d+)_(.*).csv/.match(name))
    student_id = match[1]
    test_name = match[2]
    create_test_for(student_id, test_name, File.read(filename))
  end
end

Not sure if you need to extract the values from the filename or if this information is also in the file.


问:
ASP.NET MVC Two models in ove view, code change
I had this code and it worked fine:

```<code>@model IEnumerable<Moviestore.Models.Movie>
@{
ViewBag.Title = "Index";
}

<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
    <th>
        @Html.DisplayNameFor(model => model.Title)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Genre)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Author)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Year)
    </th>
    <th></th>
</tr>

@foreach (var item in Model) {
if (item.IsDeleted == 0)
{
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Title)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Genre)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Author)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Year)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id = item.MovieID }) |
        @Html.ActionLink("Details", "Details", new { id = item.MovieID }) |
        @Html.ActionLink("Delete", "Delete", new { id = item.MovieID })
    </td>
</tr>
}
}
</table>
</code>```

But I needed to add one more model, I done that with Tuple In this way:

```<code>@using Moviestore.Models;
@model Tuple<Movie, User>

@{
ViewBag.Title = "Index";
}

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
    <th>
        @Html.DisplayNameFor(tuple => tuple.Item1.Title)
    </th>
    <th>
        @Html.DisplayNameFor(tuple => tuple.Item1.Genre)
    </th>
    <th>
        @Html.DisplayNameFor(tuple => tuple.Item1.Author)
    </th>
    <th>
        @Html.DisplayNameFor(tuple => tuple.Item1.Year)
    </th>
    <th></th>
</tr>

@foreach (var item in Model) {
if (item.IsDeleted == 0)
{
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Title)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Genre)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Author)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Year)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id = item.MovieID }) |
        @Html.ActionLink("Details", "Details", new { id = item.MovieID }) |
        @Html.ActionLink("Delete", "Delete", new { id = item.MovieID })
    </td>
</tr>
}
}
</table>
</code>```

But now I have problem with bottom half of code.
From @foreach

I don't know what I need to put instead of @foreach (var item in Model)

And will then @Html.DisplayFor(modelItem => item.Title) also need some changes.

Sorry for long post, I tried to explain the problem as best as I can.

答:
As I mentioned in the comments, the appropriate way to handle this situation (needing more than one model on a particular View page) is to use a ViewModel which contains the models you need (see here for reference).

To answer your specific question, though, you can access each item of the Tuple by its position, e.g. if your model is Tuple<Movie, User>, then you can access the Movie object by model.Item1 and the User object by model.Item2, etc.

But I strongly recommend you take the ViewModel approach that I linked instead.

Body:
I had this code and it worked fine:

@model IEnumerable<Moviestore.Models.Movie>
@{
ViewBag.Title = "Index";
}

@Html.ActionLink("Create New", "Create")

        @Html.DisplayNameFor(model => model.Title)

        @Html.DisplayNameFor(model => model.Genre)

        @Html.DisplayNameFor(model => model.Author)

        @Html.DisplayNameFor(model => model.Year)

@foreach (var item in Model) {
if (item.IsDeleted == 0)
{

        @Html.DisplayFor(modelItem => item.Title)

        @Html.DisplayFor(modelItem => item.Genre)

        @Html.DisplayFor(modelItem => item.Author)

        @Html.DisplayFor(modelItem => item.Year)

        @Html.ActionLink("Edit", "Edit", new { id = item.MovieID }) |
        @Html.ActionLink("Details", "Details", new { id = item.MovieID }) |
        @Html.ActionLink("Delete", "Delete", new { id = item.MovieID })

}
}

But I needed to add one more model, I done that with Tuple In this way:

@using Moviestore.Models;
@model Tuple<Movie, User>

@{
ViewBag.Title = "Index";
}

    @Html.ActionLink("Create New", "Create")

        @Html.DisplayNameFor(tuple => tuple.Item1.Title)

        @Html.DisplayNameFor(tuple => tuple.Item1.Genre)

        @Html.DisplayNameFor(tuple => tuple.Item1.Author)

        @Html.DisplayNameFor(tuple => tuple.Item1.Year)

@foreach (var item in Model) {
if (item.IsDeleted == 0)
{

        @Html.DisplayFor(modelItem => item.Title)

        @Html.DisplayFor(modelItem => item.Genre)

        @Html.DisplayFor(modelItem => item.Author)

        @Html.DisplayFor(modelItem => item.Year)

        @Html.ActionLink("Edit", "Edit", new { id = item.MovieID }) |
        @Html.ActionLink("Details", "Details", new { id = item.MovieID }) |
        @Html.ActionLink("Delete", "Delete", new { id = item.MovieID })

}
}

But now I have problem with bottom half of code.
From @foreach

I don't know what I need to put instead of @foreach (var item in Model)

And will then @Html.DisplayFor(modelItem => item.Title) also need some changes.

Sorry for long post, I tried to explain the problem as best as I can.


问:
Breaking down multiple Left join in multiple steps in Proc Sql
I got a code that uses a lot of left join with many tables. When I run this code, it takes more than an hour to run and at the end it gives error with Sort Execution Failure. So, I am thinking of breaking down that left join in multiple steps but I am not sure how to do it and need your help.

The code is as:

```<code>Proc sql;
create table newlib.Final_test as
SELECT
POpener.Name as Client,
Popener.PartyId as Account_Number,
Case
  When BalLoc.ConvertedRefNo NE '' then BalLoc.ConvertedRefNo
else BalLoc.Ourreferencenum
End as LC_Number,
BalLoc.OurReferenceNum ,
BalLoc.CnvLiabilityCode as Liability_Code,
POfficer.PartyID as Officer_Num,
POfficer.Name as Officer_Name,
POpener.ExpenseCode,
BalLoc.IssueDate as Issue_Date format=mmddyy10.,
BalLoc.ExpirationDate AS Expiry format=mmddyy10.,
BalLoc.LiabilityAmountBase as Total_LC_Balance,
Case
  When BalLoc.Syndicated = 0 Then BalLoc.LiabilityAmountBase
    else 0
End as SunTrust_Non_Syndicated_Exposure,
Case
  When BalLoc.Syndicated = 1 and BalLoc.PartOutGroupPkey NE 0 Then
BalLoc.LiabilityAmountBase
    else 0
  End as SunTrust_Syndicated_Exposure,
Case
  When BalLoc.Syndicated = 1 and BalLoc.PartOutGroupPkey NE 0 Then
(BalLoc.LiabilityAmountBase - (BalLoc.LiabilityAmountBase *
(PParty.ParticipationPercent/100)))
  Else BalLoc.LiabilityAmountBase
End as SunTrust_Exposure,
Case
  When BalLoc.Syndicated = 1 and BalLoc.PartOutGroupPkey <> 0 Then
(BalLoc.LiabilityAmountBase  * PParty.ParticipationPercent/100)
  Else 0
End as Exposure_Held_By_Other_Banks,
PBene.Name as Beneficiary_Trustee,
cat(put(input(POpener.ObligorNumber,best10.),z10.),put(input

   (BalLoc.CommitmentNumber,best10.),Z10.)) as Key,
case
when BalLoc.BeneCusip2 NE ' ' then catx
('|',Balloc.BeneCusip,Balloc.BeneCusip2)
else BalLoc.BeneCusip
End as Cusip,
Case
  when balLoc.OKtoExpire = 1 then '0'
  when balLOc.OKtoExpire=0 and BalLoc.AutoExtTermDays NE 0 then put
(Balloc.AutoExtTermDays,z3.)
  when balLoc.OKtoExpire=0 and BalLoc.AutoExtTermsMonth NE 0 then put
(balloc.AutoExtTermsMonth,z3.)
  else '000'
End as Evergreen
Case
when blf.AnnualRate NE 0 then put(blf.AnnualRate,z7.)
when blf.Amount NE 0 then cats('F',put(blf.amount,z7.))
else 'WAIVE'
End as Pricing,

FROM BalLocPrimary BalLoc
Left JOIN Party POpener on POpener.Pkey = BalLoc.OpenerPkey
Left join PartGroup PGroup on BallOC.PartOutGroupPkey = PGroup.pKey
Left join PartParties PParty ON PGroup.pKey = PParty.PartGroupPkey and
PParty.ParticipationPercent > 0 and
PParty.combined in
(select PPartParties.All_combined
from PPartParties /*group by PartGroupPkey, PartyPkey*/)

Left Join MemExpenseCodes ExpCodes on POpener.ExpenseCode = ExpCodes.Code
Left JOIN Party PBene on PBene.Pkey = BalLoc.BenePkey
Left join Party POfficer on POfficer.Pkey = BalLoc.AccountOfficerPkey
left join maxfee on maxfee.LocPrimaryPkey = BalLoc.LocPrimaryPkey
left join BalLocFee BLF on BLF.Pkey = maxfee.pkey
Where BalLoc.LetterType not in ('STBA','EXPA', 'FEE',' ') and
 BalLoc.LiabilityAmountBase > 0 and BalLoc.irdb = 1
;
quit;
</code>```

Thank you,

Shankar

答:
A few things I would suggest:

1, for each dataset that you reference, keep only the variables you need to join on, or which get used in the SELECT statement.  E.g., from your Party dset, it looks like you only need the Pkey field and Name.  Therefore when you make your join to that dset, you should use:

```<code>Left JOIN Party(keep=Pkey Name) PBene on PBene.Pkey = BalLoc.BenePkey
</code>```

2, Push your WHERE statement into the FROM statement like so:

```<code>FROM BalLocPrimary(where=(LetterType not in ('STBA','EXPA', 'FEE',' ') and
 LiabilityAmountBase > 0 and irdb = 1)) BalLoc
</code>```

And make sure the conditions are in the order of most common to least (barring any index that might be on those 3 fields)

3, You are driving off the BalLocPrimary dataset, left joining to everything else.  Is that what you really intend?  Is it OK that your result set comes back without a Client or Account_Number? Left Joins can be computationally expensive, and the more you can minimize them, the better.

4, Joe asked about indexes on the join fields.  You probably should have some.  I have found myself referencing this SUGI paper regularly enough to bookmark it.  Similarly, you could review the EXPLAIN PLAN from the query to see where it might be bottlenecking.  Another SUGI paper would be a good start.

5, You're right that this could (should?) be broken up into multiple steps.  That's a good intuition.  However the optimal breaks are going to be highly depending on the underlying data, index, and the join paths.  So it's hard to prescribe that from the other side of the screen.  I think that second paper I linked could give you some good tips on optimization for your specific case.

Body:
I got a code that uses a lot of left join with many tables. When I run this code, it takes more than an hour to run and at the end it gives error with Sort Execution Failure. So, I am thinking of breaking down that left join in multiple steps but I am not sure how to do it and need your help.

The code is as:

Proc sql;
create table newlib.Final_test as
SELECT
POpener.Name as Client,
Popener.PartyId as Account_Number,
Case
  When BalLoc.ConvertedRefNo NE '' then BalLoc.ConvertedRefNo
else BalLoc.Ourreferencenum
End as LC_Number,
BalLoc.OurReferenceNum ,
BalLoc.CnvLiabilityCode as Liability_Code,
POfficer.PartyID as Officer_Num,
POfficer.Name as Officer_Name,
POpener.ExpenseCode,
BalLoc.IssueDate as Issue_Date format=mmddyy10.,
BalLoc.ExpirationDate AS Expiry format=mmddyy10.,
BalLoc.LiabilityAmountBase as Total_LC_Balance,
Case
  When BalLoc.Syndicated = 0 Then BalLoc.LiabilityAmountBase
    else 0
End as SunTrust_Non_Syndicated_Exposure,
Case
  When BalLoc.Syndicated = 1 and BalLoc.PartOutGroupPkey NE 0 Then
BalLoc.LiabilityAmountBase
    else 0
  End as SunTrust_Syndicated_Exposure,
Case
  When BalLoc.Syndicated = 1 and BalLoc.PartOutGroupPkey NE 0 Then
(BalLoc.LiabilityAmountBase - (BalLoc.LiabilityAmountBase *
(PParty.ParticipationPercent/100)))
  Else BalLoc.LiabilityAmountBase
End as SunTrust_Exposure,
Case
  When BalLoc.Syndicated = 1 and BalLoc.PartOutGroupPkey <> 0 Then
(BalLoc.LiabilityAmountBase  * PParty.ParticipationPercent/100)
  Else 0
End as Exposure_Held_By_Other_Banks,
PBene.Name as Beneficiary_Trustee,
cat(put(input(POpener.ObligorNumber,best10.),z10.),put(input

   (BalLoc.CommitmentNumber,best10.),Z10.)) as Key,
case
when BalLoc.BeneCusip2 NE ' ' then catx
('|',Balloc.BeneCusip,Balloc.BeneCusip2)
else BalLoc.BeneCusip
End as Cusip,
Case
  when balLoc.OKtoExpire = 1 then '0'
  when balLOc.OKtoExpire=0 and BalLoc.AutoExtTermDays NE 0 then put
(Balloc.AutoExtTermDays,z3.)
  when balLoc.OKtoExpire=0 and BalLoc.AutoExtTermsMonth NE 0 then put
(balloc.AutoExtTermsMonth,z3.)
  else '000'
End as Evergreen
Case
when blf.AnnualRate NE 0 then put(blf.AnnualRate,z7.)
when blf.Amount NE 0 then cats('F',put(blf.amount,z7.))
else 'WAIVE'
End as Pricing,

FROM BalLocPrimary BalLoc
Left JOIN Party POpener on POpener.Pkey = BalLoc.OpenerPkey
Left join PartGroup PGroup on BallOC.PartOutGroupPkey = PGroup.pKey
Left join PartParties PParty ON PGroup.pKey = PParty.PartGroupPkey and
PParty.ParticipationPercent > 0 and
PParty.combined in
(select PPartParties.All_combined
from PPartParties /*group by PartGroupPkey, PartyPkey*/)

Left Join MemExpenseCodes ExpCodes on POpener.ExpenseCode = ExpCodes.Code
Left JOIN Party PBene on PBene.Pkey = BalLoc.BenePkey
Left join Party POfficer on POfficer.Pkey = BalLoc.AccountOfficerPkey
left join maxfee on maxfee.LocPrimaryPkey = BalLoc.LocPrimaryPkey
left join BalLocFee BLF on BLF.Pkey = maxfee.pkey
Where BalLoc.LetterType not in ('STBA','EXPA', 'FEE',' ') and
 BalLoc.LiabilityAmountBase > 0 and BalLoc.irdb = 1
;
quit;

Thank you,

Shankar

Body:
A few things I would suggest:

1, for each dataset that you reference, keep only the variables you need to join on, or which get used in the SELECT statement.  E.g., from your Party dset, it looks like you only need the Pkey field and Name.  Therefore when you make your join to that dset, you should use:

Left JOIN Party(keep=Pkey Name) PBene on PBene.Pkey = BalLoc.BenePkey

2, Push your WHERE statement into the FROM statement like so:

FROM BalLocPrimary(where=(LetterType not in ('STBA','EXPA', 'FEE',' ') and
 LiabilityAmountBase > 0 and irdb = 1)) BalLoc

And make sure the conditions are in the order of most common to least (barring any index that might be on those 3 fields)

3, You are driving off the BalLocPrimary dataset, left joining to everything else.  Is that what you really intend?  Is it OK that your result set comes back without a Client or Account_Number? Left Joins can be computationally expensive, and the more you can minimize them, the better.

4, Joe asked about indexes on the join fields.  You probably should have some.  I have found myself referencing this SUGI paper regularly enough to bookmark it.  Similarly, you could review the EXPLAIN PLAN from the query to see where it might be bottlenecking.  Another SUGI paper would be a good start.

5, You're right that this could (should?) be broken up into multiple steps.  That's a good intuition.  However the optimal breaks are going to be highly depending on the underlying data, index, and the join paths.  So it's hard to prescribe that from the other side of the screen.  I think that second paper I linked could give you some good tips on optimization for your specific case.


问:
String comparision not working when compared against an item(concatenated string) in C# ArrayList
Kindly explain what's going on with this below code (//DOESN'T WORK sections)
I know it will work if I rather use Equals() instead of == operator. But I am missing some understanding here. Thanks.

EDIT: My goal here is not to make it work, rather want to understand what's going on at compiler/runtime level in detail.

```<code>        string first = "string1";
        string full = first + " string2";

        Debug.Assert(full == "string1 string2", "Expected to be same.");//WORKS
        Debug.Assert(first + " string2" == "string1 string2", "Expected to be same.");//WORKS

        var list = new ArrayList();
        list.Add(full);
        list.Add(first + " string2");

        Debug.Assert(list[0] == "string1 string2", "Expected to be same.");//DOESN'T WORK
        Debug.Assert(list[1] == "string1 string2", "Expected to be same.");//DOESN'T WORK

        list.Add("string1 string2");
        Debug.Assert(list[2] == "string1 string2", "Expected to be same.");//WORKS
</code>```

答:
The problem is because the list is not generic, so you can´t compare an object with an string. It's better, something like this:

```<code>var list = new List<string>();
list.Add(full);
list.Add(first + " string2");

Debug.Assert(list.ElementAt(0) == "string1 string2", "Expected to be same.");
</code>```

You can use string[] as well.

Body:
Kindly explain what's going on with this below code (//DOESN'T WORK sections)
I know it will work if I rather use Equals() instead of == operator. But I am missing some understanding here. Thanks.

EDIT: My goal here is not to make it work, rather want to understand what's going on at compiler/runtime level in detail.

        string first = "string1";
        string full = first + " string2";

        Debug.Assert(full == "string1 string2", "Expected to be same.");//WORKS
        Debug.Assert(first + " string2" == "string1 string2", "Expected to be same.");//WORKS

        var list = new ArrayList();
        list.Add(full);
        list.Add(first + " string2");

        Debug.Assert(list[0] == "string1 string2", "Expected to be same.");//DOESN'T WORK
        Debug.Assert(list[1] == "string1 string2", "Expected to be same.");//DOESN'T WORK

        list.Add("string1 string2");
        Debug.Assert(list[2] == "string1 string2", "Expected to be same.");//WORKS

Body:
The problem is because the list is not generic, so you can´t compare an object with an string. It's better, something like this:

var list = new List<string>();
list.Add(full);
list.Add(first + " string2");

Debug.Assert(list.ElementAt(0) == "string1 string2", "Expected to be same.");

You can use string[] as well.


问:
Python GUI without 'video system'
I'm currently at a crossroads. I'm somewhat versed in Python (2.7) and would really like to start getting into GUI to give my (although mini) projects some more depth and versibility.

For the most part, my scripts don't use anything graphical so this is the first time I'm dipping my toes in this water.

That said, I've tried using pygame and tkinter but seem to fail at every turn to get something up and running (although I had some slight success with pygame)

Am I correct to understand that for both I need X started in order to generate any type of interface, and with that, so I need X to get any type of input (touchscreen presses)?

Thanks in advance!

答:
In order to use tkinter, you must have a graphics system running. For Windows and OSX that simply means you need to be logged in (ie: can't run as a service). For linux and other unix-like systems that means that you must have X running.

Neither tkinter nor any of the other common GUI toolkits will write directly to the screen.

Title: Python GUI without 'video system'


问:
New-StreamAnalyticsJob cannot create Operations Monitoring Input for an IOT Hub
We have a Stream Analytics job that has an Input mapping to an IOT Hub Operations Monitoring endpoint.  We originally defined our job on the Azure Portal.  It works fine when so created / updated.

We use the job logic in multiple "Azure environments" and are now keeping it in source control.  We used the Visual Studio Stream Analytics Project type to manage the source code.

We are using the New-StreamAnalyticsJob Powershell command to deploy our job into different environments.

Each time we deploy, however, the resulting Stream Analytics Job's Input points to the Messaging endpoint of our IOT Hub instead of the Operations Monitoring endpoint.

Is there something we can enter into the input's JSON file to express the endpoint type?  Here is the Input content of our JSON input to the cmdlet:

```<code>"Inputs": [{
                "Name": "IOT-Hub-Monitoring-By-Consumer-Group",
                "Properties": {
                    "DataSource": {
                        "Properties": {
                            "ConsumerGroupName": "theConsumerGroup",
                            "IotHubNamespace": "theIotNamespace",
                            "SharedAccessPolicyKey": null,
                            "SharedAccessPolicyName": "iothubowner"
                        },
                        "Type": "Microsoft.Devices/IotHubs"
                    },
                    "Serialization": {
                        "Properties": {
                            "Encoding": "UTF8",
                            "Format": "LineSeparated"
                        },
                        "Type": "Json"
                    },
                    "Type": "Stream"
                }
            },
            {
                "Name": "IOT-Hub-Messaging-By-Consumer-Group",
                "Properties": {
                    "DataSource": {
                        "Properties": {
                            "ConsumerGroupName": "anotherConsumerGroup",
                            "IotHubNamespace": "theIotNamespace",
                            "SharedAccessPolicyKey": null,
                            "SharedAccessPolicyName": "iothubowner"
                        },
                        "Type": "Microsoft.Devices/IotHubs"
                    },
                    "Serialization": {
                        "Properties": {
                            "Encoding": "UTF8",
                            "Format": "LineSeparated"
                        },
                        "Type": "Json"
                    },
                    "Type": "Stream"
                }
            }
        ]
</code>```

Is there an endpoint element within the IotHubProperties that we're not expressing?  Is it documented somewhere?

答:
I notice that the Azure Portal calls a different endpoint than is indicated here: https://learn.microsoft.com/en-us/rest/api/streamanalytics/stream-analytics-definition

It uses endpoints under https://main.streamanalytics.ext.azure.com/api.  e.g.
GET /api/Jobs/GetStreamingJob?subscriptionId={guid}&resourceGroupName=MyRG&jobName=MyJobName

You'll notice in the results JSON:

```<code>{
  "properties": {
    "inputs": {
      {
        "properties": {
          "datasource": {
            "inputIotHubSource": {
              "iotHubNamespace":"HeliosIOTHubDev",
              "sharedAccessPolicyName":"iothubowner",
              "sharedAccessPolicyKey":null,
         ---> "endpoint":"messages/events",  <---
              "consumerGroupName":"devicehealthmonitoring"
            }
</code>```

For operations monitoring you will see "endpoint":"messages/operationsMonitoringEvents"

They seem to implement Save for Inputs as PATCH /api/Inputs/PatchInput?... which takes a similarly constructed JSON with the same 2 values for endpoint.
Are you able to use that endpoint somehow?  i.e. call New-AzureRmStreamAnalyticsJob as you normally would then Invoke-WebRequest -Method Patch -Uri ...

--Edit--

The Invoke-WebRequest was a no-go -- far too much authentication to try to replicate/emulate.

A better option is to go through this tutorial to create a console application and set the endpoint after deploying using the Powershell scripts.

Something like this should work (albeit with absolutely no error/null checks):

```<code>string tenantId = "...";        //Tenant Id Guid
string subscriptionId = "...";  //Subcription Id Guid
string rgName = "...";          //Name of Resource Group
string jobName = "...";         //Name of Stream Analytics Job
string inputName = "...";       //Name-of-Input-requiring-operations-monitoring
string accesskey = "...";       //Shared Access Key for the IoT Hub

var login = new ServicePrincipalLoginInformation();
login.ClientId = "...";         //Client / Application Id for AD Service Principal (from tutorial)
login.ClientSecret = "...";     //Password for AD Service Principal (from tutorial)

var environment = new AzureEnvironment
{
    AuthenticationEndpoint = "https://login.windows.net/",
    GraphEndpoint = "https://graph.windows.net/",
    ManagementEnpoint = "https://management.core.windows.net/",
    ResourceManagerEndpoint = "https://management.azure.com/",
};
var credentials = new AzureCredentials(login, tenantId, environment)
    .WithDefaultSubscription(subscriptionId);

var azure = Azure
    .Configure()
    .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
    .Authenticate(credentials)
    .WithDefaultSubscription();

var client = new StreamAnalyticsManagementClient(credentials);
client.SubscriptionId = azure.SubscriptionId;

var job = client.StreamingJobs.List(expand: "inputs").Where(j => j.Name == jobName).FirstOrDefault();
var input = job.Inputs.Where(i => i.Name == inputName).FirstOrDefault();

var props = input.Properties as StreamInputProperties;
var ds = props.Datasource as IoTHubStreamInputDataSource;

ds.Endpoint = "messages/operationsMonitoringEvents";
ds.SharedAccessPolicyKey = accesskey;

client.Inputs.CreateOrReplace(input, rgName, jobName, inputName);
</code>```

Body:
We have a Stream Analytics job that has an Input mapping to an IOT Hub Operations Monitoring endpoint.  We originally defined our job on the Azure Portal.  It works fine when so created / updated.

We use the job logic in multiple "Azure environments" and are now keeping it in source control.  We used the Visual Studio Stream Analytics Project type to manage the source code.

We are using the New-StreamAnalyticsJob Powershell command to deploy our job into different environments.

Each time we deploy, however, the resulting Stream Analytics Job's Input points to the Messaging endpoint of our IOT Hub instead of the Operations Monitoring endpoint.

Is there something we can enter into the input's JSON file to express the endpoint type?  Here is the Input content of our JSON input to the cmdlet:

"Inputs": [{
                "Name": "IOT-Hub-Monitoring-By-Consumer-Group",
                "Properties": {
                    "DataSource": {
                        "Properties": {
                            "ConsumerGroupName": "theConsumerGroup",
                            "IotHubNamespace": "theIotNamespace",
                            "SharedAccessPolicyKey": null,
                            "SharedAccessPolicyName": "iothubowner"
                        },
                        "Type": "Microsoft.Devices/IotHubs"
                    },
                    "Serialization": {
                        "Properties": {
                            "Encoding": "UTF8",
                            "Format": "LineSeparated"
                        },
                        "Type": "Json"
                    },
                    "Type": "Stream"
                }
            },
            {
                "Name": "IOT-Hub-Messaging-By-Consumer-Group",
                "Properties": {
                    "DataSource": {
                        "Properties": {
                            "ConsumerGroupName": "anotherConsumerGroup",
                            "IotHubNamespace": "theIotNamespace",
                            "SharedAccessPolicyKey": null,
                            "SharedAccessPolicyName": "iothubowner"
                        },
                        "Type": "Microsoft.Devices/IotHubs"
                    },
                    "Serialization": {
                        "Properties": {
                            "Encoding": "UTF8",
                            "Format": "LineSeparated"
                        },
                        "Type": "Json"
                    },
                    "Type": "Stream"
                }
            }
        ]

Is there an endpoint element within the IotHubProperties that we're not expressing?  Is it documented somewhere?

Body:
I notice that the Azure Portal calls a different endpoint than is indicated here: https://learn.microsoft.com/en-us/rest/api/streamanalytics/stream-analytics-definition

It uses endpoints under https://main.streamanalytics.ext.azure.com/api.  e.g.
GET /api/Jobs/GetStreamingJob?subscriptionId={guid}&resourceGroupName=MyRG&jobName=MyJobName

You'll notice in the results JSON:

{
  "properties": {
    "inputs": {
      {
        "properties": {
          "datasource": {
            "inputIotHubSource": {
              "iotHubNamespace":"HeliosIOTHubDev",
              "sharedAccessPolicyName":"iothubowner",
              "sharedAccessPolicyKey":null,
         ---> "endpoint":"messages/events",  <---
              "consumerGroupName":"devicehealthmonitoring"
            }

For operations monitoring you will see "endpoint":"messages/operationsMonitoringEvents"

They seem to implement Save for Inputs as PATCH /api/Inputs/PatchInput?... which takes a similarly constructed JSON with the same 2 values for endpoint.
Are you able to use that endpoint somehow?  i.e. call New-AzureRmStreamAnalyticsJob as you normally would then Invoke-WebRequest -Method Patch -Uri ...

--Edit--

The Invoke-WebRequest was a no-go -- far too much authentication to try to replicate/emulate.

A better option is to go through this tutorial to create a console application and set the endpoint after deploying using the Powershell scripts.

Something like this should work (albeit with absolutely no error/null checks):

string tenantId = "...";        //Tenant Id Guid
string subscriptionId = "...";  //Subcription Id Guid
string rgName = "...";          //Name of Resource Group
string jobName = "...";         //Name of Stream Analytics Job
string inputName = "...";       //Name-of-Input-requiring-operations-monitoring
string accesskey = "...";       //Shared Access Key for the IoT Hub

var login = new ServicePrincipalLoginInformation();
login.ClientId = "...";         //Client / Application Id for AD Service Principal (from tutorial)
login.ClientSecret = "...";     //Password for AD Service Principal (from tutorial)

var environment = new AzureEnvironment
{
    AuthenticationEndpoint = "https://login.windows.net/",
    GraphEndpoint = "https://graph.windows.net/",
    ManagementEnpoint = "https://management.core.windows.net/",
    ResourceManagerEndpoint = "https://management.azure.com/",
};
var credentials = new AzureCredentials(login, tenantId, environment)
    .WithDefaultSubscription(subscriptionId);

var azure = Azure
    .Configure()
    .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
    .Authenticate(credentials)
    .WithDefaultSubscription();

var client = new StreamAnalyticsManagementClient(credentials);
client.SubscriptionId = azure.SubscriptionId;

var job = client.StreamingJobs.List(expand: "inputs").Where(j => j.Name == jobName).FirstOrDefault();
var input = job.Inputs.Where(i => i.Name == inputName).FirstOrDefault();

var props = input.Properties as StreamInputProperties;
var ds = props.Datasource as IoTHubStreamInputDataSource;

ds.Endpoint = "messages/operationsMonitoringEvents";
ds.SharedAccessPolicyKey = accesskey;

client.Inputs.CreateOrReplace(input, rgName, jobName, inputName);


问:
Multi module Maven project- modules can't see each other
I have a simple Maven project, looking like this
project view

There is a main pom.xml looking like this:

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>piche</artifactId>
    <name>PICHE project</name>
    <description>PICHE project</description>
    <groupId>com.pesho.piche</groupId>
    <version>1.0</version>
    <packaging>pom</packaging>

    <properties>
        <cucumber.jvm.version>1.2.5</cucumber.jvm.version>
        <project.version>1.0</project.version>
        <runner.folder>".."</runner.folder>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.pesho.piche</groupId>
            <artifactId>test</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>com.pesho.piche</groupId>
            <artifactId>core</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>${cucumber.jvm.version}</version>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>${cucumber.jvm.version}</version>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-guice</artifactId>
            <version>${cucumber.jvm.version}</version>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-core</artifactId>
            <version>${cucumber.jvm.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.inject</groupId>
            <artifactId>guice</artifactId>
            <version>3.0</version>
        </dependency>
        <dependency>
            <groupId>com.google.inject.extensions</groupId>
            <artifactId>guice-assistedinject</artifactId>
            <version>3.0</version>
        </dependency>
        <dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyaml</artifactId>
            <version>1.18</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>22.0</version>
        </dependency>
    </dependencies>
    </dependencyManagement>

    <modules>
        <module>core</module>
        <module>test</module>
    </modules>
</project>
</code>```

There are two modules- core and test.
core module pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>core</artifactId>
    <name>Core module</name>
    <description>Core Module</description>

    <parent>
        <groupId>com.pesho.piche</groupId>
        <artifactId>piche</artifactId>
        <version>1.0</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <url>http://maven.apache.org</url>

    <dependencies>
        <dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyaml</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>22.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.google.inject</groupId>
            <artifactId>guice</artifactId>
            <version>3.0</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>
</code>```

test module pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>test</artifactId>
    <name>Test module</name>

    <url>http://maven.apache.org</url>

    <parent>
        <artifactId>piche</artifactId>
        <groupId>com.pesho.piche</groupId>
        <version>1.0</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <dependencies>
        <dependency>
            <groupId>com.pesho.piche</groupId>
            <artifactId>core</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-java</artifactId>
    </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-junit</artifactId>
    </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-guice</artifactId>
    </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-core</artifactId>
    </dependency>
        <dependency>
            <groupId>com.google.inject</groupId>
            <artifactId>guice</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.inject.extensions</groupId>
            <artifactId>guice-assistedinject</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
        </dependency>
    </dependencies>

</project>
</code>```

I want to use code from core inside test. The dependency looks right. The project is build with no errors:

```<code>[INFO] Reactor Summary:
[INFO]
[INFO] PICHE project ..................................... SUCCESS [0.317s]
[INFO] Core module ....................................... SUCCESS [1.317s]
[INFO] Test module ....................................... SUCCESS [0.669s]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.461s
[INFO] Finished at: Fri Jun 23 11:03:18 EEST 2017
[INFO] Final Memory: 17M/41M
[INFO] ------------------------------------------------------------------------
</code>```

But when I try to import a class from core in my tests, the class cannot be found.

答: Thank you for all your answers. I noted the suggestions. The problem was that I was using default packages in the modules. Never do that! Dependencies were OK but I couldn't see them because of the classpath options.</p>

Body:
I have a simple Maven project, looking like this
project view

There is a main pom.xml looking like this:

    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>piche</artifactId>
    <name>PICHE project</name>
    <description>PICHE project</description>
    <groupId>com.pesho.piche</groupId>
    <version>1.0</version>
    <packaging>pom</packaging>

    <properties>
        <cucumber.jvm.version>1.2.5</cucumber.jvm.version>
        <project.version>1.0</project.version>
        <runner.folder>".."</runner.folder>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.pesho.piche</groupId>
            <artifactId>test</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>com.pesho.piche</groupId>
            <artifactId>core</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>${cucumber.jvm.version}</version>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>${cucumber.jvm.version}</version>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-guice</artifactId>
            <version>${cucumber.jvm.version}</version>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-core</artifactId>
            <version>${cucumber.jvm.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.inject</groupId>
            <artifactId>guice</artifactId>
            <version>3.0</version>
        </dependency>
        <dependency>
            <groupId>com.google.inject.extensions</groupId>
            <artifactId>guice-assistedinject</artifactId>
            <version>3.0</version>
        </dependency>
        <dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyaml</artifactId>
            <version>1.18</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>22.0</version>
        </dependency>
    </dependencies>
    </dependencyManagement>

    <modules>
        <module>core</module>
        <module>test</module>
    </modules>
</project>

There are two modules- core and test.
core module pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>core</artifactId>
    <name>Core module</name>
    <description>Core Module</description>

    <parent>
        <groupId>com.pesho.piche</groupId>
        <artifactId>piche</artifactId>
        <version>1.0</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <url>http://maven.apache.org</url>

    <dependencies>
        <dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyaml</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>22.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.google.inject</groupId>
            <artifactId>guice</artifactId>
            <version>3.0</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

test module pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>test</artifactId>
    <name>Test module</name>

    <url>http://maven.apache.org</url>

    <parent>
        <artifactId>piche</artifactId>
        <groupId>com.pesho.piche</groupId>
        <version>1.0</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <dependencies>
        <dependency>
            <groupId>com.pesho.piche</groupId>
            <artifactId>core</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-java</artifactId>
    </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-junit</artifactId>
    </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-guice</artifactId>
    </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-core</artifactId>
    </dependency>
        <dependency>
            <groupId>com.google.inject</groupId>
            <artifactId>guice</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.inject.extensions</groupId>
            <artifactId>guice-assistedinject</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
        </dependency>
    </dependencies>

</project>

I want to use code from core inside test. The dependency looks right. The project is build with no errors:

[INFO] Reactor Summary:
[INFO]
[INFO] PICHE project ..................................... SUCCESS [0.317s]
[INFO] Core module ....................................... SUCCESS [1.317s]
[INFO] Test module ....................................... SUCCESS [0.669s]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.461s
[INFO] Finished at: Fri Jun 23 11:03:18 EEST 2017
[INFO] Final Memory: 17M/41M
[INFO] ------------------------------------------------------------------------

But when I try to import a class from core in my tests, the class cannot be found.


问:
How to load a component with flags multiple times in the same page in Elm?
Is there a way to build components for a page with Elm and to compile two components in the same Elm file as well as loading twice the same component with the same code?

Do you know how I could do that?

答:
elm-make let you select multiple files that you want to compile together.

```<code>elm-make Header.elm Footer.elm Button.elm --output=app.js
</code>```

Header.elm

```<code>port module Header exposing (..)

import Html

main =
    Html.div [] [ Html.text "Header" ]
</code>```

Footer.elm

```<code>port module Footer exposing (..)

import Html

main =
    Html.div [] [ Html.text "Footer" ]
</code>```

Button.elm

```<code>port module Button exposing (..)

import Html

main =
    Html.div [] [ Html.button [] [ Html.text "Button" ] ]
</code>```

index.html

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Elm Demo</title>
  </head>

  <body>
    <div id="header"></div>
    <div id="button"></div>
    <div id="button2"></div>
    <div id="footer"></div>
  </body>
  <script src="app.js"></script>
  <script>
      let header = Elm.Header.embed(document.getElementById("header"));
      let footer = Elm.Footer.embed(document.getElementById("footer"));
      let button = Elm.Button.embed(document.getElementById("button"));
      let button2 = Elm.Button.embed(document.getElementById("button2"));
  </script>
</html>
</code>```

Body:
elm-make let you select multiple files that you want to compile together.

elm-make Header.elm Footer.elm Button.elm --output=app.js

Header.elm

port module Header exposing (..)

import Html

main =
    Html.div [] [ Html.text "Header" ]

Footer.elm

port module Footer exposing (..)

import Html

main =
    Html.div [] [ Html.text "Footer" ]

Button.elm

port module Button exposing (..)

import Html

main =
    Html.div [] [ Html.button [] [ Html.text "Button" ] ]

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Elm Demo</title>
  </head>

  <body>
    <div id="header"></div>
    <div id="button"></div>
    <div id="button2"></div>
    <div id="footer"></div>
  </body>
  <script src="app.js"></script>
  <script>
      let header = Elm.Header.embed(document.getElementById("header"));
      let footer = Elm.Footer.embed(document.getElementById("footer"));
      let button = Elm.Button.embed(document.getElementById("button"));
      let button2 = Elm.Button.embed(document.getElementById("button2"));
  </script>
</html>


问:
How to get returned div's offset/position in react?
In my code return i have:

```<code>return (
  <div  className="pos__container" >
  <div  className="pos__container--line" ></div>
    {timeList}
  </div>
);
</code>```

 has margin-left:10%; other styles are irrelevant.

In the function under constructor I want to get its position.

To get the offset i need to get a div first.

I have tried:
const element = ReactDOM.findDOMNode(this); which returns
findDOMNode was called on an unmounted component.

Also tried using document.QuerySelector(".pos__container--line"); which returns null

Feel like I'm out of the options.

Any suggestions how I could do this right or any other ways to do it ?

Any help would be appreciated.

Thanks in advance!

答:
You need to use the lifecycle method of React which is invoked when the component has mounted.</p>

```<code>componentDidMount(){
  var node = ReactDOM.findDOMNode(this);
  console.log(window.getComputedStyle(node).offset);
}
</code>```

Body:
In my code return i have:

return (

    {timeList}

);

 has margin-left:10%; other styles are irrelevant.

In the function under constructor I want to get its position.

To get the offset i need to get a div first.

I have tried:
const element = ReactDOM.findDOMNode(this); which returns
findDOMNode was called on an unmounted component.

Also tried using document.QuerySelector(".pos__container--line"); which returns null

Feel like I'm out of the options.

Any suggestions how I could do this right or any other ways to do it ?

Any help would be appreciated.

Thanks in advance!

Body:
You need to use the lifecycle method of React which is invoked when the component has mounted.

componentDidMount(){
  var node = ReactDOM.findDOMNode(this);
  console.log(window.getComputedStyle(node).offset);
}


问:
Efficient VBA code for conditionally deleting rows in big excel sheet
My excel sheet has 40 columns and more than 1,00,000 rows. I want to delete all the rows which contain cell with a string "NA" in any of the columns. I am struggling to find an efficient VB code for this, which doesn't cause excel to crash.
My current VBA code (explained below) takes forever to run (>5 mins on Intel Xenon and 16 GB RAM) and crashes on slower machines (i5, 4 GB RAM). Any suggestions to streamline and make it faster?

P.S. Exact number of rows and columns are not known apriori. And, I'm new to VBA, any help would be greatly appreciated.

Link to the concerned file - https://drive.google.com/file/d/0Bzl56SYDK-iRdTE1LTlYZGsxSE0/view?usp=sharing

My VBA code:

```<code>Sub DeleteRowWithContents()

'Finds the last non-blank cell on a sheet/range.

Dim lRow As Long
Dim lCol As Long

    lRow = Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row

    lCol = Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByColumns, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Column

        'MsgBox "Last Row: " & lRow
        'MsgBox "Last Column: " & lCol

     For j = lCol To 1 Step -1
     For i = lRow To 1 Step -1
        If (Cells(i, j).Value) = "NA" Then
            Cells(i, "A").EntireRow.Delete
        End If
    Next i
    lRow = Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row
    Next j

End Sub
</code>```

答:
The fastest solution to this is as follows: (Source)

as this is a CSV file, parsing as text at the command line is likely the most efficient way;

if you're on a Unix machine (Linux or OS X) then you can use SED (stream editor) from the terminal. this processes the changes in under a second!

sed '/NA/d' ahs-comb-madhya_pradesh-dhar.csv > ahs-comb-madhya_pradesh-dhar_CLEAN.csv

I believe you could use PowerShell on Windows to do something similar, the below command appears to work, although takes about 7 seconds

Get-Content .\ahs-comb-madhya_pradesh-dhar.csv | Where-Object {$_ -CNotMatch 'NA'} | Set-Content ahs-comb-madhya_pradesh-dhar_CLEAN.csv

Body:
My excel sheet has 40 columns and more than 1,00,000 rows. I want to delete all the rows which contain cell with a string "NA" in any of the columns. I am struggling to find an efficient VB code for this, which doesn't cause excel to crash.
My current VBA code (explained below) takes forever to run (>5 mins on Intel Xenon and 16 GB RAM) and crashes on slower machines (i5, 4 GB RAM). Any suggestions to streamline and make it faster?

P.S. Exact number of rows and columns are not known apriori. And, I'm new to VBA, any help would be greatly appreciated.

Link to the concerned file - https://drive.google.com/file/d/0Bzl56SYDK-iRdTE1LTlYZGsxSE0/view?usp=sharing

My VBA code:

Sub DeleteRowWithContents()

'Finds the last non-blank cell on a sheet/range.

Dim lRow As Long
Dim lCol As Long

    lRow = Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row

    lCol = Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByColumns, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Column

        'MsgBox "Last Row: " & lRow
        'MsgBox "Last Column: " & lCol

     For j = lCol To 1 Step -1
     For i = lRow To 1 Step -1
        If (Cells(i, j).Value) = "NA" Then
            Cells(i, "A").EntireRow.Delete
        End If
    Next i
    lRow = Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row
    Next j

End Sub


问:
Model Binding for multipart/form-data (File + JSON) post in ASP.NET Core 1.1
I'm attempting to build an ASP.NET Core 1.1 Controller method to handle an HTTP Request that looks like the following:

```<code>POST https://localhost/api/data/upload HTTP/1.1
Content-Type: multipart/form-data; boundary=--------------------------625450203542273177701444
Host: localhost
Content-Length: 474

----------------------------625450203542273177701444
Content-Disposition: form-data; name="file"; filename="myfile.txt"
Content-Type: text/plain

<< Contents of my file >>

----------------------------625450203542273177701444
Content-Disposition: form-data; name="text"
Content-Type: application/json

{"md5":"595f44fec1e92a71d3e9e77456ba80d0","sessionIds":["123","abc"]}
----------------------------625450203542273177701444--
</code>```

It's a multipart/form-data request with one part being a (small) file and the other part a json blob that is based on a provided specification.

Ideally, I'd love my controller method to look like:

[HttpPost]
public async Task Post(UploadPayload payload)
{
   // TODO
}

public class UploadPayload
{
    public IFormFile File { get; set; }

    [Required]
    [StringLength(32)]
    public string Md5 { get; set; }

    public List<string> SessionIds { get; set; }
}
```

<p>But alas, that doesn't Just Work {TM}.  When I have it like this, the <code>IFormFile</code> <em>does</em> get populated, but the json string doesn't get deserialized to the other properties.</p>

<p>I've also tried adding a <code>Text</code> property to <code>UploadPayload</code> that has all the properties other than the <code>IFormFile</code> and that also doesn't receive the data.  E.g.</p>

<pre class="lang-csharp prettyprint-override"><code>public class UploadPayload
{
    public IFormFile File { get; set; }

    public UploadPayloadMetadata Text { get; set; }
}

public class UploadPayloadMetadata
{
    [Required]
    [StringLength(32)]
    public string Md5 { get; set; }

    public List<string> SessionIds { get; set; }
}
</code>```

A workaround that I have is to avoid model binding and use MultipartReader along the lines of:

[HttpPost]
public async Task Post()
{
   ...

   var reader = new MultipartReader(Request.GetMultipartBoundary(), HttpContext.Request.Body);

   var section = await reader.ReadNextSectionAsync();
   var filePart = section.AsFileSection();

   // Do stuff & things with the file

   section = await reader.ReadNextSectionAsync();
   var jsonPart = section.AsFormDataSection();
   var jsonString = await jsonPart.GetValueAsync();

   // Use $JsonLibrary to manually deserailize into the model
   // Do stuff & things with the metadata

   ...
}
```

Doing the above bypasses model validation features, etc.  Also, I thought maybe I could take that jsonString and then somehow get it into a state that I could then call await TryUpdateModelAsync(payloadModel, ...) but couldn't figure out how to get there either - and that didn't seem all that clean either.

Is it possible to get to my desired state of "transparent" model binding like my first attempt?  If so, how would one get to that?

答:
I'm not 100% clear on how this would work for ASP.NET Core but for Web API (so I assume a similar path exists here) you'd want to go down the road of a Media Formatter. Here's an example (fairly similar to your question) Github Sample with blog post

Custom formatters might be the ticket? https://learn.microsoft.com/en-us/aspnet/core/mvc/advanced/custom-formatters

Body:
I'm attempting to build an ASP.NET Core 1.1 Controller method to handle an HTTP Request that looks like the following:

POST https://localhost/api/data/upload HTTP/1.1
Content-Type: multipart/form-data; boundary=--------------------------625450203542273177701444
Host: localhost
Content-Length: 474

----------------------------625450203542273177701444
Content-Disposition: form-data; name="file"; filename="myfile.txt"
Content-Type: text/plain

<< Contents of my file >>

----------------------------625450203542273177701444
Content-Disposition: form-data; name="text"
Content-Type: application/json

{"md5":"595f44fec1e92a71d3e9e77456ba80d0","sessionIds":["123","abc"]}
----------------------------625450203542273177701444--

It's a multipart/form-data request with one part being a (small) file and the other part a json blob that is based on a provided specification.

Ideally, I'd love my controller method to look like:

[HttpPost]
public async Task Post(UploadPayload payload)
{
   // TODO
}

public class UploadPayload
{
    public IFormFile File { get; set; }

    [Required]
    [StringLength(32)]
    public string Md5 { get; set; }

    public List<string> SessionIds { get; set; }
}

But alas, that doesn't Just Work {TM}.  When I have it like this, the IFormFile does get populated, but the json string doesn't get deserialized to the other properties.

I've also tried adding a Text property to UploadPayload that has all the properties other than the IFormFile and that also doesn't receive the data.  E.g.

public class UploadPayload
{
    public IFormFile File { get; set; }

    public UploadPayloadMetadata Text { get; set; }
}

public class UploadPayloadMetadata
{
    [Required]
    [StringLength(32)]
    public string Md5 { get; set; }

    public List<string> SessionIds { get; set; }
}

A workaround that I have is to avoid model binding and use MultipartReader along the lines of:

[HttpPost]
public async Task Post()
{
   ...

   var reader = new MultipartReader(Request.GetMultipartBoundary(), HttpContext.Request.Body);

   var section = await reader.ReadNextSectionAsync();
   var filePart = section.AsFileSection();

   // Do stuff & things with the file

   section = await reader.ReadNextSectionAsync();
   var jsonPart = section.AsFormDataSection();
   var jsonString = await jsonPart.GetValueAsync();

   // Use $JsonLibrary to manually deserailize into the model
   // Do stuff & things with the metadata

   ...
}

Doing the above bypasses model validation features, etc.  Also, I thought maybe I could take that jsonString and then somehow get it into a state that I could then call await TryUpdateModelAsync(payloadModel, ...) but couldn't figure out how to get there either - and that didn't seem all that clean either.

Is it possible to get to my desired state of "transparent" model binding like my first attempt?  If so, how would one get to that?


问:
VBA, Parse by "|" and Transpose, Next row
I have the following data in a cells A1

```<code>|stack|over|flow|
</code>```

and cells A2..

```<code>|today|is|friday
</code>```

How can I delimit this and transpose it into a vertical/column based view view?

Delimiting will give me data row based, which is good but that I have to transpose this manually each time. I plan to do this for many rows. I realized this could be tricky as the next row will need to be pushed back down for each time.

Result A1:A6:

```<code>Stack

Over

flow

today

is

friday
</code>```

Edit

答:
For unlimited rows and unlimited columns:

```<code>Sub splt()
Dim str As String
Dim col As Long, rw As Long, colcnt As Long, rwcnt As Long
With Sheets("Sheet1")
    colcnt = .Cells(1, .Columns.Count).End(xlToLeft).Column 'total no of columns
    For col = 1 To colcnt
        rwcnt = .Cells(.Rows.Count, col).End(xlUp).Row 'total no of rows for specific column
        For rw = 1 To rwcnt
            str = str & .Cells(rw, col)
        Next rw

        rw = 1
        For Each Item In Split(str, "|") 'split string and display output
            If Item <> "" Then
                .Cells(rw, col) = Item
                rw = rw + 1
            End If
        Next
        str = ""
    Next
End With
End Sub
</code>```

Edit:
You can use an array for this, but the following method is less complicated to easy to write and read:

```<code>Sub splt()
Dim rw As Long, i As Long, rwcnt As Long
i = 1
With Sheets("Sheet1")
    rwcnt = .Cells(.Rows.Count, 2).End(xlUp).Row 'last non-empty row number
    For rw = 1 To rwcnt 'from row 1 till last non-empty row
        For Each Item In Split(.Cells(rw, 2), "|") 'split the string in column 2 from "|"
            If Item <> "" Then ' 'if the splitted part of the string is not empty
                .Cells(i, 4) = .Cells(rw, 1) 'populate column 4 with column 1
                .Cells(i, 5) = Item 'populate column 5 with splitted part of the string
                .Cells(i, 6) = .Cells(rw, 3) 'populate column 6 with column 3
                i = i + 1 ' increase i variable by one to be able to write the next empty row for the next loop
            End If
        Next 'loop to next splitted string
    Next rw 'loop to next row
    .Columns("A:C").EntireColumn.Delete 'when all data is extracted to Columns D-E-F, delete Columns A-B-C and your results will be in Column A-B-C now
End With
End Sub
</code>```

Body:
I have the following data in a cells A1

|stack|over|flow|

and cells A2..

|today|is|friday

How can I delimit this and transpose it into a vertical/column based view view?

Delimiting will give me data row based, which is good but that I have to transpose this manually each time. I plan to do this for many rows. I realized this could be tricky as the next row will need to be pushed back down for each time.

Result A1:A6:

Stack

Over

flow

today

is

friday

Edit

Body:
For unlimited rows and unlimited columns:

Sub splt()
Dim str As String
Dim col As Long, rw As Long, colcnt As Long, rwcnt As Long
With Sheets("Sheet1")
    colcnt = .Cells(1, .Columns.Count).End(xlToLeft).Column 'total no of columns
    For col = 1 To colcnt
        rwcnt = .Cells(.Rows.Count, col).End(xlUp).Row 'total no of rows for specific column
        For rw = 1 To rwcnt
            str = str & .Cells(rw, col)
        Next rw

        rw = 1
        For Each Item In Split(str, "|") 'split string and display output
            If Item <> "" Then
                .Cells(rw, col) = Item
                rw = rw + 1
            End If
        Next
        str = ""
    Next
End With
End Sub

Edit:
You can use an array for this, but the following method is less complicated to easy to write and read:

Sub splt()
Dim rw As Long, i As Long, rwcnt As Long
i = 1
With Sheets("Sheet1")
    rwcnt = .Cells(.Rows.Count, 2).End(xlUp).Row 'last non-empty row number
    For rw = 1 To rwcnt 'from row 1 till last non-empty row
        For Each Item In Split(.Cells(rw, 2), "|") 'split the string in column 2 from "|"
            If Item <> "" Then ' 'if the splitted part of the string is not empty
                .Cells(i, 4) = .Cells(rw, 1) 'populate column 4 with column 1
                .Cells(i, 5) = Item 'populate column 5 with splitted part of the string
                .Cells(i, 6) = .Cells(rw, 3) 'populate column 6 with column 3
                i = i + 1 ' increase i variable by one to be able to write the next empty row for the next loop
            End If
        Next 'loop to next splitted string
    Next rw 'loop to next row
    .Columns("A:C").EntireColumn.Delete 'when all data is extracted to Columns D-E-F, delete Columns A-B-C and your results will be in Column A-B-C now
End With
End Sub


答:
You could union all all three tables and sum the results:

```<code>SELECT   `date`, SUM(cnt), SUM(click), SUM(point)
FROM     (SELECT `date`, cnt, click, point FROM a
          UNION ALL
          SELECT `date`, cnt, click, point FROM b
          UNION ALL
          SELECT `date`, cnt, click, point FROM c) t
GROUP BY `date`
</code>```

Title: Separate table sum join

Body:
I have following tables with some ddata as described below

Table A

------------------------------------
      date    |  cnt  |  click  |  point
------------------------------------
2014-07-01 |  3    |    5    |    10

2014-07-03 |  5    |    15    |    20

2014-07-05 |  1    |    2    |    3

Table B

------------------------------------
      date    |  cnt  |  click  |  point
------------------------------------
2014-07-02 |  3    |    5    |    10

2014-07-03 |  3    |    5    |    20

2014-07-06 |  1    |    2    |    3

Table C

------------------------------------
      date    |  cnt  |  click  |  point
------------------------------------
2014-07-01 |  3    |    5    |    10

2014-07-02 |  2    |    3    |    30

2014-07-05 |  1    |    2    |    3

result

------------------------------------
      date    |  cnt  |  click  |  point
------------------------------------
2014-07-01 |  6    |    10    |    20

2014-07-02 |  5    |    8      |    40

2014-07-03 |  8    |    20    |    40

2014-07-05 |  2    |    4    |    6

2014-07-06 |  1    |    2    |    3

Above Join result but not union all.
Any suggestion please?

Body:
You could union all all three tables and sum the results:

SELECT   `date`, SUM(cnt), SUM(click), SUM(point)
FROM     (SELECT `date`, cnt, click, point FROM a
          UNION ALL
          SELECT `date`, cnt, click, point FROM b
          UNION ALL
          SELECT `date`, cnt, click, point FROM c) t
GROUP BY `date`