问:
What is a "node project"?
What is a "NodeJs project"? How would you describe a node project to a person that is moving to learn nodeJs? Or, at a job interview, for example, if someone  asked you this question, how would you reply? How would you describe a "node project"?</p>

答:
A node project is any program that is built to run on the node.js Javascript engine and use its built-in runtime library.  It could be a simple one file script to carry out some sort of local scripting operation or it could be whole directory hierarchy of script files and installed modules designed to be a clustered server running a website at scale or anything in between.

node.js itself is a very flexible development environment that can be used to create a wide variety of programs.  It's somewhat analogous to Python (though obviously a different language) in that it comes with a language interpreter, a runtime library of built-in functionality and a community of modules (most of which are open source) that you can add in to your project.

If you're hoping to seem node.js-proficient in an interview and don't even know the answer to this already, then you have a lot of additional studying to do because a few simple followup questions about the relevant strengths of node.js compared to other environments or a few quick programming questions about the node.js environment would likely quickly show the limitations of your knowledge.

Title: What is a "node project"?


来源: stackexchange

问:
Android Search Highlight Full Word
String fullText = "Our Honorable Prime Minister";

String searchText = "onor";

I can highlight "onor" text well. [by using bottom codes]

But I want to highlight full "Honorable" text when my search string is "onor".

My code is:

```<code>public static void setSearchText(TextView textView, String fullText, String searchText) {
    // highlight search text
    if (null != searchText && !searchText.isEmpty()) {
        int startPos = fullText.indexOf(searchText);
        int endPos = startPos + searchText.length();
        if (startPos != -1) {

            int ofe = fullText.indexOf(searchText, 0);
            Spannable WordtoSpan = new SpannableString(fullText);

            for (int ofs = 0; ofs < fullText.length() && ofe != -1; ofs = ofe + 1) {
                ofe = fullText.indexOf(searchText, ofs);
                if (ofe == -1)
                    break;
                else {
                    ColorStateList redColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{Color.RED});
                    TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, redColor, null);
                    WordtoSpan.setSpan(highlightSpan, ofe, ofe + searchText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    WordtoSpan.setSpan(new BackgroundColorSpan(0xFFFFFF00), ofe, ofe + searchText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    WordtoSpan.setSpan(new RelativeSizeSpan(1.5f), ofe, ofe + searchText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    textView.setText(WordtoSpan, TextView.BufferType.SPANNABLE);
                }
            }
        } else {
            textView.setText(fullText);
        }

    } else {
        textView.setText(fullText);
    }
}
</code>```

答:
Once you've found a match for your search string in the full text, you need to expand that match outwards to the word boundaries (spaces).

This is one way to do it:

// For single Item search

```<code>private static void setSearchText(TextView textView, final String fullText, final String searchText) {
  // highlight search text
  if (null != searchText && !searchText.isEmpty()) {
    int startPos = fullText.indexOf(searchText);
    int endPos = startPos + searchText.length();

    if (startPos != -1) {
      // Found a match to the partial text -- now search outward to
      // the word boundaries
      final char WORD_BOUNDARY = ' ';
      final char WORD_BOUNDARY1 = '\n';

      int wordStart = startPos;
                    while (wordStart >= 0 && fullText.charAt(wordStart) != WORD_BOUNDARY && fullText.charAt(wordStart) != WORD_BOUNDARY1) {
                        --wordStart;
                    }
                    wordStart = wordStart + 1;

                    int wordEnd = endPos;
                    while (wordEnd < fullText.length() && fullText.charAt(wordEnd) != WORD_BOUNDARY && fullText.charAt(wordEnd) != WORD_BOUNDARY1) {
                        ++wordEnd;
                    }

      // Now highlight based on the word boundaries
      ColorStateList redColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{Color.RED});
      TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, redColor, null);

      Spannable wordtoSpan = new SpannableString(fullText);

      wordtoSpan.setSpan(highlightSpan, wordStart, wordEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
      wordtoSpan.setSpan(new BackgroundColorSpan(0xFFFFFF00), wordStart, wordEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
      wordtoSpan.setSpan(new RelativeSizeSpan(1.5f), wordStart, wordEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

      textView.setText(wordtoSpan, TextView.BufferType.SPANNABLE);
    } else {
      textView.setText(fullText);
    }
  } else {
    textView.setText(fullText);
  }
}
</code>```

// For Multiple String Search Use following Codes:

```<code>public static void setSearchText(TextView textView, final String fullText, final String searchText) {
    // highlight search text
    if (null != searchText && !searchText.isEmpty()) {
        int startPos = fullText.indexOf(searchText, 0);
        int endPos = startPos + searchText.length();

        if (startPos != -1) {
            // Found a match to the partial text -- now search outward to
            // the word boundaries

            Spannable wordtoSpan = new SpannableString(fullText);

            for (int i = 0; i < fullText.length() && startPos != -1; i = startPos + 1) {
                startPos = fullText.indexOf(searchText, i);
                endPos = startPos + searchText.length();
                if (startPos == -1)
                    break;
                else {
                    final char WORD_BOUNDARY = ' ';
                    final char WORD_BOUNDARY1 = '\n';

                    int wordStart = startPos;
                    while (wordStart >= 0 && fullText.charAt(wordStart) != WORD_BOUNDARY && fullText.charAt(wordStart) != WORD_BOUNDARY1) {
                        --wordStart;
                    }
                    wordStart = wordStart + 1;

                    int wordEnd = endPos;
                    while (wordEnd < fullText.length() && fullText.charAt(wordEnd) != WORD_BOUNDARY && fullText.charAt(wordEnd) != WORD_BOUNDARY1) {
                        ++wordEnd;
                    }

                    // Now highlight based on the word boundaries
                    ColorStateList redColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{Color.RED});
                    TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, redColor, null);

                    wordtoSpan.setSpan(highlightSpan, wordStart, wordEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    wordtoSpan.setSpan(new BackgroundColorSpan(0xFFFFFF00), wordStart, wordEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    wordtoSpan.setSpan(new RelativeSizeSpan(1.5f), wordStart, wordEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                    textView.setText(wordtoSpan, TextView.BufferType.SPANNABLE);

                }
            }
        } else {
            textView.setText(fullText);
        }
    } else {
        textView.setText(fullText);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Android Search Highlight Full Word

Body:
String fullText = "Our Honorable Prime Minister";

String searchText = "onor";

I can highlight "onor" text well. [by using bottom codes]

But I want to highlight full "Honorable" text when my search string is "onor".

My code is:

public static void setSearchText(TextView textView, String fullText, String searchText) {
    // highlight search text
    if (null != searchText && !searchText.isEmpty()) {
        int startPos = fullText.indexOf(searchText);
        int endPos = startPos + searchText.length();
        if (startPos != -1) {

            int ofe = fullText.indexOf(searchText, 0);
            Spannable WordtoSpan = new SpannableString(fullText);

            for (int ofs = 0; ofs < fullText.length() && ofe != -1; ofs = ofe + 1) {
                ofe = fullText.indexOf(searchText, ofs);
                if (ofe == -1)
                    break;
                else {
                    ColorStateList redColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{Color.RED});
                    TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, redColor, null);
                    WordtoSpan.setSpan(highlightSpan, ofe, ofe + searchText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    WordtoSpan.setSpan(new BackgroundColorSpan(0xFFFFFF00), ofe, ofe + searchText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    WordtoSpan.setSpan(new RelativeSizeSpan(1.5f), ofe, ofe + searchText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    textView.setText(WordtoSpan, TextView.BufferType.SPANNABLE);
                }
            }
        } else {
            textView.setText(fullText);
        }

    } else {
        textView.setText(fullText);
    }
}

Body:
Once you've found a match for your search string in the full text, you need to expand that match outwards to the word boundaries (spaces).

This is one way to do it:

// For single Item search

private static void setSearchText(TextView textView, final String fullText, final String searchText) {
  // highlight search text
  if (null != searchText && !searchText.isEmpty()) {
    int startPos = fullText.indexOf(searchText);
    int endPos = startPos + searchText.length();

    if (startPos != -1) {
      // Found a match to the partial text -- now search outward to
      // the word boundaries
      final char WORD_BOUNDARY = ' ';
      final char WORD_BOUNDARY1 = '\n';

      int wordStart = startPos;
                    while (wordStart >= 0 && fullText.charAt(wordStart) != WORD_BOUNDARY && fullText.charAt(wordStart) != WORD_BOUNDARY1) {
                        --wordStart;
                    }
                    wordStart = wordStart + 1;

                    int wordEnd = endPos;
                    while (wordEnd < fullText.length() && fullText.charAt(wordEnd) != WORD_BOUNDARY && fullText.charAt(wordEnd) != WORD_BOUNDARY1) {
                        ++wordEnd;
                    }

      // Now highlight based on the word boundaries
      ColorStateList redColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{Color.RED});
      TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, redColor, null);

      Spannable wordtoSpan = new SpannableString(fullText);

      wordtoSpan.setSpan(highlightSpan, wordStart, wordEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
      wordtoSpan.setSpan(new BackgroundColorSpan(0xFFFFFF00), wordStart, wordEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
      wordtoSpan.setSpan(new RelativeSizeSpan(1.5f), wordStart, wordEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

      textView.setText(wordtoSpan, TextView.BufferType.SPANNABLE);
    } else {
      textView.setText(fullText);
    }
  } else {
    textView.setText(fullText);
  }
}

// For Multiple String Search Use following Codes:

public static void setSearchText(TextView textView, final String fullText, final String searchText) {
    // highlight search text
    if (null != searchText && !searchText.isEmpty()) {
        int startPos = fullText.indexOf(searchText, 0);
        int endPos = startPos + searchText.length();

        if (startPos != -1) {
            // Found a match to the partial text -- now search outward to
            // the word boundaries

            Spannable wordtoSpan = new SpannableString(fullText);

            for (int i = 0; i < fullText.length() && startPos != -1; i = startPos + 1) {
                startPos = fullText.indexOf(searchText, i);
                endPos = startPos + searchText.length();
                if (startPos == -1)
                    break;
                else {
                    final char WORD_BOUNDARY = ' ';
                    final char WORD_BOUNDARY1 = '\n';

                    int wordStart = startPos;
                    while (wordStart >= 0 && fullText.charAt(wordStart) != WORD_BOUNDARY && fullText.charAt(wordStart) != WORD_BOUNDARY1) {
                        --wordStart;
                    }
                    wordStart = wordStart + 1;

                    int wordEnd = endPos;
                    while (wordEnd < fullText.length() && fullText.charAt(wordEnd) != WORD_BOUNDARY && fullText.charAt(wordEnd) != WORD_BOUNDARY1) {
                        ++wordEnd;
                    }

                    // Now highlight based on the word boundaries
                    ColorStateList redColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{Color.RED});
                    TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, redColor, null);

                    wordtoSpan.setSpan(highlightSpan, wordStart, wordEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    wordtoSpan.setSpan(new BackgroundColorSpan(0xFFFFFF00), wordStart, wordEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    wordtoSpan.setSpan(new RelativeSizeSpan(1.5f), wordStart, wordEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                    textView.setText(wordtoSpan, TextView.BufferType.SPANNABLE);

                }
            }
        } else {
            textView.setText(fullText);
        }
    } else {
        textView.setText(fullText);
    }
}


问:
REST and HATEOS definitions self-violating?
QUESTION: Can HATEOAS in REST be considered a valid proposition when it is self-evidently internally contradictory : If an interface is said to not be RESTful (according to Fielding), when a Client cannot utilize the in-band data (URI's) from the Response Hypertext (Hypermedia) without reference to an external (out-of-band) document, and therefore tightly coupling Client and Server according to Fielding, how can we do anything but fail Roy Fielding's prima facie assertion?

It seems to me that Fielding's exposition makes HATEOAS and REST an internally contradictory proposition that cannot be fulfilled with the current technology - unless someone knows how to it without referring to out-of-band data?

(EDIT) I suspect no-one is reading/has read Fielding's rant, so here's the most relevant piece:

"A REST API should be entered with no prior knowledge beyond the initial URI (bookmark) and set of standardized media types that are appropriate for the intended audience (i.e., expected to be understood by any client that might use the API). From that point on, all application state transitions must be driven by client selection of server-provided choices that are present in the received representations or implied by the user’s manipulation of those representations. The transitions may be determined (or limited by) the client’s knowledge of media types and resource communication mechanisms, both of which may be improved on-the-fly (e.g., code-on-demand). [Failure here implies that out-of-band information is driving interaction instead of hypertext.]"

We all keep asserting that we must have out-of-band knowledge of the URI's available methods beyond the initial data stream. Note how Fielding very stridently tells us that this is failure. Yet, it's how we're all dong it, me included. But Fielding screams No back at us.

(EDIT: because no-one's reading ithe explanation).

答:
So, the answer to my question seems to be that none us know how to do it the way Fielding said it should be done, so none us know how to acheive a HATEOAS compliant RESTful API without violating Fielding's primary assertion regarding out-of-band data, and therefore making our app non-RESTful in so doing.

Everyone stridently believes they have this answer right, but we're all ignoring the fact that Roy Fielding says we are all wrong. He says we're all writing RPC's.

Roy Fielding: REST APIs must be hypertext-driven
"I am getting frustrated by the number of people calling any HTTP-based interface a REST API"

It boils down to the fact that we are not building the kind of apps that lend themselves to Roy's thesis on REST. Indeed, he believes the proposition that we would render our URI's as part of CDATA that includes the "method" or that the context of the URI would self-evidently provide it, like the FORM element does. He explicitly rails against the OpenSocialst REST API stating that it is not RESTful.

Here: “anchor elements with an href attribute create a hypertext link that, when selected, invokes a retrieval request (GET) on the URI corresponding to the CDATA-encoded href attribute.” Identifiers, methods, and media types are orthogonal concerns — methods are not given meaning by the media type. Instead, the media type tells the client either what method to use (e.g., anchor implies GET) or how to determine the method to use (e.g., form element says to look in method attribute). The client should already know what the methods mean (they are universal) and how to dereference a URI.

I tend to design JSON responses that provide this approach:

```<code>GET /account/12345 HTTP/1.1
{
    "account": {
        "number": "12345",
        "currency": "usd",
        "balance": "100.00",
        "deposit": {
            "href": "/account/12345/deposit",
            "action": "POST"
        },
        "withdraw": {
            "href": "/account/12345/withdraw",
            "action": "POST"
        },
        "transfer": {
            "href": "/account/12345/transfer",
            "action": "POST"
        },
        "close": {
            "href": "/account/12345/close",
            "action": "DELETE"
        }
    }
}
</code>```

... adding additional properties to the design as needed, but these are the basics.

I believe this allow the Client to be written to be RESTful, but in so doing I am using the Response Body, which Fielding says is not what he intended.

Body:
So, the answer to my question seems to be that none us know how to do it the way Fielding said it should be done, so none us know how to acheive a HATEOAS compliant RESTful API without violating Fielding's primary assertion regarding out-of-band data, and therefore making our app non-RESTful in so doing.

Everyone stridently believes they have this answer right, but we're all ignoring the fact that Roy Fielding says we are all wrong. He says we're all writing RPC's.

Roy Fielding: REST APIs must be hypertext-driven
"I am getting frustrated by the number of people calling any HTTP-based interface a REST API"

It boils down to the fact that we are not building the kind of apps that lend themselves to Roy's thesis on REST. Indeed, he believes the proposition that we would render our URI's as part of CDATA that includes the "method" or that the context of the URI would self-evidently provide it, like the FORM element does. He explicitly rails against the OpenSocialst REST API stating that it is not RESTful.

Here: “anchor elements with an href attribute create a hypertext link that, when selected, invokes a retrieval request (GET) on the URI corresponding to the CDATA-encoded href attribute.” Identifiers, methods, and media types are orthogonal concerns — methods are not given meaning by the media type. Instead, the media type tells the client either what method to use (e.g., anchor implies GET) or how to determine the method to use (e.g., form element says to look in method attribute). The client should already know what the methods mean (they are universal) and how to dereference a URI.

I tend to design JSON responses that provide this approach:

GET /account/12345 HTTP/1.1
{
    "account": {
        "number": "12345",
        "currency": "usd",
        "balance": "100.00",
        "deposit": {
            "href": "/account/12345/deposit",
            "action": "POST"
        },
        "withdraw": {
            "href": "/account/12345/withdraw",
            "action": "POST"
        },
        "transfer": {
            "href": "/account/12345/transfer",
            "action": "POST"
        },
        "close": {
            "href": "/account/12345/close",
            "action": "DELETE"
        }
    }
}

... adding additional properties to the design as needed, but these are the basics.

I believe this allow the Client to be written to be RESTful, but in so doing I am using the Response Body, which Fielding says is not what he intended.


问:
Automate Word document into excel
I have to transfer hundreds of word documents into excel.  The documents are client records from way back, and they look like this:

Date: dd/mm/yy

Employee name: Name

Several lines of text in one paragraph.

There will be dozens of entrees on the page like this, formatted into one column.  I need the end result to be one column for each category.  The major challenge with this is the text descriptions.  The way they are formatted in word, there doesn't seem to be a simple way to copy and paste them into excel without the result being one cell for each line of the paragraph.  Any method I've tried that replaces hard returns for soft returns takes all the text on the entire page and puts into one cell, which makes it worse.  I have hundreds of files to transfer, so I don't have the time to copy and paste each note into one cell.  The paragraphs also are not uniform in length, although there is typically an empty line before and after the note starts/ends.  I'm sure there must be a VB solution for this, but I'm not knowledgeable enough to figure it out.  Any help would be appreciated.

答:
You can set Bookmarks in Word, and import all Bookmarks into ranges in Excel.</p>

```<code>Sub TryThis()
Dim oWord As Word.Application
Dim oDoc As Word.document
Dim vBkMarks As Variant
Dim vRecord
Dim rRecord As Range
Dim nFields As Long
Dim i As Long

vBkMarks = Array("Bookmark1", "Bookmark2", "Bookmark3") 'etc...
ReDim vRecord(LBound(vBkMarks) To UBound(vBkMarks))
nFields = UBound(vBkMarks) - LBound(vBkMarks) + 1
On Error Resume Next
Set oWord = GetObject(, "Word.Application")
On Error GoTo 0
If oWord Is Nothing Then _
Set oWord = CreateObject("Word.Application")
Set oDoc = oWord.ActiveDocument
For i = LBound(vBkMarks) To UBound(vBkMarks)
vRecord(i) = oDoc.Bookmarks(vBkMarks(i)).Range.Text
Next i
With Sheets("DataTable")
.Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0).Resize( _
1, nFields).Value = vRecord
End With
End Sub
</code>```

Title: Automate Word document into excel

Body:
You can set Bookmarks in Word, and import all Bookmarks into ranges in Excel.

Sub TryThis()
Dim oWord As Word.Application
Dim oDoc As Word.document
Dim vBkMarks As Variant
Dim vRecord
Dim rRecord As Range
Dim nFields As Long
Dim i As Long

vBkMarks = Array("Bookmark1", "Bookmark2", "Bookmark3") 'etc...
ReDim vRecord(LBound(vBkMarks) To UBound(vBkMarks))
nFields = UBound(vBkMarks) - LBound(vBkMarks) + 1
On Error Resume Next
Set oWord = GetObject(, "Word.Application")
On Error GoTo 0
If oWord Is Nothing Then _
Set oWord = CreateObject("Word.Application")
Set oDoc = oWord.ActiveDocument
For i = LBound(vBkMarks) To UBound(vBkMarks)
vRecord(i) = oDoc.Bookmarks(vBkMarks(i)).Range.Text
Next i
With Sheets("DataTable")
.Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0).Resize( _
1, nFields).Value = vRecord
End With
End Sub


问:
change a code from flipping "8bpp .bmp image" horizontally to flip a "1bpp .bmp image" horizontally in x86
Hello here I have developed the code for Mirror/flipping an 8 bpp .BMP image horizontally. Handling any width properly, not only multiples of 4. Now I have to convert this code to do the same but for a 1 bpp . bmp image(grayscale) using x86. The difficult part is that I dont know how to excess the individual bit maybe someone can edit this code..

```<code>        section     .text
    global      mirrorbmp8
mirrorbmp8:
    push        ebp
    mov     ebp, esp
    push        ebx
    push        esi
    push        edi

    mov     ebx, [ebp+12]       ;width - without padding
    and     ebx, 11b
    je      init            ;checking if there is a padding
    mov     edi, 4
    sub     edi, ebx
    add     [ebp+12], edi       ;width - with padding

init:
    mov     ebx, [ebp+16]
    ;calculating the distance between top&bottom pixel
    dec     ebx
    mov     eax, [ebp+12]
    mul     ebx
    mov     esi, eax

    mov     edi, [ebp+8]    ;the first bottom pixel
    mov     edx, edi            ;the first top pixel
    mov     eax, edi
    add     eax, esi
    mov     ecx, [ebp+12]
            ;register responsible for calc left columns

loop0:
    push        esi
    mov     esi, [ebp+12]

loop1:
    mov     bl, [edi]               ;changing pixels
    xchg        bl, [eax]
    mov     [edi], bl

    add     edi, esi        ;next pixel in this column
    sub     eax, esi
    cmp     edi, eax
    jl      loop1

    inc     edx             ;next bottom pixel
    mov     edi, edx

    mov     eax, edi                ;next top pixel
    pop     esi
    add     eax, esi

    dec     ecx         ;decrement number of columns left
    jnz     loop0           ;was that the last column?

end:
    pop     edi
    pop     esi
    pop     ebx

    mov     esp, ebp
    pop     ebp
    ret
</code>```

Any help will be appreciated.
Thanks in advance :)

p.s if i will be able to do this version then I have to convert the whole code for x86-64 version also, any hints in this regard will also be helpful..

答:
In case you want to know how to flip the image left to right instead of top to bottom, here's how you'd do that.

First, copy the headers of the bitmap into another file. Next, figure out how many bits past imageWidth % 32 are at the end of each scan line:

```<code>orphanBits = imageWidth % 32
</code>```

In the example below, orphanedBits is 19. Read the last two DWORDS from the end of the scanline into two general purpose registers:

```<code>ebx = 10001010 11010101 00101010 10101010
eax = 01010101 01011000 00000000 00000000
  END OF SCAN LINE ^
</code>```

Use the SHRD operand to move bits from ebx into ecx until the entire register is filled up:

```<code>shrd eax, ebx, orphanBits

ebx = 00000000 00000000 00010001 01011010
eax = 10100101 01010101 01001010 10101011
                       END OF SCAN LINE ^
</code>```

Then use  the following code to swap the bits of eax:

```<code>mov edx,eax
shr eax,1
and edx,055555555h
and eax,055555555h
lea eax,[2*edx+eax]
mov edx,eax
shr eax,2
and edx,033333333h
and eax,033333333h
lea eax,[4*edx+eax]
mov edx,eax
shr eax,4
and edx,0F0F0F0Fh
and eax,0F0F0F0Fh
shl edx,4
add eax,edx
bswap eax

eax = 11010101 01010010 10101010 10100101
      ^ END OF SCAN LINE
</code>```

Write the adjusted DWORD (now in reverse order) into the new image. Repeat until the whole scanline is read. Repeat until all scanlines are read.

Edit: Originally had just bswap before I remembered it swapped bytes, not bits.

ContentLicense: CC BY-SA 2.5

Body:
Hello here I have developed the code for Mirror/flipping an 8 bpp .BMP image horizontally. Handling any width properly, not only multiples of 4. Now I have to convert this code to do the same but for a 1 bpp . bmp image(grayscale) using x86. The difficult part is that I dont know how to excess the individual bit maybe someone can edit this code..

        section     .text
    global      mirrorbmp8
mirrorbmp8:
    push        ebp
    mov     ebp, esp
    push        ebx
    push        esi
    push        edi

    mov     ebx, [ebp+12]       ;width - without padding
    and     ebx, 11b
    je      init            ;checking if there is a padding
    mov     edi, 4
    sub     edi, ebx
    add     [ebp+12], edi       ;width - with padding

init:
    mov     ebx, [ebp+16]
    ;calculating the distance between top&bottom pixel
    dec     ebx
    mov     eax, [ebp+12]
    mul     ebx
    mov     esi, eax

    mov     edi, [ebp+8]    ;the first bottom pixel
    mov     edx, edi            ;the first top pixel
    mov     eax, edi
    add     eax, esi
    mov     ecx, [ebp+12]
            ;register responsible for calc left columns

loop0:
    push        esi
    mov     esi, [ebp+12]

loop1:
    mov     bl, [edi]               ;changing pixels
    xchg        bl, [eax]
    mov     [edi], bl

    add     edi, esi        ;next pixel in this column
    sub     eax, esi
    cmp     edi, eax
    jl      loop1

    inc     edx             ;next bottom pixel
    mov     edi, edx

    mov     eax, edi                ;next top pixel
    pop     esi
    add     eax, esi

    dec     ecx         ;decrement number of columns left
    jnz     loop0           ;was that the last column?

end:
    pop     edi
    pop     esi
    pop     ebx

    mov     esp, ebp
    pop     ebp
    ret

Any help will be appreciated.
Thanks in advance :)

p.s if i will be able to do this version then I have to convert the whole code for x86-64 version also, any hints in this regard will also be helpful..

Body:
In case you want to know how to flip the image left to right instead of top to bottom, here's how you'd do that.

First, copy the headers of the bitmap into another file. Next, figure out how many bits past imageWidth % 32 are at the end of each scan line:

orphanBits = imageWidth % 32

In the example below, orphanedBits is 19. Read the last two DWORDS from the end of the scanline into two general purpose registers:

ebx = 10001010 11010101 00101010 10101010
eax = 01010101 01011000 00000000 00000000
  END OF SCAN LINE ^

Use the SHRD operand to move bits from ebx into ecx until the entire register is filled up:

shrd eax, ebx, orphanBits

ebx = 00000000 00000000 00010001 01011010
eax = 10100101 01010101 01001010 10101011
                       END OF SCAN LINE ^

Then use  the following code to swap the bits of eax:

mov edx,eax
shr eax,1
and edx,055555555h
and eax,055555555h
lea eax,[2*edx+eax]
mov edx,eax
shr eax,2
and edx,033333333h
and eax,033333333h
lea eax,[4*edx+eax]
mov edx,eax
shr eax,4
and edx,0F0F0F0Fh
and eax,0F0F0F0Fh
shl edx,4
add eax,edx
bswap eax

eax = 11010101 01010010 10101010 10100101
      ^ END OF SCAN LINE

Write the adjusted DWORD (now in reverse order) into the new image. Repeat until the whole scanline is read. Repeat until all scanlines are read.

Edit: Originally had just bswap before I remembered it swapped bytes, not bits.


问:
Excel VBA -Insert image, but when I delete the image ind the explorer it dissapears in the excel sheet

The code works (sort of), but when I've inserted the image, I save the excel file and delete the foto in the file explorer. Then when I open then excel file again the image is gone.

```<code>Sub InsertImage()
    With Application.FileDialog(msoFileDialogFilePicker)
        .AllowMultiSelect = False
        .ButtonName = "Submit"
        .Title = "Select an image file"
        .Filters.Clear
        .Filters.Add "JPG", "*.JPG"
        .Filters.Add "JPEG File Interchange Format", "*.JPEG"
        .Filters.Add "Graphics Interchange Format", "*.GIF"
        .Filters.Add "Portable Network Graphics", "*.PNG"
        .Filters.Add "Tag Image File Format", "*.TIFF"
        .Filters.Add "All Pictures", "*.*"

        If .Show = -1 Then
            Dim img As Object
            Set img = ActiveSheet.Pictures.Insert(.SelectedItems(1))

            'Scale image size
            'img.ShapeRange.ScaleWidth 0.75, msoFalse, msoScaleFromTopLeft
            'img.ShapeRange.ScaleHeight 0.75, msoFalse, msoScaleFromTopLeft

            'Position image
            img.Left = 300
            img.Top = 200

            'Set image sizes in points
            img.Width = 150
            img.Height = 150
        Else
            MsgBox ("Programet blev Annulleret")
        End If
    End With
End Sub
</code>```

Isn't there a way to make the picture save with the excel file? So when I delete the original picture it is still in the excel file.

The error I get "The linked image cannot be displayed. The file may have been moved, renamed, or deleted. Verify that the link points to the correct file and location.

答:
The picture is being inserted as a linked image, if you want the image to be saved in the excel spreadsheet you'll want it to be an embedded image</p>

```<code>Sub InsertImage()

    Dim FullPathName as string

    With Application.FileDialog(msoFileDialogFilePicker)
        .AllowMultiSelect = False
        .ButtonName = "Submit"
        .Title = "Select an image file"
        .Filters.Clear
        .Filters.Add "JPG", "*.JPG"
        .Filters.Add "JPEG File Interchange Format", "*.JPEG"
        .Filters.Add "Graphics Interchange Format", "*.GIF"
        .Filters.Add "Portable Network Graphics", "*.PNG"
        .Filters.Add "Tag Image File Format", "*.TIFF"
        .Filters.Add "All Pictures", "*.*"

        If .Show = -1 Then
            '''''' Store the pathname of selected image to a variable
            FullPathName = .SelectedItems(1)

            '''''' Imports image as embedded into Worksheet
            Activesheet.Shapes.AddPicture filename:=FullPathName, _
            linktofile:=msoFalse, savewithdocument:=msoCTrue, _
            left:=300, _
            top:=200, _
            width:=150, _
            height:=150

            Dim Pic As shape
            For Each Pic In ActiveSheet.Shapes
               ''''' Change "A1" to which ever cell this is being placed in
               'If (Pic.left = Range("A1").left And Pic.top = Range("A1").top) Then
                  Pic.Select
                  Pic.LockAspectRatio = msoTrue
               'End If
            Next Pic

        Else
            MsgBox ("Programet blev Annulleret")
        End If
    End With
End Sub
</code>```

Body:
The code works (sort of), but when I've inserted the image, I save the excel file and delete the foto in the file explorer. Then when I open then excel file again the image is gone.

Sub InsertImage()
    With Application.FileDialog(msoFileDialogFilePicker)
        .AllowMultiSelect = False
        .ButtonName = "Submit"
        .Title = "Select an image file"
        .Filters.Clear
        .Filters.Add "JPG", "*.JPG"
        .Filters.Add "JPEG File Interchange Format", "*.JPEG"
        .Filters.Add "Graphics Interchange Format", "*.GIF"
        .Filters.Add "Portable Network Graphics", "*.PNG"
        .Filters.Add "Tag Image File Format", "*.TIFF"
        .Filters.Add "All Pictures", "*.*"

        If .Show = -1 Then
            Dim img As Object
            Set img = ActiveSheet.Pictures.Insert(.SelectedItems(1))

            'Scale image size
            'img.ShapeRange.ScaleWidth 0.75, msoFalse, msoScaleFromTopLeft
            'img.ShapeRange.ScaleHeight 0.75, msoFalse, msoScaleFromTopLeft

            'Position image
            img.Left = 300
            img.Top = 200

            'Set image sizes in points
            img.Width = 150
            img.Height = 150
        Else
            MsgBox ("Programet blev Annulleret")
        End If
    End With
End Sub

Isn't there a way to make the picture save with the excel file? So when I delete the original picture it is still in the excel file.

The error I get "The linked image cannot be displayed. The file may have been moved, renamed, or deleted. Verify that the link points to the correct file and location.

Body:
The picture is being inserted as a linked image, if you want the image to be saved in the excel spreadsheet you'll want it to be an embedded image

Sub InsertImage()

    Dim FullPathName as string

    With Application.FileDialog(msoFileDialogFilePicker)
        .AllowMultiSelect = False
        .ButtonName = "Submit"
        .Title = "Select an image file"
        .Filters.Clear
        .Filters.Add "JPG", "*.JPG"
        .Filters.Add "JPEG File Interchange Format", "*.JPEG"
        .Filters.Add "Graphics Interchange Format", "*.GIF"
        .Filters.Add "Portable Network Graphics", "*.PNG"
        .Filters.Add "Tag Image File Format", "*.TIFF"
        .Filters.Add "All Pictures", "*.*"

        If .Show = -1 Then
            '''''' Store the pathname of selected image to a variable
            FullPathName = .SelectedItems(1)

            '''''' Imports image as embedded into Worksheet
            Activesheet.Shapes.AddPicture filename:=FullPathName, _
            linktofile:=msoFalse, savewithdocument:=msoCTrue, _
            left:=300, _
            top:=200, _
            width:=150, _
            height:=150

            Dim Pic As shape
            For Each Pic In ActiveSheet.Shapes
               ''''' Change "A1" to which ever cell this is being placed in
               'If (Pic.left = Range("A1").left And Pic.top = Range("A1").top) Then
                  Pic.Select
                  Pic.LockAspectRatio = msoTrue
               'End If
            Next Pic

        Else
            MsgBox ("Programet blev Annulleret")
        End If
    End With
End Sub


问:
Parsing unknown number of form field pairs into Javascript array
I have a form featuring 2 inputs, a dropdown and a text-input. I would like to append an empty array with the values of each, using the dropdown as the Key and the text-input as the value.

Furthermore, I have an unknown number of these key/value : select/input combinations, the example below featuring 2.

```<code><div id="referenceList">

  <!-- Pair #1 -->
  <label>1) 'Reference value 1'</label>
  <select class="form-control form-list input_importData predictionType" id="input_importData_referenceTypeMap-0">
    <option value="" disabled="">Select a Reference Type</option>
    <option value="Dry Matter">Dry Matter</option>
    <option value="Brix">Brix</option>
    <option value="Total Acid">Total Acid</option>
    <option value="Firmness">Firmness</option>
  </select>
  <input type="number" class="form-control form-list input_importData" id="input_importData_referenceValue-0">

  <!-- Pair #2 -->
  <label>2) 'Reference value 2'</label>
  <select class="form-control form-list input_importData predictionType" id="input_importData_referenceTypeMap-1">
    <option value="" disabled="">Select a Reference Type</option>
    <option value="Dry Matter">Dry Matter</option>
    <option value="Brix">Brix</option>
    <option value="Total Acid">Total Acid</option>
    <option value="Firmness">Firmness</option>
  </select>
  <input type="number" class="form-control form-list input_importData" id="input_importData_referenceValue-1">
</div>
</code>```

Here is an example of my code attempting to do this:

```<code>var referenceArray = {};
$('#referenceList select, #referenceList input').each(function(key, value) {
     referenceArray[this.value] = this.value;
});
</code>```

And here is the result of outputting referenceArray:

```<code>{{"Reference value 1":13.644132614135742,"Reference value 2":16.426380157470703}: "{"Reference value 1":13.644132614135742,"Reference value 2":16.426380157470703}", Brix: "Brix", 13.644132614135742: "13.644132614135742", Dry Matter: "Dry Matter", 16.426380157470703: "16.426380157470703", …}
</code>```

Clearly not functioning properly as the expected result would be

{"Brix":13.64434534, "Dry Matter": 15.343483423}

Not sure if I'm doing this incorrectly by using unique id's for each select/input combination or if they should be titled the same for better iteration?

Thanks!

答:
Try this out. I added a fieldset to your html. And then all you need to do is cycle through every fieldset o whatever and add that to your object. I´ll explain the code in a later edit.

IDK whether this is a more optimal way but it might be easier to comprehend and edit, since every value pair will be separated and extracted accordingly.

$(document).ready(function() {
  var referenceArray = {};

  $('select, input').on('change', function() { /**I use these to capture an event*/
    referenceArray = {}; //Rebuild the object, if you need
    let fld, objKey, objValue;
    $('fieldset').each(function(key, value) {  /*Cycle through every container not every field. then extract the value of the inputs in every container. In this case i am using a fieldset*/
      fld = $(this);
      objKey = fld.find('select').val(); //Get the key of your property
      objValue = fld.find('input').val(); //Get the actual value
      referenceArray[objKey] = objValue; //Add the key and value as needed
    });

    console.log(referenceArray);
  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="referenceList">
  <!-- Pair #1 -->
  <fieldset>
    <label>1) 'Reference value 1'</label>
    <select class="form-control form-list input_importData predictionType" id="input_importData_referenceTypeMap-0">
      <option value="" disabled="">Select a Reference Type</option>
      <option value="Dry Matter">Dry Matter</option>
      <option value="Brix">Brix</option>
      <option value="Total Acid">Total Acid</option>
      <option value="Firmness">Firmness</option>
    </select>
    <input type="number" class="form-control form-list input_importData" id="input_importData_referenceValue-0">
  </fieldset>

  <fieldset>
    <!-- Pair #2 -->
    <label>2) 'Reference value 2'</label>
    <select class="form-control form-list input_importData predictionType" id="input_importData_referenceTypeMap-1">
      <option value="" disabled="">Select a Reference Type</option>
      <option value="Dry Matter">Dry Matter</option>
      <option value="Brix">Brix</option>
      <option value="Total Acid">Total Acid</option>
      <option value="Firmness">Firmness</option>
    </select>
    <input type="number" class="form-control form-list input_importData" id="input_importData_referenceValue-1">
  </fieldset>

</div></code>```

Body:
I have a form featuring 2 inputs, a dropdown and a text-input. I would like to append an empty array with the values of each, using the dropdown as the Key and the text-input as the value.

Furthermore, I have an unknown number of these key/value : select/input combinations, the example below featuring 2.

  1) 'Reference value 1'
  <select class="form-control form-list input_importData predictionType" id="input_importData_referenceTypeMap-0">
    <option value="" disabled="">Select a Reference Type</option>
    <option value="Dry Matter">Dry Matter</option>
    <option value="Brix">Brix</option>
    <option value="Total Acid">Total Acid</option>
    <option value="Firmness">Firmness</option>
  </select>
  <input type="number" class="form-control form-list input_importData" id="input_importData_referenceValue-0">

  2) 'Reference value 2'
  <select class="form-control form-list input_importData predictionType" id="input_importData_referenceTypeMap-1">
    <option value="" disabled="">Select a Reference Type</option>
    <option value="Dry Matter">Dry Matter</option>
    <option value="Brix">Brix</option>
    <option value="Total Acid">Total Acid</option>
    <option value="Firmness">Firmness</option>
  </select>
  <input type="number" class="form-control form-list input_importData" id="input_importData_referenceValue-1">

Here is an example of my code attempting to do this:

var referenceArray = {};
$('#referenceList select, #referenceList input').each(function(key, value) {
     referenceArray[this.value] = this.value;
});

And here is the result of outputting referenceArray:

{{"Reference value 1":13.644132614135742,"Reference value 2":16.426380157470703}: "{"Reference value 1":13.644132614135742,"Reference value 2":16.426380157470703}", Brix: "Brix", 13.644132614135742: "13.644132614135742", Dry Matter: "Dry Matter", 16.426380157470703: "16.426380157470703", …}

Clearly not functioning properly as the expected result would be

{"Brix":13.64434534, "Dry Matter": 15.343483423}

Not sure if I'm doing this incorrectly by using unique id's for each select/input combination or if they should be titled the same for better iteration?

Thanks!

Body:
Try this out. I added a fieldset to your html. And then all you need to do is cycle through every fieldset o whatever and add that to your object. I´ll explain the code in a later edit.

IDK whether this is a more optimal way but it might be easier to comprehend and edit, since every value pair will be separated and extracted accordingly.

$(document).ready(function() {
  var referenceArray = {};

  $('select, input').on('change', function() { /**I use these to capture an event*/
    referenceArray = {}; //Rebuild the object, if you need
    let fld, objKey, objValue;
    $('fieldset').each(function(key, value) {  /*Cycle through every container not every field. then extract the value of the inputs in every container. In this case i am using a fieldset*/
      fld = $(this);
      objKey = fld.find('select').val(); //Get the key of your property
      objValue = fld.find('input').val(); //Get the actual value
      referenceArray[objKey] = objValue; //Add the key and value as needed
    });

    console.log(referenceArray);
  });

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="referenceList">
  <!-- Pair #1 -->
  <fieldset>
    <label>1) 'Reference value 1'</label>
    <select class="form-control form-list input_importData predictionType" id="input_importData_referenceTypeMap-0">
      <option value="" disabled="">Select a Reference Type</option>
      <option value="Dry Matter">Dry Matter</option>
      <option value="Brix">Brix</option>
      <option value="Total Acid">Total Acid</option>
      <option value="Firmness">Firmness</option>
    </select>
    <input type="number" class="form-control form-list input_importData" id="input_importData_referenceValue-0">
  </fieldset>

  <fieldset>
    <!-- Pair #2 -->
    <label>2) 'Reference value 2'</label>
    <select class="form-control form-list input_importData predictionType" id="input_importData_referenceTypeMap-1">
      <option value="" disabled="">Select a Reference Type</option>
      <option value="Dry Matter">Dry Matter</option>
      <option value="Brix">Brix</option>
      <option value="Total Acid">Total Acid</option>
      <option value="Firmness">Firmness</option>
    </select>
    <input type="number" class="form-control form-list input_importData" id="input_importData_referenceValue-1">
  </fieldset>

</div>


问:
how to split a text file by line gaps in java
I am reading a text file in Java that looks like this,

"
Q1. You are given a train data set having 1000 columns and 1 million rows. The data set is based on a classification problem. Your manager has asked you to reduce the dimension of this data so that model computation time can be reduced. Your machine has memory constraints. What would you do? (You are free to make practical assumptions.)

Q2. Is rotation necessary in PCA? If yes, Why? What will happen if you don’t rotate the components?

Q3. You are given a data set. The data set has missing values which spread along 1 standard deviation from the median. What percentage of data would remain unaffected? Why? "

Now, I want to read this file and then store each of these sentences(questions) in a string array. How can I do that in java?

I tried this,

```<code>String mlq = new String(Files.readAllBytes(Paths.get("MLques.txt")));
String[] mlq1=mlq.split("\n\n");
</code>```

But this is not working.

答:
Try this

```<code>String mlq = new String(Files.readAllBytes(Paths.get("MLQ.txt")));
    String[] mlq1=mlq.split("\r\n\r\n");
    System.out.println(mlq1.length);
    System.out.println(Arrays.toString(mlq1));
</code>```

This should do it by line gap of 2 lines.

Body:
I am reading a text file in Java that looks like this,

"
Q1. You are given a train data set having 1000 columns and 1 million rows. The data set is based on a classification problem. Your manager has asked you to reduce the dimension of this data so that model computation time can be reduced. Your machine has memory constraints. What would you do? (You are free to make practical assumptions.)

Q2. Is rotation necessary in PCA? If yes, Why? What will happen if you don’t rotate the components?

Q3. You are given a data set. The data set has missing values which spread along 1 standard deviation from the median. What percentage of data would remain unaffected? Why? "

Now, I want to read this file and then store each of these sentences(questions) in a string array. How can I do that in java?

I tried this,

String mlq = new String(Files.readAllBytes(Paths.get("MLques.txt")));
String[] mlq1=mlq.split("\n\n");

But this is not working.

Body:
Try this

String mlq = new String(Files.readAllBytes(Paths.get("MLQ.txt")));
    String[] mlq1=mlq.split("\r\n\r\n");
    System.out.println(mlq1.length);
    System.out.println(Arrays.toString(mlq1));

This should do it by line gap of 2 lines.


问:
GLSL performance differences between function call vs. inlining

Does it make a performance difference in GLSL if something simple like a + operator is wrapped into a function?

So for example these two scenarios:

Example 1:

in uniform float uValueA;
in uniform float uValueB;

void main()
{
    float value = uValueA + uValueB;
    // [...]
}
```

<h3>Example 2:</h3>

<pre class="lang-c prettyprint-override"><code>in uniform float uValueA;
in uniform float uValueB;

float addValues(float a, float b)
{
    return a + b;
}

void main()
{
    float value = addValues(uValueA, uValueB);
    // [...]
}
</code>```

is there any difference in the compiled end product? Or do they result in the same number of instructions and performance?

答:
When I tested this specific case a couple years ago, I found no performance difference between functions or in-line code. If I remember correctly, at the time I used tools from Nvidia and/or AMD to look at the assembly code generated from the GLSL files. This also confirmed that the assembly was identical whether I used functions or not. This suggests that functions are inlined.

I suggest you have a look for yourself at the assembly code of both versions of your shader to convince yourself. This question (https://gamedev.stackexchange.com/questions/65695/aquire-disassembly-of-shader-code) explains some ways to get this information.

Body:
Does it make a performance difference in GLSL if something simple like a + operator is wrapped into a function?

So for example these two scenarios:

Example 1:

in uniform float uValueA;
in uniform float uValueB;

void main()
{
    float value = uValueA + uValueB;
    // [...]
}

Example 2:

in uniform float uValueA;
in uniform float uValueB;

float addValues(float a, float b)
{
    return a + b;
}

void main()
{
    float value = addValues(uValueA, uValueB);
    // [...]
}

is there any difference in the compiled end product? Or do they result in the same number of instructions and performance?


问:
ASP TableAdapters. Getting row data from a SQL parameter query
Trying to get my head round ASP.NET DALs and TableAdapters and I'm hoping somebody can help me with getting the column data when using SQL query parameters.

If I have a TableAdapter with a query that returns one or more rows, I can get row and column data from the datatable no problem. For a simple query which returns one row I can use:

```<code>SQL: SELECT firstName, lastName from Names WHERE ID=1

Dim MyAdapter1 As New ProjectTableAdapters.NamesTableAdapter1
Dim f As String = MyAdapter1.GetNames.Rows(0)("firstName")
Dim l As String = MyAdapter1.GetNames.Rows(0)("lastName")
</code>```

However if use a TableAdapter which has a query with a parameter I keep getting exceptions thrown. I'm sure this is simple, if someone can point me in right direction (vb if possible). Thanks a lot.

```<code>SQL: SELECT firstName, lastName from Names WHERE ID=@ID

Dim ID As Integer = 1
Dim MyAdapter2 As New ProjectTableAdapters.NamesTableAdapter2
Dim f As String = MyAdapter2.GetNames(Rows(0)("firstName"),ID)   [throws exection]
</code>```

Edit:
I think I have it working now - my bad syntax...

```<code>Dim f As String = MyAdapter2.GetNames(ID).Rows(0)("firstName")
</code>```

答:
```<code>Public Function MyFunction() As DataSet
        Dim conString As String = "Connection String"
        Dim conn As New SqlConnection(conString)
        Dim da As New SqlDataAdapter()
        Dim cmd As New SqlCommand With {
            .Connection = conn,
            .CommandText = "SELECT firstName, lastName from Names WHERE ID=@ID",
            .CommandType = CommandType.Text}
        cmd.Parameters.Add("@ID", SqlDbType.Int).Value = 1
        da.SelectCommand = cmd
        Dim ds As DataSet = New DataSet()
        conn.Open()
        da.Fill(ds)
        conn.Close()
        Return ds
    End Function
</code>```

Body:
Trying to get my head round ASP.NET DALs and TableAdapters and I'm hoping somebody can help me with getting the column data when using SQL query parameters.

If I have a TableAdapter with a query that returns one or more rows, I can get row and column data from the datatable no problem. For a simple query which returns one row I can use:

SQL: SELECT firstName, lastName from Names WHERE ID=1

Dim MyAdapter1 As New ProjectTableAdapters.NamesTableAdapter1
Dim f As String = MyAdapter1.GetNames.Rows(0)("firstName")
Dim l As String = MyAdapter1.GetNames.Rows(0)("lastName")

However if use a TableAdapter which has a query with a parameter I keep getting exceptions thrown. I'm sure this is simple, if someone can point me in right direction (vb if possible). Thanks a lot.

SQL: SELECT firstName, lastName from Names WHERE ID=@ID

Dim ID As Integer = 1
Dim MyAdapter2 As New ProjectTableAdapters.NamesTableAdapter2
Dim f As String = MyAdapter2.GetNames(Rows(0)("firstName"),ID)   [throws exection]

Edit:
I think I have it working now - my bad syntax...

Dim f As String = MyAdapter2.GetNames(ID).Rows(0)("firstName")


问:
Python defining methods
I have been reading some python code out there and I see some variations on how one write method.

Some write (example 1):

```<code>def A() :
*method A implementation*

def B():
*method B implementation*
</code>```

Others write (example 2):

```<code>def A() :
*method A implementation*

   def B():
   *method B implementation*
</code>```

Does anyone know the difference, pro and cons of example 1 versus example 2 ?

Thanks =)

答: As far as I understand in the second example function B() will be accessible only from the function A(). And in the first one both functions will be globally accessible.

Title: Python defining methods

Body:
I have been reading some python code out there and I see some variations on how one write method.

Some write (example 1):

def A() :
*method A implementation*

def B():
*method B implementation*

Others write (example 2):

def A() :
*method A implementation*

   def B():
   *method B implementation*

Does anyone know the difference, pro and cons of example 1 versus example 2 ?

Thanks =)


问:
How to check if a value doesn't exist in one or more arrays inside array of arrays?
I need to write a function that returns true if a value exists in a multidimensional array and false if the value doesn't exist in atleast one array in the multidimensional array.</p>

```<code>    function isItemOmnipresent (arrayOfArrays, item) {

     var arrays = arrayOfArrays;
     var itemCheck = item;

     for(var i = 0; i < arrays.length; i++){
      for(var j = 0; j < arrays[i].length; j++){
       if(arrays[i][j] == itemCheck) {
         return true;
      } else {
         return false;
      }
    }
  }
</code>```

答:
```<code> const check = (multi, value) => multi.some(array => array.includes(value));
</code>```

Usable like this:

```<code>check([[1,2],[3,4]], 2);
</code>```

Body:
I need to write a function that returns true if a value exists in a multidimensional array and false if the value doesn't exist in atleast one array in the multidimensional array.

    function isItemOmnipresent (arrayOfArrays, item) {

     var arrays = arrayOfArrays;
     var itemCheck = item;

     for(var i = 0; i < arrays.length; i++){
      for(var j = 0; j < arrays[i].length; j++){
       if(arrays[i][j] == itemCheck) {
         return true;
      } else {
         return false;
      }
    }
  }

Body:
 const check = (multi, value) => multi.some(array => array.includes(value));

Usable like this:

check([[1,2],[3,4]], 2);


问:
fade in button so it won't automatically fade out again
I'm using a tap gesture recogniser so if the user taps on the screen the button fades out for 5 seconds and then if the user wants to see the buttons on the screen again they tap on the screen and the button fades in.

The Problem is:

I can't disable the button when it fades in so it won't automatically fade out again. I tried to invalidate the timer but that didn't work. To be more specific of what I want to do:

On app load, you see an enabled "Start Stop Button." - Tap anywhere on the screen and a 5 second timer starts to fade the button out and disables it. Once the button fades out and disables, I can tap anywhere on the screen to fade the button back in, enable it, and kill the timer so the button shows up as it was before I first tapped it.

```<code> class ViewController: UIViewController {
    // Create these 3 properties in the top of your class
    var secondToFadeOut = 5 // How many second do you want the view to idle before the button fades. You can change this to whatever you'd like.
    var timer = Timer() // Create the timer!
    var isTimerRunning: Bool = false // Need this to prevent multiple timers from running at the same time.

@IBOutlet weak var startStopButton: UIButton! // The outlet for your button. This is used to fade it in and out, and enable / disable it.

override func viewDidLoad() {
    super.viewDidLoad()
    startStopButton.isEnabled = true
    runTimer()

    // Add a tap gesture recognizer to the main view to determine when the screen was tapped (for the purpose of resetting the timer).
    let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.tap(_:)))
    self.view.addGestureRecognizer(tapRecognizer)

}

func runTimer() {
    // Create the timer to run a method (in this case... updateTimer) every 1 second.
    timer = Timer.scheduledTimer(timeInterval: 1, target: self,   selector: (#selector(ViewController.updateTimer)), userInfo: nil, repeats: true)
    // Set the isTimerRunning bool to true
    isTimerRunning = true
}

@objc func updateTimer() {
    // Every 1 second that this method runs, 1 second will be chopped off the secondToFadeOut property. If that hits 0 (< 1), then run the fadeOutButton and invalidate the timer so it stops running.
    secondToFadeOut -= 1
    print(secondToFadeOut)
    if secondToFadeOut < 1 {
        fadeOutButton()
        timer.invalidate()
        isTimerRunning = false
    }
}

@objc func tap(_ gestureRecognizer: UITapGestureRecognizer) {
    // When the view is tapped (based on the gesture recognizer), reset the secondToFadeOut property, fade in (and enable) the button.
    //secondToFadeOut = 5
    fadeInButton()
    timer.invalidate()
    //if isTimerRunning == false {
    //    runTimer()
    //}
}

func fadeOutButton() {
    // Fade out your button! I also disabled it here. But you can do whatever your little heart desires.
    UIView.animate(withDuration: 0.5) {
        self.startStopButton.alpha = 0.25
    }
    self.startStopButton.isEnabled = false
}
func fadeInButton() {
    // Fade the button back in, and set it back to active (so it's tappable)
    UIView.animate(withDuration: 0.5) {
        self.startStopButton.alpha = 1
    }
    self.startStopButton.isEnabled = true
}

@IBAction func startStopButtonPressed(_ sender: UIButton) {
    print("Start Stop Button Pressed")
}
}
</code>```

答:
My best guess is that you have a rogue Timer object that remains in memory even after you invalidate your current timer, and that is causing the button to fade out again after it fades in.

I have made several edits to your class. Check the code out:

```<code> class ViewController: UIViewController {
// Create these 3 properties in the top of your class
var secondToFadeOut = 5 // How many second do you want the view to idle before the button fades. You can change this to whatever you'd like.
var timer? = nil // Create the timer!

@IBOutlet weak var startStopButton: UIButton! // The outlet for your button. This is used to fade it in and out, and enable / disable it.

override func viewDidLoad() {
    super.viewDidLoad()
    startStopButton.isEnabled = true
    runTimer()

    // Add a tap gesture recognizer to the main view to determine when the screen was tapped (for the purpose of resetting the timer).
    let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.tap(_:)))
    self.view.addGestureRecognizer(tapRecognizer)
}

func runTimer() {
    if timer == nil {
        timer = Timer.scheduledTimer(timeInterval: secondToFadeOut, target: self,   selector: (#selector(ViewController.timerFired)), userInfo: nil, repeats: false)
    }
}

@objc func timerFired() {
    timer = nil
    if self.startStopButton.isEnabled {
        fadeOutButton()
    } else {
        fadeInButton()
    }
}

@objc func tap(_ gestureRecognizer: UITapGestureRecognizer) {
    runTimer()
}

func fadeOutButton() {
    UIView.animate(withDuration: 0.5) {
        self.startStopButton.alpha = 0.25
    }
    self.startStopButton.isEnabled = false
}

func fadeInButton() {
    UIView.animate(withDuration: 0.5) {
        self.startStopButton.alpha = 1
    }
    self.startStopButton.isEnabled = true
}

@IBAction func startStopButtonPressed(_ sender: UIButton) {
    print("Start Stop Button Pressed")
}
}
</code>```

Body:
I'm using a tap gesture recogniser so if the user taps on the screen the button fades out for 5 seconds and then if the user wants to see the buttons on the screen again they tap on the screen and the button fades in.

The Problem is:

I can't disable the button when it fades in so it won't automatically fade out again. I tried to invalidate the timer but that didn't work. To be more specific of what I want to do:

On app load, you see an enabled "Start Stop Button." - Tap anywhere on the screen and a 5 second timer starts to fade the button out and disables it. Once the button fades out and disables, I can tap anywhere on the screen to fade the button back in, enable it, and kill the timer so the button shows up as it was before I first tapped it.

 class ViewController: UIViewController {
    // Create these 3 properties in the top of your class
    var secondToFadeOut = 5 // How many second do you want the view to idle before the button fades. You can change this to whatever you'd like.
    var timer = Timer() // Create the timer!
    var isTimerRunning: Bool = false // Need this to prevent multiple timers from running at the same time.

@IBOutlet weak var startStopButton: UIButton! // The outlet for your button. This is used to fade it in and out, and enable / disable it.

override func viewDidLoad() {
    super.viewDidLoad()
    startStopButton.isEnabled = true
    runTimer()

    // Add a tap gesture recognizer to the main view to determine when the screen was tapped (for the purpose of resetting the timer).
    let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.tap(_:)))
    self.view.addGestureRecognizer(tapRecognizer)

}

func runTimer() {
    // Create the timer to run a method (in this case... updateTimer) every 1 second.
    timer = Timer.scheduledTimer(timeInterval: 1, target: self,   selector: (#selector(ViewController.updateTimer)), userInfo: nil, repeats: true)
    // Set the isTimerRunning bool to true
    isTimerRunning = true
}

@objc func updateTimer() {
    // Every 1 second that this method runs, 1 second will be chopped off the secondToFadeOut property. If that hits 0 (< 1), then run the fadeOutButton and invalidate the timer so it stops running.
    secondToFadeOut -= 1
    print(secondToFadeOut)
    if secondToFadeOut < 1 {
        fadeOutButton()
        timer.invalidate()
        isTimerRunning = false
    }
}

@objc func tap(_ gestureRecognizer: UITapGestureRecognizer) {
    // When the view is tapped (based on the gesture recognizer), reset the secondToFadeOut property, fade in (and enable) the button.
    //secondToFadeOut = 5
    fadeInButton()
    timer.invalidate()
    //if isTimerRunning == false {
    //    runTimer()
    //}
}

func fadeOutButton() {
    // Fade out your button! I also disabled it here. But you can do whatever your little heart desires.
    UIView.animate(withDuration: 0.5) {
        self.startStopButton.alpha = 0.25
    }
    self.startStopButton.isEnabled = false
}
func fadeInButton() {
    // Fade the button back in, and set it back to active (so it's tappable)
    UIView.animate(withDuration: 0.5) {
        self.startStopButton.alpha = 1
    }
    self.startStopButton.isEnabled = true
}

@IBAction func startStopButtonPressed(_ sender: UIButton) {
    print("Start Stop Button Pressed")
}
}

Body:
My best guess is that you have a rogue Timer object that remains in memory even after you invalidate your current timer, and that is causing the button to fade out again after it fades in.

I have made several edits to your class. Check the code out:

 class ViewController: UIViewController {
// Create these 3 properties in the top of your class
var secondToFadeOut = 5 // How many second do you want the view to idle before the button fades. You can change this to whatever you'd like.
var timer? = nil // Create the timer!

@IBOutlet weak var startStopButton: UIButton! // The outlet for your button. This is used to fade it in and out, and enable / disable it.

override func viewDidLoad() {
    super.viewDidLoad()
    startStopButton.isEnabled = true
    runTimer()

    // Add a tap gesture recognizer to the main view to determine when the screen was tapped (for the purpose of resetting the timer).
    let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.tap(_:)))
    self.view.addGestureRecognizer(tapRecognizer)
}

func runTimer() {
    if timer == nil {
        timer = Timer.scheduledTimer(timeInterval: secondToFadeOut, target: self,   selector: (#selector(ViewController.timerFired)), userInfo: nil, repeats: false)
    }
}

@objc func timerFired() {
    timer = nil
    if self.startStopButton.isEnabled {
        fadeOutButton()
    } else {
        fadeInButton()
    }
}

@objc func tap(_ gestureRecognizer: UITapGestureRecognizer) {
    runTimer()
}

func fadeOutButton() {
    UIView.animate(withDuration: 0.5) {
        self.startStopButton.alpha = 0.25
    }
    self.startStopButton.isEnabled = false
}

func fadeInButton() {
    UIView.animate(withDuration: 0.5) {
        self.startStopButton.alpha = 1
    }
    self.startStopButton.isEnabled = true
}

@IBAction func startStopButtonPressed(_ sender: UIButton) {
    print("Start Stop Button Pressed")
}
}


问:
How to use custom name convention with owned types?
```<code>public class ProcessInitialization
{
    public Guid CorrelationId { get; set; }
    public MyProcessContext ProcessContext { get; set; }
}

public class MyProcessContext
{
    public int? ProcessId { get; set; }
}
</code>```

Without using my convention I got

```<code>SELECT `process`.`CorrelationId`
FROM `ProcessInitialization` AS `process`
WHERE `process`.`ProcessContext_ProcessId` = 8
</code>```

My convention makes snake_case from PascalCase:

```<code>public static void SetSimpleUnderscoreTableNameConvention(this ModelBuilder modelBuilder,
    bool preserveAcronyms,
    IDictionary<string, string> propertyMap = null,
    IDictionary<string, string> entityMap = null
    )
{
    var propMap = propertyMap ?? new Dictionary<string, string>();
    var entMap = entityMap ?? new Dictionary<string, string>();

    foreach (var entity in modelBuilder.Model.GetEntityTypes())
    {
        foreach (var prop in entity.GetProperties())
        {
            if (propMap.ContainsKey(prop.Name))
            {
                prop.Relational().ColumnName = propMap[prop.Name];
            }
            else
            {
                var underscoredProp = AddUndercoresToSentence(prop.Name, preserveAcronyms);
                prop.Relational().ColumnName = underscoredProp.ToLowerInvariant();
            }
        }

        var entName = entity.DisplayName();

        if (entMap.ContainsKey(entName))
        {
            entity.Relational().TableName = entMap[entName];
        }
        else
        {
            var underscored = AddUndercoresToSentence(entity.DisplayName(), preserveAcronyms);
            entity.Relational().TableName = underscored.ToLowerInvariant();
        }
    }
}
</code>```

With it query becomes invalid:

```<code>SELECT `process`.`correlation_id`
FROM `process`
LEFT JOIN `process_initialization._process_context#_my_process_context` AS `process.ProcessContext` ON `process`.`correlation_id` = `process.ProcessContext`.`process_initialization_correlation_id`
WHERE `process.ProcessContext`.`process_id` = 8
</code>```

Looks like I need to not apply my transformation to some of entity:

```<code>var underscored = AddUndercoresToSentence(entity.DisplayName(), preserveAcronyms);
if (underscored.Contains("#")) // any other way to understand it is special?
    continue;
entity.Relational().TableName = underscored.ToLowerInvariant();
</code>```

After that I got:

The keys {'ProcessInitializationCorrelationId'} on 'ProcessInitialization.ProcessContext#MyProcessContext' and {'CorrelationId'} on 'ProcessInitialization' are both mapped to 'process_initialization.PK_process_initialization' but with different columns ({'process_initialization_correlation_id'} and {'correlation_id'}).

答:
Owned types require special processing.

First, you recognize them by using IEntityType.IsOwned() method.

Then, when the entity type is owned, you should skip the table name mapping (because they share the same table as the root owner entity). Also owned types have shadow PK properties which should be skipped, and for other properties you should build column name from the path from root owner to the owned type. The owner information is accessible through DefiningEntityType and DefiningNavigationName properties of IEntityType.

Applying all that to your code:

```<code>foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
    foreach (var prop in entity.GetProperties())
    {
        if (entity.IsOwned() && prop.IsPrimaryKey()) continue;
        IEntityType propOwner = entity;
        string propName = prop.Name, columnName = null;
        do
        {
            if (!propMap.TryGetValue(propName, out var name))
                name = AddUndercoresToSentence(propName, preserveAcronyms).ToLowerInvariant();
            columnName = columnName == null ? name : name + "_" + columnName;
            propName = propOwner.DefiningNavigationName;
            propOwner = propOwner.DefiningEntityType;
        }
        while (propName != null);
        prop.Relational().ColumnName = columnName;
    }

    if (entity.IsOwned()) continue;
    var entName = entity.DisplayName();
    if (!entMap.TryGetValue(entName, out var tableName))
        tableName = AddUndercoresToSentence(entName, preserveAcronyms).ToLowerInvariant();
    entity.Relational().TableName = tableName;
}
</code>```

Body:
public class ProcessInitialization
{
    public Guid CorrelationId { get; set; }
    public MyProcessContext ProcessContext { get; set; }
}

public class MyProcessContext
{
    public int? ProcessId { get; set; }
}

Without using my convention I got

SELECT `process`.`CorrelationId`
FROM `ProcessInitialization` AS `process`
WHERE `process`.`ProcessContext_ProcessId` = 8

My convention makes snake_case from PascalCase:

public static void SetSimpleUnderscoreTableNameConvention(this ModelBuilder modelBuilder,
    bool preserveAcronyms,
    IDictionary<string, string> propertyMap = null,
    IDictionary<string, string> entityMap = null
    )
{
    var propMap = propertyMap ?? new Dictionary<string, string>();
    var entMap = entityMap ?? new Dictionary<string, string>();

    foreach (var entity in modelBuilder.Model.GetEntityTypes())
    {
        foreach (var prop in entity.GetProperties())
        {
            if (propMap.ContainsKey(prop.Name))
            {
                prop.Relational().ColumnName = propMap[prop.Name];
            }
            else
            {
                var underscoredProp = AddUndercoresToSentence(prop.Name, preserveAcronyms);
                prop.Relational().ColumnName = underscoredProp.ToLowerInvariant();
            }
        }

        var entName = entity.DisplayName();

        if (entMap.ContainsKey(entName))
        {
            entity.Relational().TableName = entMap[entName];
        }
        else
        {
            var underscored = AddUndercoresToSentence(entity.DisplayName(), preserveAcronyms);
            entity.Relational().TableName = underscored.ToLowerInvariant();
        }
    }
}

With it query becomes invalid:

SELECT `process`.`correlation_id`
FROM `process`
LEFT JOIN `process_initialization._process_context#_my_process_context` AS `process.ProcessContext` ON `process`.`correlation_id` = `process.ProcessContext`.`process_initialization_correlation_id`
WHERE `process.ProcessContext`.`process_id` = 8

Looks like I need to not apply my transformation to some of entity:

var underscored = AddUndercoresToSentence(entity.DisplayName(), preserveAcronyms);
if (underscored.Contains("#")) // any other way to understand it is special?
    continue;
entity.Relational().TableName = underscored.ToLowerInvariant();

After that I got:

The keys {'ProcessInitializationCorrelationId'} on 'ProcessInitialization.ProcessContext#MyProcessContext' and {'CorrelationId'} on 'ProcessInitialization' are both mapped to 'process_initialization.PK_process_initialization' but with different columns ({'process_initialization_correlation_id'} and {'correlation_id'}).

Body:
Owned types require special processing.

First, you recognize them by using IEntityType.IsOwned() method.

Then, when the entity type is owned, you should skip the table name mapping (because they share the same table as the root owner entity). Also owned types have shadow PK properties which should be skipped, and for other properties you should build column name from the path from root owner to the owned type. The owner information is accessible through DefiningEntityType and DefiningNavigationName properties of IEntityType.

Applying all that to your code:

foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
    foreach (var prop in entity.GetProperties())
    {
        if (entity.IsOwned() && prop.IsPrimaryKey()) continue;
        IEntityType propOwner = entity;
        string propName = prop.Name, columnName = null;
        do
        {
            if (!propMap.TryGetValue(propName, out var name))
                name = AddUndercoresToSentence(propName, preserveAcronyms).ToLowerInvariant();
            columnName = columnName == null ? name : name + "_" + columnName;
            propName = propOwner.DefiningNavigationName;
            propOwner = propOwner.DefiningEntityType;
        }
        while (propName != null);
        prop.Relational().ColumnName = columnName;
    }

    if (entity.IsOwned()) continue;
    var entName = entity.DisplayName();
    if (!entMap.TryGetValue(entName, out var tableName))
        tableName = AddUndercoresToSentence(entName, preserveAcronyms).ToLowerInvariant();
    entity.Relational().TableName = tableName;
}


问:
Is there a way to elegantly "swap" rows in all foreign key and many to many fields in django?
I have a class let's call it Entity it's a container for a label and a type and then I have many other models like Store, Purchase... And they have a relationship like so:

```<code>class Store(Model):
 store_name = TextField()
 entities = ManyToManyField(Entity)

class Purchase(Model):
 datetime = DatetimeField(auto=True)
 entity = ForeignKeyField(Entity)
</code>```

In this case, say that I have an entity that I end up wanting to "swap" for instance, at some time I had "CocaCola" and then I have "Coca Cola", the user decides hey these two are the same, let's "merge them", effectively what I need to do is delete CocaCola or Coca Cola and swap all the keys out

so....

```<code>for p in Purchase.objects.filter(entity=cocacola_entity):
 p.entity = coca_cola_entity
 p.save()
for s in Purchase.objects.filter(entities=cocacola_entity):
 s.entities.remove(cocacola_entity)
 s.entities.add(coca_cola_entity)
 s.save()
cocacola_entity.delete()
</code>```

Is there a better way to handle this in a global context? I.e. "Django magically fetch me EVERYTHING with this row as a foreign key and swap it with the other one)

答:
Django doesn't have anything like this built-in to do this magically. However, you can write a couple of functions to make this easier to do:

```<code>def swap_field(model, field, old_val, new_val):
    """Swaps the field values of a field
    model:   Model class
    field:   Name of the field
    old_val: Old (current) value of the field
    new_val: New value to set on the field
    """

    for obj in model.objects.filter(**{field: old_val}):
        setattr(obj, field, new_val)
        obj.save()

def swap_m2m(model, field, old_val, new_val):
    """Swaps the field values of a ManyToManyField"""

    for obj in model.objects.filter(**{field: old_val}):
        m2m_field = getattr(obj, field)
        m2m_field.add(new_val)
        m2m_field.remove(old_val)
</code>```

Usage:

```<code>swap_field(Purchase, 'entity', cocacola_entity, coca_cola_entity)

swap_m2m(Store, 'entities', cocacola_entity, coca_cola_entity)
</code>```

If you need to update many models, you can make a loop:

```<code>models = [ModelA, ModelB, ModelC, ...]

for model in models:
    swap_m2m(model, 'entities', cocacola_entity, coca_cola_entity)
</code>```

Body:
I have a class let's call it Entity it's a container for a label and a type and then I have many other models like Store, Purchase... And they have a relationship like so:

class Store(Model):
 store_name = TextField()
 entities = ManyToManyField(Entity)

class Purchase(Model):
 datetime = DatetimeField(auto=True)
 entity = ForeignKeyField(Entity)

In this case, say that I have an entity that I end up wanting to "swap" for instance, at some time I had "CocaCola" and then I have "Coca Cola", the user decides hey these two are the same, let's "merge them", effectively what I need to do is delete CocaCola or Coca Cola and swap all the keys out

so....

for p in Purchase.objects.filter(entity=cocacola_entity):
 p.entity = coca_cola_entity
 p.save()
for s in Purchase.objects.filter(entities=cocacola_entity):
 s.entities.remove(cocacola_entity)
 s.entities.add(coca_cola_entity)
 s.save()
cocacola_entity.delete()

Is there a better way to handle this in a global context? I.e. "Django magically fetch me EVERYTHING with this row as a foreign key and swap it with the other one)

Body:
Django doesn't have anything like this built-in to do this magically. However, you can write a couple of functions to make this easier to do:

def swap_field(model, field, old_val, new_val):
    """Swaps the field values of a field
    model:   Model class
    field:   Name of the field
    old_val: Old (current) value of the field
    new_val: New value to set on the field
    """

    for obj in model.objects.filter(**{field: old_val}):
        setattr(obj, field, new_val)
        obj.save()

def swap_m2m(model, field, old_val, new_val):
    """Swaps the field values of a ManyToManyField"""

    for obj in model.objects.filter(**{field: old_val}):
        m2m_field = getattr(obj, field)
        m2m_field.add(new_val)
        m2m_field.remove(old_val)

Usage:

swap_field(Purchase, 'entity', cocacola_entity, coca_cola_entity)

swap_m2m(Store, 'entities', cocacola_entity, coca_cola_entity)

If you need to update many models, you can make a loop:

models = [ModelA, ModelB, ModelC, ...]

for model in models:
    swap_m2m(model, 'entities', cocacola_entity, coca_cola_entity)


问:
NHibernate second-level caching of collections
I am having trouble working out how to correctly cache one-to-many or many-to-many relationships in NHibernate.

For example, an office class may have the following mapping:

```<code>public OfficeDbMap()
{
    ...
    HasMany(x => x.Employees)
        .Cache.NonStrictReadWrite();
}
</code>```

However I find that when I delete an employee (without specifically removing its relationship to the office), that the cache of office->employees does not get invalidated and the employee continues to appear in the office's list of employees.

I suspect it may have something to do with cache regions, but I don't know whether the region should be the office's region or the employee's region (actually I have tried specifying both and neither works).

答:
The problem may be the NonStrictReadWrite configuration.
You have to use the Read-Write strategy.

Body:
I am having trouble working out how to correctly cache one-to-many or many-to-many relationships in NHibernate.

For example, an office class may have the following mapping:

public OfficeDbMap()
{
    ...
    HasMany(x => x.Employees)
        .Cache.NonStrictReadWrite();
}

However I find that when I delete an employee (without specifically removing its relationship to the office), that the cache of office->employees does not get invalidated and the employee continues to appear in the office's list of employees.

I suspect it may have something to do with cache regions, but I don't know whether the region should be the office's region or the employee's region (actually I have tried specifying both and neither works).


问:
why doesn't this $.post() work on iOS?
Why doesn't the following form work on iOS?

It works on Chrome / Android / Windows / Mac but not on Safari / Chrome on iOS.  I've narrowed down the issue to the jquery post function.

It makes it past the "e.preventDefault()" but never posts the data (I have a php script confirming the post never makes it to the server).  And the callback with the alert() does not fire.

```<code><form method="post" action="" id="wl_form">
<div class="form-group">
    <label for="first">First Name *</label>
    <input type="text" name="first" class="form-control" id="first">
</div>
<button name="submit" type="submit" id="submit" class="btn btn-default">Submit</button>
</form>
</code>```

```<code>var form = document.getElementsByTagName('form')[0];

form.addEventListener('submit', doSubmit);

function doSubmit (e) {

    e.preventDefault();

    alert("ive made it this far");

    $.post("record.php",
    {
        first: $("#first").val()
    },
    function(data){
        console.log("submitting");
        alert("Success: " + data);
    });

    window.location.href = "nextpage.html";
}
</code>```

答:
It looks like you are performing a redirect immediately after the post ajax call.  If you perform a page transfer fast enough, the ajax request will be cancelled and your backend may never see it.

As you found from the comments, moving the redirect into the success callback should allow you to perform the ajax request fully and then perform the redirect.

Title: why doesn't this $.post() work on iOS?

Body:
Why doesn't the following form work on iOS?

It works on Chrome / Android / Windows / Mac but not on Safari / Chrome on iOS.  I've narrowed down the issue to the jquery post function.

It makes it past the "e.preventDefault()" but never posts the data (I have a php script confirming the post never makes it to the server).  And the callback with the alert() does not fire.

<form method="post" action="" id="wl_form">

    First Name *
    <input type="text" name="first" class="form-control" id="first">

<button name="submit" type="submit" id="submit" class="btn btn-default">Submit</button>
</form>

var form = document.getElementsByTagName('form')[0];

form.addEventListener('submit', doSubmit);

function doSubmit (e) {

    e.preventDefault();

    alert("ive made it this far");

    $.post("record.php",
    {
        first: $("#first").val()
    },
    function(data){
        console.log("submitting");
        alert("Success: " + data);
    });

    window.location.href = "nextpage.html";
}