问:
Loadbitmap is compiling and working well as x86, but not working when compiling as x64
I am new to C++. This is adapted code by me from a WIN32 API book.
It is working as desired only when x86 mode in debug is on. When there is x64, it is compiling but not working.
I tried to change GWL_HINSTANCE to GWLP_HINSTANCE with no result.</p>

```<code>hBmpBkgr = LoadBitmapW((HINSTANCE)GetWindowLongW(hWnd, GWLP_HINSTANCE), MAKEINTRESOURCEW(IDB_STONE));
hBkBrush = CreatePatternBrush(hBmpBkgr);
SetClassLongW(hWnd, GCLP_HBRBACKGROUND, (LONG)hBkBrush);

hBmpBall = LoadBitmapW((HINSTANCE)GetWindowLongW(hWnd, GWLP_HINSTANCE), MAKEINTRESOURCEW(IDB_BALL));
GetObjectW(hBmpBall, sizeof(bm), (LPSTR)&bm);

hMemDcFrame = CreateCompatibleDC(hdc);
hBmpFrame = CreateCompatibleBitmap(hdc, rect.right, rect.bottom);
SelectObject(hMemDcFrame, hBmpFrame);

SetGraphicsMode(hMemDcFrame, GM_ADVANCED);
</code>```

答:
SetClassLongW:

Replaces the specified 32-bit (long) value at the
  specified offset into the extra class memory or the WNDCLASSEX
  structure for the class to which the specified window belongs.

Note: This function has been superseded by the SetClassLongPtr function. To write code that is compatible with both 32-bit and 64-bit versions of Windows, use SetClassLongPtr.

In addition, [LoadBitmap is available for use in the operating systems specified in the Requirements section. It may be altered or unavailable in subsequent versions. Instead, use LoadImage and DrawFrameControl.]

For more details, please refer: LoadBitmap

Body:
I am new to C++. This is adapted code by me from a WIN32 API book.
It is working as desired only when x86 mode in debug is on. When there is x64, it is compiling but not working.
I tried to change GWL_HINSTANCE to GWLP_HINSTANCE with no result.

hBmpBkgr = LoadBitmapW((HINSTANCE)GetWindowLongW(hWnd, GWLP_HINSTANCE), MAKEINTRESOURCEW(IDB_STONE));
hBkBrush = CreatePatternBrush(hBmpBkgr);
SetClassLongW(hWnd, GCLP_HBRBACKGROUND, (LONG)hBkBrush);

hBmpBall = LoadBitmapW((HINSTANCE)GetWindowLongW(hWnd, GWLP_HINSTANCE), MAKEINTRESOURCEW(IDB_BALL));
GetObjectW(hBmpBall, sizeof(bm), (LPSTR)&bm);

hMemDcFrame = CreateCompatibleDC(hdc);
hBmpFrame = CreateCompatibleBitmap(hdc, rect.right, rect.bottom);
SelectObject(hMemDcFrame, hBmpFrame);

SetGraphicsMode(hMemDcFrame, GM_ADVANCED);


来源: stackexchange

问:
Wait for all items added to buffered channel
I have implemented WaitGroup but it doesn't work as expected, I need to print all 1000 logs but actual result is just ~9xx logs, I know the root cause is the first gorouting hasn't been finished yet while the rest of goroutines in the loop of buffered channel have been done

How do I solve this problem? Thanks in advance

```<code>package main

import (
    "log"
    "sync"
)

func main() {
    buffer := make(chan int, 5)
    var wg sync.WaitGroup
    wg.Add(1)
    go func(wg *sync.WaitGroup) {
        for i := 1; i <= 1000; i++ {
            buffer <- i
        }

        close(buffer)
        wg.Done()
    }(&wg)

    for item := range buffer {
        wg.Add(1)
        go func(wg *sync.WaitGroup, item int) {
            log.Printf("done for item %d\n", item)
            wg.Done()
        }(&wg, item)
    }

    wg.Wait()
}

</code>```

Updated

I found the problem, I run the codes in GoLand IDE and it doesn't print all the logs, if I run in terminal it should be fine

答: I don't see any issue with the waitgroup and it is printing all 1000 logs on go playground.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have implemented WaitGroup but it doesn't work as expected, I need to print all 1000 logs but actual result is just ~9xx logs, I know the root cause is the first gorouting hasn't been finished yet while the rest of goroutines in the loop of buffered channel have been done

How do I solve this problem? Thanks in advance

package main

import (
    "log"
    "sync"
)

func main() {
    buffer := make(chan int, 5)
    var wg sync.WaitGroup
    wg.Add(1)
    go func(wg *sync.WaitGroup) {
        for i := 1; i <= 1000; i++ {
            buffer <- i
        }

        close(buffer)
        wg.Done()
    }(&wg)

    for item := range buffer {
        wg.Add(1)
        go func(wg *sync.WaitGroup, item int) {
            log.Printf("done for item %d\n", item)
            wg.Done()
        }(&wg, item)
    }

    wg.Wait()
}

Updated

I found the problem, I run the codes in GoLand IDE and it doesn't print all the logs, if I run in terminal it should be fine


问:
Android SeekBar with separators
I am making a custom SeekBar as following image.

after searching through internet, I couldn't find the best solution to meet for this issue. The following code is normal SeekBar control and please help me to change like above image.

```<code><SeekBar
 android:id="@+id/seekBar"
 android:layout_width="fill_parent"
 android:layout_height="@dimen/sbumit_form_field_height"
 android:layout_marginTop="@dimen/sbumit_form_field_top_mergin"
 android:layout_marginLeft="@dimen/sbumit_form_field_side_mergin"
 android:layout_marginRight="@dimen/sbumit_form_field_side_mergin"
 android:max="6"/>
</code>```

答:
Whatever you are looking for is here

See here.

It can customize the separator and text, and there are listeners as well.

ContentLicense: CC BY-SA 3.0

Title: Android SeekBar with separators

Body:
I am making a custom SeekBar as following image.

after searching through internet, I couldn't find the best solution to meet for this issue. The following code is normal SeekBar control and please help me to change like above image.

<SeekBar
 android:id="@+id/seekBar"
 android:layout_width="fill_parent"
 android:layout_height="@dimen/sbumit_form_field_height"
 android:layout_marginTop="@dimen/sbumit_form_field_top_mergin"
 android:layout_marginLeft="@dimen/sbumit_form_field_side_mergin"
 android:layout_marginRight="@dimen/sbumit_form_field_side_mergin"
 android:max="6"/>


问:
Best way to plot a 2D square lattice of atoms in Python?
Summary of the problem:
I'm working on a Physics problem and I want to plot a 2D lattice of atoms, where the nodes have been connected using arrows as shown here 2D lattice figure.

What I've tried:
I've tried using grid_2d_graph from NetworkX, taking help from this answer but wasn't able to get it to work as I wanted it to.  The code I used was as follows:

```<code>G = nx.grid_2d_graph(4,4)
pos = dict( (n, n) for n in G.nodes() )
nx.draw_networkx(G, pos=pos)
plt.axis('off')
plt.show()
</code>```

This produced the following image, which wasn't exactly what I had in mind.

答:
Here is a simplistic approach using matplotlib's arrow. It requires, that the grid (graph) is represented as a dictionary where the keys are point (node) coordinates on the grid and the values are neighbouring points to which an outgoing arrow (edge) should be drawn. When the size of your grid changes, you will probably need to play around with w, h and such to control the size of the plotted elements.

grid = {  # point(x, y), outgoing connections [points]
    (0, 0): [(0, 1), (1, 0)],
    (0, 1): [],
    (1, 0): [],
    (1, 1): [(1, 0), (0, 1)]
}

w = 0.005  # Errorwidth
h = 0.05   # Errorhead width

fig, ax = plt.subplots()
for point, connections in grid.items():
    for outgoing in connections:
        dx = outgoing[0] - point[0]
        dy = outgoing[1] - point[1]
        ax.arrow(point[0], point[1],
                 dx / 2, dy / 2,
                 width=w, head_width=h,
                 facecolor="k",
                 zorder=0)
        ax.arrow(point[0] + dx / 2,
                 point[1] + dy / 2,
                 dx / 2, dy / 2,
                 width=w, head_width=0,
                 facecolor="k",
                 zorder=0)
    ax.plot(*point,
            marker="o", markersize=10, markeredgecolor="k",
            markerfacecolor="red",
            zorder=1)
```

Body:
Summary of the problem:
I'm working on a Physics problem and I want to plot a 2D lattice of atoms, where the nodes have been connected using arrows as shown here 2D lattice figure.

What I've tried:
I've tried using grid_2d_graph from NetworkX, taking help from this answer but wasn't able to get it to work as I wanted it to.  The code I used was as follows:

G = nx.grid_2d_graph(4,4)
pos = dict( (n, n) for n in G.nodes() )
nx.draw_networkx(G, pos=pos)
plt.axis('off')
plt.show()

This produced the following image, which wasn't exactly what I had in mind.


问:
Conditional Ajax.Actionlink in Telerik MVC Grid
I have a Telerik ASP.NET  MVC 2.0 Grid on a partialview  . Here in this Grid there is column say " Status" having values as " active " & " inactive". I want to show a delete link in only those rows having Status Column Value as " Active ".

I am rendering this partialview on my main View having a ViewModel and my partialview is rendered using a descriptor .

I tried to use a ClientTemplate / Template but I am not able to put a condtional check before displaying a delete Link . How to achieve this using C# 4.0 ASP.NET4.0 code . I need some sample code . Its very urgent so your help is deeply appreciated .Thanks in advance for going through my problem

答:
Basically, you will most likely need to wrap a conditional block inside the template definition which to determine whether the delete link should be output or not. Check the general templates definitions from the demos below and try this out to see how it goes:

http://demos.telerik.com/aspnet-mvc/razor/grid/templatesclientside
http://demos.telerik.com/aspnet-mvc/razor/grid/templatesserverside


问:
How to speed up a search on large collection of text files (1TB)
I have a collection of text files containing anonymised medical data (age, country, symptoms, diagnosis etc). This data goes back for at least 30 years so as you can imagine I have quite a large sized data set. In total I have around 20,000 text files totalling approx. 1TB.

Periodically I will be needing to search these files for occurances of a particular string (not regex). What is the quickest way to search through this data?

I have tried using grep and recursively searching through the directory as follows:

```<code>LC_ALL=C fgrep -r -i "searchTerm" /Folder/Containing/Files
</code>```

The only problem with doing the above is that it takes hours (sometimes half a day!) to search through this data.

Is there a quicker way to search through this data? At this moment I am open to different approaches such as databases, elasticsearch etc. If I do go down the database route, I will have approx. 1 billion records.

My only requirements are:

1) The search will be happening on my local computer (Dual-Core CPU and 8GB RAM)

2) I will be searching for strings (not regex).

3) I will need to see all occurances of the search string and the file it was within.

答:
Worth covering the topic from at two level: approach, and specific software to use.

Approach:
Based on the way you describe the data, it looks that pre-indexing will provide significant help. Pre-indexing will perform one time scan of the data, and will build a a compact index that make it possible to perform quick searches and identify where specific terms showed in the repository.

Depending on the queries, it the index will reduce or completely eliminate having to search through the actual document, even for complex queries like 'find all documents where AAA and BBB appears together).

Specific Tool

The hardware that you describe is relatively basic. Running complex searches will benefit from large memory/multi-core hardware. There are excellent solutions out there - elastic search, solr and similar tools can do magic, given strong hardware to support them.

I believe you want to look into two options, depending on your skills, and the data (it will help sample of the data can be shared) by OP.
* Build you own index, using light-weight database (sqlite, postgresql), OR
* Use light-weight search engine.

For the second approach, using describe hardware, I would recommended looking into 'glimpse' (and the supporting agrep utility). Glimple provide a way to pre-index the data, which make searches extremely fast. I've used it on big data repository (few GB, but never TB).

See: https://github.com/gvelez17/glimpse

Clearly, not as modern and feature rich as Elastic Search, but much easier to setup. It is server-less. The main benefit for the use case described by OP is the ability to scan existing files, without having to load the documents into extra search engine repository.

Body:
I have a collection of text files containing anonymised medical data (age, country, symptoms, diagnosis etc). This data goes back for at least 30 years so as you can imagine I have quite a large sized data set. In total I have around 20,000 text files totalling approx. 1TB.

Periodically I will be needing to search these files for occurances of a particular string (not regex). What is the quickest way to search through this data?

I have tried using grep and recursively searching through the directory as follows:

LC_ALL=C fgrep -r -i "searchTerm" /Folder/Containing/Files

The only problem with doing the above is that it takes hours (sometimes half a day!) to search through this data.

Is there a quicker way to search through this data? At this moment I am open to different approaches such as databases, elasticsearch etc. If I do go down the database route, I will have approx. 1 billion records.

My only requirements are:

1) The search will be happening on my local computer (Dual-Core CPU and 8GB RAM)

2) I will be searching for strings (not regex).

3) I will need to see all occurances of the search string and the file it was within.


问:
Built-In Azure policy definition
There used to be a Built-In Azure Policy definition called "Require specified tag" that is no longer there. Is there a reason that it was removed with no replacement? Does anyone have the JSON code for this old policy definition?

Much appreciated.

答:
Are you looking for this policy:

```<code>{
  "properties": {
    "displayName": "Require a tag on resources",
    "policyType": "BuiltIn",
    "mode": "Indexed",
    "description": "Enforces existence of a tag. Does not apply to resource groups.",
    "metadata": {
      "version": "1.0.1",
      "category": "Tags"
    },
    "parameters": {
      "tagName": {
        "type": "String",
        "metadata": {
          "displayName": "Tag Name",
          "description": "Name of the tag, such as 'environment'"
        }
      }
    },
    "policyRule": {
      "if": {
        "field": "[concat('tags[', parameters('tagName'), ']')]",
        "exists": "false"
      },
      "then": {
        "effect": "deny"
      }
    }
  },
  "id": "/providers/Microsoft.Authorization/policyDefinitions/871b6d14-10aa-478d-b590-94f262ecfa99",
  "type": "Microsoft.Authorization/policyDefinitions",
  "name": "871b6d14-10aa-478d-b590-94f262ecfa99"
}
</code>```

These policies are present as built-in policies for "Require tags".

Title: Built-In Azure policy definition

Body:
Are you looking for this policy:

{
  "properties": {
    "displayName": "Require a tag on resources",
    "policyType": "BuiltIn",
    "mode": "Indexed",
    "description": "Enforces existence of a tag. Does not apply to resource groups.",
    "metadata": {
      "version": "1.0.1",
      "category": "Tags"
    },
    "parameters": {
      "tagName": {
        "type": "String",
        "metadata": {
          "displayName": "Tag Name",
          "description": "Name of the tag, such as 'environment'"
        }
      }
    },
    "policyRule": {
      "if": {
        "field": "[concat('tags[', parameters('tagName'), ']')]",
        "exists": "false"
      },
      "then": {
        "effect": "deny"
      }
    }
  },
  "id": "/providers/Microsoft.Authorization/policyDefinitions/871b6d14-10aa-478d-b590-94f262ecfa99",
  "type": "Microsoft.Authorization/policyDefinitions",
  "name": "871b6d14-10aa-478d-b590-94f262ecfa99"
}

These policies are present as built-in policies for "Require tags".


问:
MySQL: Is there a way to speed up a left join looking for rows that do not match a row in another table?
I have a query that looks like this:

SELECT * FROM foo
        LEFT JOIN bar
        ON bar.id = foo.bar_id
        WHERE bar.id IS NULL
        LIMIT 30;
```

<p>It's attempting to find entries in <code>foo</code> that have a <code>bar_id</code> that does not have a corresponding entry in <code>bar</code>.</p>

<p>There is an index on <code>foo.bar_id</code> and a unique (incremental) index on <code>bar.id</code></p>

<p>The output of explain looks like this:</p>

```id  select_type table   partitions  type    possible_keys   key key_len ref rows    filtered    Extra
1   SIMPLE  foo NULL    ALL NULL    NULL    NULL    NULL    4411867 100.00  NULL
1   SIMPLE  bar NULL    eq_ref  PRIMARY PRIMARY 4   foo.bar_id  1   100.00  Using where; Not exists
```

<p>(sorry, i've struggled to get the formatting of that table to display very nicely).</p>

<p>This query is sometimes taking 5+ minutes (although for some reason it sometimes takes 30 seconds shortly after running for 5 minutes)</p>

<p>Is there anyway to improve it? Or is it just a hardware limitation?</p>

<hr>

<p>In response to the comments, this version makes no noticeable improvement in terms of performance.</p>

<pre class="lang-sql prettyprint-override"><code>        SELECT foo.* FROM foo
        LEFT JOIN bar
        ON bar.id = foo.bar_id
        WHERE bar.id IS NULL
        ORDER BY foo.id ASC
        LIMIT 30;
</code>```

There is a slight difference when selecting foo.* as opposed to * but in my case I was selecting specific columns anyway, I just did not think to include them in the pseudo example.

答:
No

The query as written must check foo rows until it finds 30 missing rows from bar.  If foo is big, and there aren't many missing rows, that could take a long time.

Maybe

You have SELECT *.  See if it runs faster if it returns only SELECT foo.id.  There is no need for the bar.* part of *; they will always be NULL.  If id is not sufficient, you can use id to get other columns.

Yes

If you are walking through the table picking a few (30) to work on and delete, this is a terribly inefficient way to do it.  It is "Order(N^2)".  I have a much faster way (O(N)), which involves "remembering where you left off":  http://mysql.rjweb.org/doc.php/deletebig#deleting_in_chunks  (That discussion is couched in terms of "deleting in chunks", but it can be adapted to other actions.)

Body:
I have a query that looks like this:

SELECT * FROM foo
        LEFT JOIN bar
        ON bar.id = foo.bar_id
        WHERE bar.id IS NULL
        LIMIT 30;

It's attempting to find entries in foo that have a bar_id that does not have a corresponding entry in bar.

There is an index on foo.bar_id and a unique (incremental) index on bar.id

The output of explain looks like this:

id  select_type table   partitions  type    possible_keys   key key_len ref rows    filtered    Extra
1   SIMPLE  foo NULL    ALL NULL    NULL    NULL    NULL    4411867 100.00  NULL
1   SIMPLE  bar NULL    eq_ref  PRIMARY PRIMARY 4   foo.bar_id  1   100.00  Using where; Not exists

(sorry, i've struggled to get the formatting of that table to display very nicely).

This query is sometimes taking 5+ minutes (although for some reason it sometimes takes 30 seconds shortly after running for 5 minutes)

Is there anyway to improve it? Or is it just a hardware limitation?

In response to the comments, this version makes no noticeable improvement in terms of performance.

        SELECT foo.* FROM foo
        LEFT JOIN bar
        ON bar.id = foo.bar_id
        WHERE bar.id IS NULL
        ORDER BY foo.id ASC
        LIMIT 30;

There is a slight difference when selecting foo.* as opposed to * but in my case I was selecting specific columns anyway, I just did not think to include them in the pseudo example.


问:
Postgresql error on inserting new row 'PG::NotNullViolation: ERROR: null value in column "id" violates not-null constraint'
I am just migrate my us server to an eu region on heroku, and restore the old database backup to new server. Unfortunately I am getting following error while try to insert an new row to one of table

```<code>INSERT INTO "users" ("created_at", "id", ...) VALUES ($1, $2, ...) [["created_at", Thu, 13 Oct 2016 23:53:17 CEST +02:00], ["id", nil], ...]

ActiveRecord::StatementInvalid: PG::NotNullViolation: ERROR: null value in column "id" violates not-null constraint

DETAIL: Failing row contains (null, ...)
</code>```

My schema looks like following

```<code>create_table "users", :id => false, :force => true do |t|
   t.integer  "id",          :null => false
   t.datetime "created_at",  :null => false
   ...
end
</code>```

How can I solve this issue?

答:
I had the same weird problem, and got it solved by a slight variant of your first solution:

```<code>rake db:drop
</code>```

Then

```<code>rake db:migrate:reset
</code>```

And finally

```<code>pg_restore --verbose --data-only --disable-triggers --no-acl --no-owner -h localhost -U user_name -d database_name latest.dump
</code>```

This way, it keeps the database structure, only restores the data, but, by not checking the foreign key constraints, it can load the tables, and doesn't end with a bunch of empty tables...

Body:
I am just migrate my us server to an eu region on heroku, and restore the old database backup to new server. Unfortunately I am getting following error while try to insert an new row to one of table

INSERT INTO "users" ("created_at", "id", ...) VALUES ($1, $2, ...) [["created_at", Thu, 13 Oct 2016 23:53:17 CEST +02:00], ["id", nil], ...]

ActiveRecord::StatementInvalid: PG::NotNullViolation: ERROR: null value in column "id" violates not-null constraint

DETAIL: Failing row contains (null, ...)

My schema looks like following

create_table "users", :id => false, :force => true do |t|
   t.integer  "id",          :null => false
   t.datetime "created_at",  :null => false
   ...
end

How can I solve this issue?

Body:
I had the same weird problem, and got it solved by a slight variant of your first solution:

rake db:drop

Then

rake db:migrate:reset

And finally

pg_restore --verbose --data-only --disable-triggers --no-acl --no-owner -h localhost -U user_name -d database_name latest.dump

This way, it keeps the database structure, only restores the data, but, by not checking the foreign key constraints, it can load the tables, and doesn't end with a bunch of empty tables...


问:
User input boolean in python
I am trying to have a user input whether or not they like spicy food and the output is supposed to be a boolean but I don't seem to be getting an output with my code below:</p>

```<code>def likes_spicyfood():
    spicyfood = bool(input("Do you like spicy food? True or False?"))
    if spicyfood == ("True"):
        print("True")
    if spicyfood == ("False"):
        print("False")
        return(likes_spicyfood)
</code>```

答:
First we'll need to read the user's input after they read the question:

hungry = input("Are you hungry? True or False \n")
```

<p>Now that we have their response in a variable, <code>hungry</code>, we're able to use it in some statements:</p>

```if hungry.lower() == "true":
```

<p>Notice the use of <code>.lower()</code>, which will take their string, regardless of capitalisation of letters, and convert it all to lowercase. This means that whether they enter <code>"True"</code>, <code>"tRue"</code> or <code>"TRUE"</code>, they will all evaluate to being <code>True</code> if compared to the lowercase counterpart <code>"true"</code>.  </p>

<p>What's important when doing this, is to always have your comparison string be lowercase as well. because if you tried evaluating <code>"true"</code> against <code>"True"</code>, it would return <code>False</code>.</p>

<p>Using this knowledge, we're able to put it all together and print out what we want:</p>

<pre class="lang-py prettyprint-override"><code>hungry = input("Are you hungry? True or false \n")

if hungry.lower() == "true":
    print("Feed me!")
else:
    print("I'm not hungry.")
</code>```

Title: User input boolean in python

Body:
I am trying to have a user input whether or not they like spicy food and the output is supposed to be a boolean but I don't seem to be getting an output with my code below:

def likes_spicyfood():
    spicyfood = bool(input("Do you like spicy food? True or False?"))
    if spicyfood == ("True"):
        print("True")
    if spicyfood == ("False"):
        print("False")
        return(likes_spicyfood)

Body:
First we'll need to read the user's input after they read the question:

hungry = input("Are you hungry? True or False \n")

Now that we have their response in a variable, hungry, we're able to use it in some statements:

if hungry.lower() == "true":

Notice the use of .lower(), which will take their string, regardless of capitalisation of letters, and convert it all to lowercase. This means that whether they enter "True", "tRue" or "TRUE", they will all evaluate to being True if compared to the lowercase counterpart "true".

What's important when doing this, is to always have your comparison string be lowercase as well. because if you tried evaluating "true" against "True", it would return False.

Using this knowledge, we're able to put it all together and print out what we want:

hungry = input("Are you hungry? True or false \n")

if hungry.lower() == "true":
    print("Feed me!")
else:
    print("I'm not hungry.")


问:
Exporting data from multiple SQL tables to different flat files using SSIS Script Task
I am trying to create a datagrid and export the contents to a text file using VB.NET and I am doing this inside an SSIS script task in order to automate the process to export a dynamic table to text file. I don't get any error and the files are created but the files are empty.

What am I doing wrong here in this code?

```<code>Public Sub Main()

    Dim FName As String = "D:\test.TXT"

    ''''''''''''''''''''''''''''''''''''''''''
    If File.Exists(FName) Then
        File.Delete(FName)
    End If
    ''''''''''''''''''''''''''''''''''''''''''

    Dim myConnection As OleDbConnection = New OleDbConnection("Data Source=localhost;Provider=SQLNCLI10;Initial Catalog=AdventureWorksDW2008R2;Integrated Security=SSPI;")
    Dim da As OleDbDataAdapter = New OleDbDataAdapter("Select * from Table")
    Dim ds As DataSet = New DataSet

    da.Fill(ds, "Test")

    Dim DataGrid1 As New DataGrid
    DataGrid1.DataSource = ds.DefaultViewManager
    Dim DataGridView1 As New DataGridView

    DataGridView1.DataSource = ds

    Dim dgvc As DataGridViewCell
    Dim sw As New System.IO.StreamWriter(FName)

    For Each dgvr As DataGridViewRow In DataGridView1.Rows

        Dim intCellCount As Integer = dgvr.Cells.Count
        Dim intCounter As Integer = 1

        For Each dgvc In dgvr.Cells()
            If intCounter <> intCellCount Then
                sw.Write(dgvc.Value.ToString & "|")
            Else
                sw.WriteLine(dgvc.Value.ToString)
            End If

            intCounter += 1
        Next
    Next

    Dts.TaskResult = ScriptResults.Success

End Sub
</code>```

答: Why don't you use an OLEDB source component, put your table query in there and then output it to a flat file writer in SSIS instead of using a script component? This blog post illustrates how to do this.</p>

Body:
I am trying to create a datagrid and export the contents to a text file using VB.NET and I am doing this inside an SSIS script task in order to automate the process to export a dynamic table to text file. I don't get any error and the files are created but the files are empty.

What am I doing wrong here in this code?

Public Sub Main()

    Dim FName As String = "D:\test.TXT"

    ''''''''''''''''''''''''''''''''''''''''''
    If File.Exists(FName) Then
        File.Delete(FName)
    End If
    ''''''''''''''''''''''''''''''''''''''''''

    Dim myConnection As OleDbConnection = New OleDbConnection("Data Source=localhost;Provider=SQLNCLI10;Initial Catalog=AdventureWorksDW2008R2;Integrated Security=SSPI;")
    Dim da As OleDbDataAdapter = New OleDbDataAdapter("Select * from Table")
    Dim ds As DataSet = New DataSet

    da.Fill(ds, "Test")

    Dim DataGrid1 As New DataGrid
    DataGrid1.DataSource = ds.DefaultViewManager
    Dim DataGridView1 As New DataGridView

    DataGridView1.DataSource = ds

    Dim dgvc As DataGridViewCell
    Dim sw As New System.IO.StreamWriter(FName)

    For Each dgvr As DataGridViewRow In DataGridView1.Rows

        Dim intCellCount As Integer = dgvr.Cells.Count
        Dim intCounter As Integer = 1

        For Each dgvc In dgvr.Cells()
            If intCounter <> intCellCount Then
                sw.Write(dgvc.Value.ToString & "|")
            Else
                sw.WriteLine(dgvc.Value.ToString)
            End If

            intCounter += 1
        Next
    Next

    Dts.TaskResult = ScriptResults.Success

End Sub


答:
but it's already happening.

As it's not ordered properly, I think it's misleading to you think that it's only printing ~9xx logs.

I ran it and I got (Full output not shown):

```<code>2020/06/03 10:38:35 done for item 986
2020/06/03 10:38:35 done for item 988
2020/06/03 10:38:35 done for item 1000
2020/06/03 10:38:35 done for item 995
2020/06/03 10:38:35 done for item 993
2020/06/03 10:38:35 done for item 996
2020/06/03 10:38:35 done for item 997
2020/06/03 10:38:35 done for item 991
2020/06/03 10:38:35 done for item 998
2020/06/03 10:38:35 done for item 990
2020/06/03 10:38:35 done for item 992
2020/06/03 10:38:35 done for item 999
2020/06/03 10:38:35 done for item 989
2020/06/03 10:38:35 done for item 412
</code>```

Notice: 1000 is there.

If you want to confirm:

go run main.go &> sample.txt // Redirects the output of the executable to sample.txt
cat sample.txt | wc -l       // Counts the number of lines in output
```

It's 1000.

Title: Wait for all items added to buffered channel

Body:
but it's already happening.

As it's not ordered properly, I think it's misleading to you think that it's only printing ~9xx logs.

I ran it and I got (Full output not shown):

2020/06/03 10:38:35 done for item 986
2020/06/03 10:38:35 done for item 988
2020/06/03 10:38:35 done for item 1000
2020/06/03 10:38:35 done for item 995
2020/06/03 10:38:35 done for item 993
2020/06/03 10:38:35 done for item 996
2020/06/03 10:38:35 done for item 997
2020/06/03 10:38:35 done for item 991
2020/06/03 10:38:35 done for item 998
2020/06/03 10:38:35 done for item 990
2020/06/03 10:38:35 done for item 992
2020/06/03 10:38:35 done for item 999
2020/06/03 10:38:35 done for item 989
2020/06/03 10:38:35 done for item 412

Notice: 1000 is there.

If you want to confirm:

go run main.go &> sample.txt // Redirects the output of the executable to sample.txt
cat sample.txt | wc -l       // Counts the number of lines in output

It's 1000.


问:
How to dynamically add a pair of text input and textarea in Angular 8?
The following piece of html is from our angular page where a user is supposed to introduce a question and its respective answer (something like Q&A thing).

```<code> <mat-card>
           <button mat-stroked-button color="primary" style="margin-right: 20px;">
               Add a new Q & A pair
            </button>
            </mat-card>
            <div *ngFor="let qna of interview.qnas">
                <mat-card id="{{qna.id}}" style="margin-bottom: 25px;">
                    <mat-form-field>
                        <input matInput type="text" class="form-control" placeholder="Interview question" required [(ngModel)]="qna.question" name="question">
                    </mat-form-field>
                    <mat-form-field>
                        <textarea matInput rows="5" class="form-control" placeholder="Ideal answer from the talent" [(ngModel)]="qna.answer" name="answer"></textarea>
                    </mat-form-field>
                    <button mat-stroked-button color="warn">
                        Remove this
                    </button>
                </mat-card>
            </div>
</code>```

As you can see in the HTML, there are two buttons in there, the first button is supposed to let users add a new pair of  and  and the 2nd one is supposed to remove a pair. I can probably come up with a solution for removing the pair but I am not so sure how to implement adding a new Q&A pair on the fly when the user clicks on it. Also, please consider that we have two-way binding in place too.

答:
<mat-card>
    <button mat-stroked-button color="primary" style="margin-right: 20px;"
            (click)="addQnApair()">
        Add a new Q & A pair
    </button>
</mat-card>

    <mat-card id="{{qna.id}}" style="margin-bottom: 25px;">
        <mat-form-field>
            <input matInput type="text" class="form-control"
                   placeholder="Interview question" required [(ngModel)]="qna.question"
                   name="question">
        </mat-form-field>
        <mat-form-field>
                        <textarea matInput rows="5" class="form-control"
                                  placeholder="Ideal answer from the talent" [(ngModel)]="qna.answer"
                                  name="answer"></textarea>
        </mat-form-field>
        <button mat-stroked-button color="warn"
                (click)="removeQnApair(i)">
            Remove this
        </button>
    </mat-card>

```

<p>In ts file</p>

<pre class="lang-js prettyprint-override"><code>removeQnApair(i) {
    this.interview.qnas.splice(i,1);
     }

addQnApair(){
   this.interview.qnas.push({id: this.interview.qnas.length+1,
                question: '',
                answer: ''});
   }
</code>```

Body:
The following piece of html is from our angular page where a user is supposed to introduce a question and its respective answer (something like Q&A thing).

 <mat-card>
           <button mat-stroked-button color="primary" style="margin-right: 20px;">
               Add a new Q & A pair
            </button>
            </mat-card>

                <mat-card id="{{qna.id}}" style="margin-bottom: 25px;">
                    <mat-form-field>
                        <input matInput type="text" class="form-control" placeholder="Interview question" required [(ngModel)]="qna.question" name="question">
                    </mat-form-field>
                    <mat-form-field>
                        <textarea matInput rows="5" class="form-control" placeholder="Ideal answer from the talent" [(ngModel)]="qna.answer" name="answer"></textarea>
                    </mat-form-field>
                    <button mat-stroked-button color="warn">
                        Remove this
                    </button>
                </mat-card>

As you can see in the HTML, there are two buttons in there, the first button is supposed to let users add a new pair of  and  and the 2nd one is supposed to remove a pair. I can probably come up with a solution for removing the pair but I am not so sure how to implement adding a new Q&A pair on the fly when the user clicks on it. Also, please consider that we have two-way binding in place too.

Body:
<mat-card>
    <button mat-stroked-button color="primary" style="margin-right: 20px;"
            (click)="addQnApair()">
        Add a new Q & A pair
    </button>
</mat-card>
<div *ngFor="let qna of interview.qnas; let i= index">
    <mat-card id="{{qna.id}}" style="margin-bottom: 25px;">
        <mat-form-field>
            <input matInput type="text" class="form-control"
                   placeholder="Interview question" required [(ngModel)]="qna.question"
                   name="question">
        </mat-form-field>
        <mat-form-field>
                        <textarea matInput rows="5" class="form-control"
                                  placeholder="Ideal answer from the talent" [(ngModel)]="qna.answer"
                                  name="answer"></textarea>
        </mat-form-field>
        <button mat-stroked-button color="warn"
                (click)="removeQnApair(i)">
            Remove this
        </button>
    </mat-card>
</div>

In ts file

removeQnApair(i) {
    this.interview.qnas.splice(i,1);
     }

addQnApair(){
   this.interview.qnas.push({id: this.interview.qnas.length+1,
                question: '',
                answer: ''});
   }


问:
Complex For & If loop confusion, returning and accessing classes. Objective-C
I have a view which has a number of subviews. I need to find a particular UIImageView with a particular UIImage.

Here is the code I'm using to loop through:

```<code>BOOL fileExistsAtLocation;
for (id subview in drawGallery.subviews){
    if ([[subview class] isSubclassOfClass: [UIImageView class]]){
        // I need to detect the subview's image property to see if it matches.
    }
}
</code>```

I've tried

```<code>if(subview.image == [UIImage imageNamed:image]){

}
</code>```

But I'm getting told that image isn't part of the structure, which is understandable as all the subviews are essentially of UIView type. How do I target only the UIImageViews and then check their image property?

Regarding the 'tag' answer, the code I tried was:

```<code>BOOL fileIsAtLocation;
for (id subview in drawGallery.subviews){
    if ([subview isKindOfClass:[UIImageView class]]){
        if ((UIView *)subview.tag){
            NSLog(@"FOUND");
        }
    }
}
</code>```

答:
[UIImage imageNamed:image] will return a new instance of that image so it will NEVER be equal.  I'd suggest tagging all of your subviews.  So when you create the image views, assign a unique tag (this could just be an auto incrementing number).  Then you can detect of interest based on the tag.

```<code>BOOL fileExistsAtLocation;
for (id subview in drawGallery.subviews){
    if ([subView isKindOfClass:[UIImageView class]){
        // I need to detect the subview's image property to see if it matches.
        if([(UIView *)subView tag] == uniqueIDAssignedToImage) {
            // You have found your view
        }
    }
}
</code>```

Also use isKindOfClass to check the class type.

Hope this helps.

Body:
I have a view which has a number of subviews. I need to find a particular UIImageView with a particular UIImage.

Here is the code I'm using to loop through:

BOOL fileExistsAtLocation;
for (id subview in drawGallery.subviews){
    if ([[subview class] isSubclassOfClass: [UIImageView class]]){
        // I need to detect the subview's image property to see if it matches.
    }
}

I've tried

if(subview.image == [UIImage imageNamed:image]){

}

But I'm getting told that image isn't part of the structure, which is understandable as all the subviews are essentially of UIView type. How do I target only the UIImageViews and then check their image property?

Regarding the 'tag' answer, the code I tried was:

BOOL fileIsAtLocation;
for (id subview in drawGallery.subviews){
    if ([subview isKindOfClass:[UIImageView class]]){
        if ((UIView *)subview.tag){
            NSLog(@"FOUND");
        }
    }
}

Body:
[UIImage imageNamed:image] will return a new instance of that image so it will NEVER be equal.  I'd suggest tagging all of your subviews.  So when you create the image views, assign a unique tag (this could just be an auto incrementing number).  Then you can detect of interest based on the tag.

BOOL fileExistsAtLocation;
for (id subview in drawGallery.subviews){
    if ([subView isKindOfClass:[UIImageView class]){
        // I need to detect the subview's image property to see if it matches.
        if([(UIView *)subView tag] == uniqueIDAssignedToImage) {
            // You have found your view
        }
    }
}

Also use isKindOfClass to check the class type.

Hope this helps.


问:
Promise in Angular 9
I'm trying to write a synchronous function call in Angular using a Promise, but it still gets a different result than expected.
I have 2 functions that use the service that download data from the API:

```<code>getData1(shortcut: string): void {
  this.apiServ.getPrice(shortcut).subscribe(
    (price: CurrentPrice) => {
      this.price = price;
      console.log(1);
    },
    error => this.error = error
  );
}

getData2(shortcut: string): void {
  this.apiServ.getPrice(shortcut).subscribe(
    (price: CurrentPrice) => {
      this.price = price;
      console.log(2);
    },
    error => this.error = error
  );
}
</code>```

I'm trying to make the next function call after the response is completed. So:

```<code>data(shortcuts) {
  this.getData1(shortcuts[0]);
  this.getData2(shortcuts[1]);
}

ngOnInit() {
  const myPromise = new Promise((resolve) => {
    this.data(this.shortcuts);
    resolve(3)
  });
  myPromise.then((value) => {console.log(value)});
}

</code>```

But my browser prints this call order:

```<code>3
1
2
</code>```

What am I doing wrong?

I also tried to use callbacks but the effect is always the same.

答:
You could use zip from rxjs:

import { Observable, zip } from 'rxjs';
import { tap } from 'rxjs/operators';

```<code>getData1(shortcut: string): Observable<any>  {
  return this.apiServ.getPrice(shortcut).pipe(
    tap(
      (price: CurrentPrice) => {
        this.price = price;
        console.log(1);
      }
    )
  );
}

getData2(shortcut: string): Observable<any>  {
  return this.apiServ.getPrice(shortcut).pipe(
    tap(
      (price: CurrentPrice) => {
        this.price = price;
        console.log(2);
      }
    )
  );
}

data(shortcuts) : Observable<any> {
  const res1 = this.getData1(shortcuts[0]);
  const res2 = this.getData2(shortcuts[1]);
  return zip(res1, res2);
}

ngOnInit() {
  this.data(this.shortcuts).subscribe(() => {
    // your code
  })
}
</code>```

Title: Promise in Angular 9

Body:
I'm trying to write a synchronous function call in Angular using a Promise, but it still gets a different result than expected.
I have 2 functions that use the service that download data from the API:

getData1(shortcut: string): void {
  this.apiServ.getPrice(shortcut).subscribe(
    (price: CurrentPrice) => {
      this.price = price;
      console.log(1);
    },
    error => this.error = error
  );
}

getData2(shortcut: string): void {
  this.apiServ.getPrice(shortcut).subscribe(
    (price: CurrentPrice) => {
      this.price = price;
      console.log(2);
    },
    error => this.error = error
  );
}

I'm trying to make the next function call after the response is completed. So:

data(shortcuts) {
  this.getData1(shortcuts[0]);
  this.getData2(shortcuts[1]);
}

ngOnInit() {
  const myPromise = new Promise((resolve) => {
    this.data(this.shortcuts);
    resolve(3)
  });
  myPromise.then((value) => {console.log(value)});
}

But my browser prints this call order:

3
1
2

What am I doing wrong?

I also tried to use callbacks but the effect is always the same.

Body:
You could use zip from rxjs:

import { Observable, zip } from 'rxjs';
import { tap } from 'rxjs/operators';

getData1(shortcut: string): Observable<any>  {
  return this.apiServ.getPrice(shortcut).pipe(
    tap(
      (price: CurrentPrice) => {
        this.price = price;
        console.log(1);
      }
    )
  );
}

getData2(shortcut: string): Observable<any>  {
  return this.apiServ.getPrice(shortcut).pipe(
    tap(
      (price: CurrentPrice) => {
        this.price = price;
        console.log(2);
      }
    )
  );
}

data(shortcuts) : Observable<any> {
  const res1 = this.getData1(shortcuts[0]);
  const res2 = this.getData2(shortcuts[1]);
  return zip(res1, res2);
}

ngOnInit() {
  this.data(this.shortcuts).subscribe(() => {
    // your code
  })
}


问:
Cannot show json data in dropdown list jquery
I am getting json data from my php code something like this :

{2: "Robert ", 3: "Adem"}

Now i want to show it in dropdown list using jQuery I'm using the following code but 'm getting object in dropdown.

```<code>jQuery(response).each(function (index, value) {
  jQuery("#name").append(jQuery("<option>").val(value).text(value));
});
</code>```

答:
If the response coming from your PHP file is a JSON string then you will have to convert it into a javascript array then iterate it to get your option

use JSON.parse();

```<code>var options = JSON.parse(JSON.stringify(response));

jQuery.each( options, function( index, value ) {
   $('#name').append('<option value="'+index+'">'+value+'</option>');
});
</code>```

Body:
I am getting json data from my php code something like this :

{2: "Robert ", 3: "Adem"}

Now i want to show it in dropdown list using jQuery I'm using the following code but 'm getting object in dropdown.

jQuery(response).each(function (index, value) {
  jQuery("#name").append(jQuery("<option>").val(value).text(value));
});

Body:
If the response coming from your PHP file is a JSON string then you will have to convert it into a javascript array then iterate it to get your option

use JSON.parse();

var options = JSON.parse(JSON.stringify(response));

jQuery.each( options, function( index, value ) {
   $('#name').append('<option value="'+index+'">'+value+'</option>');
});


问:
React Native create class with key-value pair props
```<code>class Adder extends Component {
  constructor(props) {
    super(props)
    this.props.callback(this.props.valueA + this.props.valueB)
  }
}
</code>```

In JSX I can do this:

```<code><Adder callback={this.resultFunc} valueA={4} valueB={2}/>
</code>```

I don't know the syntax in JS, for instance this doesn't work. I only get the first argument passed:

```<code>this.myAdder = new Adder({callback:this.resultFunc},{valueA:4},{valueB:2});
</code>```

Anything but the first KV pair is undefined in the Adder class.
Can anyone please point me right? Thanks!

答: You should have only one object: new Adder({callback:this.resultFunc, valueA:4, valueB:2}) this will be your props.</p>

Body:
class Adder extends Component {
  constructor(props) {
    super(props)
    this.props.callback(this.props.valueA + this.props.valueB)
  }
}

In JSX I can do this:

<Adder callback={this.resultFunc} valueA={4} valueB={2}/>

I don't know the syntax in JS, for instance this doesn't work. I only get the first argument passed:

this.myAdder = new Adder({callback:this.resultFunc},{valueA:4},{valueB:2});

Anything but the first KV pair is undefined in the Adder class.
Can anyone please point me right? Thanks!


问:
Endpoint Not found MVC
I'm working with a very weird endpoint,
Now the data I post to my endpoint is the scorecardId and the DashboardConfig and the rest of my data is populated via the backend, which is the UserId and the DateCreated, Now I need to do a get request for the specific user and I did something like this:

```<code>#region Public Methods
        [HttpGet]
        [Route("GetbyUserID")]
        [ValidateModel]
        public IHttpActionResult GetbyUserID(Guid UserID)
        {
            UserID = this.GetUserId();
            var config = _prefentialDashboardConfigService.GetByUserID(UserID);
            return Ok(config);
        }
</code>```

My model:

```<code>    public Guid ScorecardId { get; set; }

    public Guid UserId { get; set; }

    public DateTime DateCreated { get; set; }

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

My CRUD:

```<code>        public PrefentialDashboardConfig GetByUserID(System.Guid UserId, params string[] includes)
    {
        return Repository.SingleOrDefault<PrefentialDashboardConfig>(config => config.UserId == UserId, includes);
    }
}
</code>```

My ICRUD:

```<code>        T SingleOrDefault<T>(Expression<Func<T, bool>> where, params string[] includes) where T : class;
</code>```

And in my front end I just called the get request but it gives me a 404 resource not found error. I call my end point like this in knockout:

```<code>var test = PreferentialProcurementDashboardApi.GetbyUserID();
//For testing purposes
console.log("You got it right!" + JSON.stringify(test));
</code>```

What would be the best way to get my data to the frontend console by the UserId which is taken from my backend?

答:
only guessing, you are probably not passing the UserId when you are doing the http get request.

```<code>var test = PreferentialProcurementDashboardApi.GetbyUserID();
</code>```

probably should be

```<code>var test = PreferentialProcurementDashboardApi.GetbyUserID(5);
</code>```

check the network tab in the browser dev tools to make sure that there are parameters are being passed to the backend

Title: Endpoint Not found MVC

Body:
I'm working with a very weird endpoint,
Now the data I post to my endpoint is the scorecardId and the DashboardConfig and the rest of my data is populated via the backend, which is the UserId and the DateCreated, Now I need to do a get request for the specific user and I did something like this:

#region Public Methods
        [HttpGet]
        [Route("GetbyUserID")]
        [ValidateModel]
        public IHttpActionResult GetbyUserID(Guid UserID)
        {
            UserID = this.GetUserId();
            var config = _prefentialDashboardConfigService.GetByUserID(UserID);
            return Ok(config);
        }

My model:

    public Guid ScorecardId { get; set; }

    public Guid UserId { get; set; }

    public DateTime DateCreated { get; set; }

    public string DashboardConfig { get; set; }

My CRUD:

        public PrefentialDashboardConfig GetByUserID(System.Guid UserId, params string[] includes)
    {
        return Repository.SingleOrDefault<PrefentialDashboardConfig>(config => config.UserId == UserId, includes);
    }
}

My ICRUD:

        T SingleOrDefault<T>(Expression<Func<T, bool>> where, params string[] includes) where T : class;

And in my front end I just called the get request but it gives me a 404 resource not found error. I call my end point like this in knockout:

var test = PreferentialProcurementDashboardApi.GetbyUserID();
//For testing purposes
console.log("You got it right!" + JSON.stringify(test));

What would be the best way to get my data to the frontend console by the UserId which is taken from my backend?

Body:
only guessing, you are probably not passing the UserId when you are doing the http get request.

var test = PreferentialProcurementDashboardApi.GetbyUserID();

probably should be

var test = PreferentialProcurementDashboardApi.GetbyUserID(5);

check the network tab in the browser dev tools to make sure that there are parameters are being passed to the backend


问:
Reuse same DOM element in two different react components
I have a small question.

Let's imagine I have component A which holds , after component A does it's job I render component B. I would like that same DOM element (textarea) would be reused in component B.
The reason is if new textarea is rendered in component B it loses focus as it's just new DOM element. It's like after component A lifetame take textarea element from it and just put it in component B instead of rendering new one.

Sample APP
https://jsfiddle.net/remdex/v67gqyLa/1/#&togetherjs=aiRvTGhRK2

class AComponent extends React.Component {
  render() {
      return ( <textarea>A Component</textarea>  )
 }
}

class BComponent extends React.Component {
  render() {
      return ( <textarea>Should be A Component text</textarea>  )
 }
}

class ABComponent extends React.Component {
  constructor(props) {
    super(props)
    this.state = {'component' : 'A'};
  }

  render() {
    return (

<button onClick={(e) => this.setState({component:'B'})}>Switch to B Component</button>
      {this.state.component == 'A' && <AComponent/>}
      {this.state.component == 'B' && <BComponent/>}

    )
  }
}

ReactDOM.render(<ABComponent />, document.querySelector("#app"))```

答:
This can be achieved using a ref. ABComponent passes a ref to BComponent to attach to the textarea. When the state of ABComponent updates to component = 'B', then the ref is used to set focus. Use a ref passed to AComponent to grab its textarea value before it's unmounted, then set the value of the textarea in B to it.

```<code>import React, { Component, createRef } from "react";

...

class AComponent extends Component {
  render() {
    const { textareaRef } = this.props;
    return <textarea ref={textareaRef} defaultValue="A Component" />;
  }
}

class BComponent extends Component {
  render() {
    const { textareaRef } = this.props;
    return <textarea ref={textareaRef} defaultValue="Should be A Component text" />;
  }
}

class ABComponent extends Component {
  state = { component: "A" };
  refA = createRef();
  refB = createRef();

  componentDidUpdate(prevProps, prevState) {
    const { component, content } = this.state;
    if (prevState.component !== component) {
      if (component === "B") {
        this.refB.current.focus();
        this.refB.current.value = content;
      }
    }
  }

  render() {
    return (
      <div>
        <button
          onClick={e =>
            this.setState({ component: "B", content: this.refA.current.value })
          }
        >
          Switch to B Component
        </button>
        {this.state.component === "A" && <AComponent textareaRef={this.refA} />}
        {this.state.component === "B" && <BComponent textareaRef={this.refB} />}
      </div>
    );
  }
}
</code>```

Body:
This can be achieved using a ref. ABComponent passes a ref to BComponent to attach to the textarea. When the state of ABComponent updates to component = 'B', then the ref is used to set focus. Use a ref passed to AComponent to grab its textarea value before it's unmounted, then set the value of the textarea in B to it.

import React, { Component, createRef } from "react";

...

class AComponent extends Component {
  render() {
    const { textareaRef } = this.props;
    return <textarea ref={textareaRef} defaultValue="A Component" />;
  }
}

class BComponent extends Component {
  render() {
    const { textareaRef } = this.props;
    return <textarea ref={textareaRef} defaultValue="Should be A Component text" />;
  }
}

class ABComponent extends Component {
  state = { component: "A" };
  refA = createRef();
  refB = createRef();

  componentDidUpdate(prevProps, prevState) {
    const { component, content } = this.state;
    if (prevState.component !== component) {
      if (component === "B") {
        this.refB.current.focus();
        this.refB.current.value = content;
      }
    }
  }

  render() {
    return (
      <div>
        <button
          onClick={e =>
            this.setState({ component: "B", content: this.refA.current.value })
          }
        >
          Switch to B Component
        </button>
        {this.state.component === "A" && <AComponent textareaRef={this.refA} />}
        {this.state.component === "B" && <BComponent textareaRef={this.refB} />}
      </div>
    );
  }
}


问:
Build Fails: `npm rebuild node-sass --force`
Using n to switch Node versions.
I've ran yarn, npm rebuild node-sass --force many many times. And still fails. Getting this error:

Node Sass could not find a binding for your current environment

```<code>This usually happens because your environment has changed since running `npm install`.
Run `npm rebuild node-sass --force` to build the binding for your current environment.
</code>```

Anyone have any idea how to fix?

Also..
When running this command..

```<code>npm rebuild node-sass --force
</code>```

I get..

```<code>npm WARN using --force I sure hope you know what you are doing.
</code>```

Doens't seem like it is doing anything..

答:
We are also facing the same issue many times, due to different versions of node and npm for numbers of web applications.

For that, we are just using the below command to take proper node-sass supported versions.

npm install node-sass or npm install node-sass -g

then try to rebuild the node-sass with,

npm rebuild node-sass or npm rebuild node-sass -f

After that all, if required then we can rebuild all packages and npm start or npm run watch and then the application is working properly.

Body:
Using n to switch Node versions.
I've ran yarn, npm rebuild node-sass --force many many times. And still fails. Getting this error:

Node Sass could not find a binding for your current environment

This usually happens because your environment has changed since running `npm install`.
Run `npm rebuild node-sass --force` to build the binding for your current environment.

Anyone have any idea how to fix?

Also..
When running this command..

npm rebuild node-sass --force

I get..

npm WARN using --force I sure hope you know what you are doing.

Doens't seem like it is doing anything..


问:
Why is Pandas' whitespace delimiter skipping one of my values?
I'm currently trying to use Python read a text file into Sqlite3 using Pandas. Here are a few entries from the text file:

```<code>1  Michael  462085  2.2506  Jessica  302962  1.5436
2  Christopher  361250  1.7595  Ashley  301702  1.5372
3  Matthew  351477  1.7119  Emily  237133  1.2082
</code>```

The data consists of popular baby names, and I have to separate male names and female names into their own tables and perform queries on them. My method consists of first placing all the data into both tables, then dropping the unneeded columns afterwards. My issue is that when I try to add names to the columns, I get a value error: The expected axis has 6 elements, but 7 values. I'm assuming it's because Pandas possibly isn't reading the last values of each line, but I can't figure out how to fix it. My current delimiter is a whitespace delimiter that you can see below.

Here is my code:

```<code>import sqlite3
import pandas as pd
import csv

con = sqlite3.connect("C:\\****\\****\\****\\****\\****\baby_names.db")
c=con.cursor()

# Please note that most of these functions will be commented out, because they will only be run once.

def create_and_insert():
    # load data
    df = pd.read_csv('babynames.txt', index_col=0, header=None, sep= '\s+', engine = 'python')
    # Reading the textfile

    df.columns = ['Rank', 'BoyName', 'Boynumber', 'Boypercent', 'Girlname', 'Girlnumber', 'Girlpercent']
    # Adding Column names

    df.columns = df.columns.str.strip()

    con = sqlite3.connect("*************\\baby_names.db")

    # drop data into database
    df.to_sql("Combined", con)

    df.to_sql("Boys", con)

    df.to_sql("Girls", con)

    con.commit()
    con.close()
create_and_insert()

def test():
    c.execute("SELECT * FROM Boys WHERE Rank = 1")
    print(c.fetchall())

test()

con.commit()
con.close()
</code>```

I've tried adding multiple delimiters, but it didn't seem to do anything. Using just regular space as the delimiter seems to just create 'blank' column names. From reading the Pandas docs, it says that multiple delimiters are possible, but I can't quite figure it out. Any help would be greatly appreciated!

答:
Note that:

your input file contains 7 columns,

but the initial column is set as the index (you passed index_col=0),

so your DataFrame contains only 6 regular columns.

Print df to confirm it.

Now, when you run df.columns = ['Rank', ...], you attempt to assing the
7 passed names to existing 6 data columns.

Probably you should:

read the DataFrame without setting the index (for now),

assign all 7 column names,

set Rank column as the index.

The code to do it is:

```<code>df = pd.read_csv('babynames.txt', header=None, sep='\s+', engine='python')
df.columns = ['Rank', 'BoyName', 'Boynumber', 'Boypercent', 'Girlname', 'Girlnumber',
    'Girlpercent']
df.set_index('Rank', inplace=True)
</code>```

Or even shorter (all in one):

```<code>df = pd.read_csv('babynames.txt', sep='\s+', engine='python',
    names=['Rank', 'BoyName', 'Boynumber', 'Boypercent', 'Girlname', 'Girlnumber',
    'Girlpercent'], index_col='Rank')
</code>```

Body:
I'm currently trying to use Python read a text file into Sqlite3 using Pandas. Here are a few entries from the text file:

1  Michael  462085  2.2506  Jessica  302962  1.5436
2  Christopher  361250  1.7595  Ashley  301702  1.5372
3  Matthew  351477  1.7119  Emily  237133  1.2082

The data consists of popular baby names, and I have to separate male names and female names into their own tables and perform queries on them. My method consists of first placing all the data into both tables, then dropping the unneeded columns afterwards. My issue is that when I try to add names to the columns, I get a value error: The expected axis has 6 elements, but 7 values. I'm assuming it's because Pandas possibly isn't reading the last values of each line, but I can't figure out how to fix it. My current delimiter is a whitespace delimiter that you can see below.

Here is my code:

import sqlite3
import pandas as pd
import csv

con = sqlite3.connect("C:\\****\\****\\****\\****\\****\baby_names.db")
c=con.cursor()

# Please note that most of these functions will be commented out, because they will only be run once.

def create_and_insert():
    # load data
    df = pd.read_csv('babynames.txt', index_col=0, header=None, sep= '\s+', engine = 'python')
    # Reading the textfile

    df.columns = ['Rank', 'BoyName', 'Boynumber', 'Boypercent', 'Girlname', 'Girlnumber', 'Girlpercent']
    # Adding Column names

    df.columns = df.columns.str.strip()

    con = sqlite3.connect("*************\\baby_names.db")

    # drop data into database
    df.to_sql("Combined", con)

    df.to_sql("Boys", con)

    df.to_sql("Girls", con)

    con.commit()
    con.close()
create_and_insert()

def test():
    c.execute("SELECT * FROM Boys WHERE Rank = 1")
    print(c.fetchall())

test()

con.commit()
con.close()

I've tried adding multiple delimiters, but it didn't seem to do anything. Using just regular space as the delimiter seems to just create 'blank' column names. From reading the Pandas docs, it says that multiple delimiters are possible, but I can't quite figure it out. Any help would be greatly appreciated!

Body:
Note that:

your input file contains 7 columns,

but the initial column is set as the index (you passed index_col=0),

so your DataFrame contains only 6 regular columns.

Print df to confirm it.

Now, when you run df.columns = ['Rank', ...], you attempt to assing the
7 passed names to existing 6 data columns.

Probably you should:

read the DataFrame without setting the index (for now),

assign all 7 column names,

set Rank column as the index.

The code to do it is:

df = pd.read_csv('babynames.txt', header=None, sep='\s+', engine='python')
df.columns = ['Rank', 'BoyName', 'Boynumber', 'Boypercent', 'Girlname', 'Girlnumber',
    'Girlpercent']
df.set_index('Rank', inplace=True)

Or even shorter (all in one):

df = pd.read_csv('babynames.txt', sep='\s+', engine='python',
    names=['Rank', 'BoyName', 'Boynumber', 'Boypercent', 'Girlname', 'Girlnumber',
    'Girlpercent'], index_col='Rank')


问:
Pandas splitting Columns and creating Columns of tuples
I have a dataframe which looks as follows:

```<code># df

colA     colB          colC

rqp      129            a
pot      217;345        u
ghay     716            b
rbba     217;345        d
tary     612;811;760    a
kals     716            t
</code>```

The ColB (any component out of two shown) & ColC combination make a unique combination.
I want to create a dataframe from this dataframe which will look like the following

```<code># newdf:

colAA      coLBB

(129,a)    (a,rqp)
(217,u)    (u,pot)
(345,u)    (u,pot)
(716,b)    (b,ghay)
(217,d)    (d,rbba)
(345,d)    (d,rbba)
(612,a)    (a,tary)
(811,a)    (a,tary)
(760,a)    (a,tary)
(716,t)    (t,kals)
</code>```

I have tried creating new columns if there is a single element in colB, but cannot get how to do using the semicolon splitter and then how to create columns of tuples.

If I do not have any semicolon in ColB, then I can use

```<code>df['AA'] = list(zip(df[colB], df[colC]))
df['AB'] = list(zip(df[colC], df[colA]))
</code>```

However the presence of semicolon in ColB I am getting issues, as how to split that string into multiple ones and assign the tuples.
Any help will be very much appreciated.

答:
Code

```<code>def merge(row):
    return pd.Series({
            "colAA": (row.colB, row.colC),
            "colBB": (row.colC, row.colA),
        })

df['colB'] = df['colB'].str.split(';')
df = df.explode('colB')
newDf = df.apply(merge, axis=1).reset_index(drop=True)
</code>```

Explanation

You can split colB to get list of values,
Then apply explode function to get multiple rows

```<code>df['colB'] = df['colB'].str.split(';')
df = df.explode('colB')

# output
    colA    colB    colC
0   rqp 129 a
1   pot 217 u
1   pot 345 u
2   ghay    716 b
3   rbba    217 d
</code>```

Then apply merge function below to create new data frame

```<code>def merge(row):
    for b in row.colB.split(";"):
         return pd.Series({
            "colAA": (b, row.colC),
            "colBB": (row.colC, row.colA),

        })
</code>```

Then apply this function on Df

```<code>newDf = df.apply(merge, axis=1).reset_index(drop=True)

# output
    colAA        colBB
0   (129, a)    (a, rqp)
1   (217, u)    (u, pot)
2   (345, u)    (u, pot)
3   (716, b)    (b, ghay)
4   (217, d)    (d, rbba)
5   (345, d)    (d, rbba)
6   (612, a)    (a, tary)
7   (811, a)    (a, tary)
8   (760, a)    (a, tary)
9   (716, t)    (t, kals)
</code>```

Body:
I have a dataframe which looks as follows:

# df

colA     colB          colC

rqp      129            a
pot      217;345        u
ghay     716            b
rbba     217;345        d
tary     612;811;760    a
kals     716            t

The ColB (any component out of two shown) & ColC combination make a unique combination.
I want to create a dataframe from this dataframe which will look like the following

# newdf:

colAA      coLBB

(129,a)    (a,rqp)
(217,u)    (u,pot)
(345,u)    (u,pot)
(716,b)    (b,ghay)
(217,d)    (d,rbba)
(345,d)    (d,rbba)
(612,a)    (a,tary)
(811,a)    (a,tary)
(760,a)    (a,tary)
(716,t)    (t,kals)

I have tried creating new columns if there is a single element in colB, but cannot get how to do using the semicolon splitter and then how to create columns of tuples.

If I do not have any semicolon in ColB, then I can use

df['AA'] = list(zip(df[colB], df[colC]))
df['AB'] = list(zip(df[colC], df[colA]))

However the presence of semicolon in ColB I am getting issues, as how to split that string into multiple ones and assign the tuples.
Any help will be very much appreciated.

Body:
Code

def merge(row):
    return pd.Series({
            "colAA": (row.colB, row.colC),
            "colBB": (row.colC, row.colA),
        })

df['colB'] = df['colB'].str.split(';')
df = df.explode('colB')
newDf = df.apply(merge, axis=1).reset_index(drop=True)

Explanation

You can split colB to get list of values,
Then apply explode function to get multiple rows

df['colB'] = df['colB'].str.split(';')
df = df.explode('colB')

# output
    colA    colB    colC
0   rqp 129 a
1   pot 217 u
1   pot 345 u
2   ghay    716 b
3   rbba    217 d

Then apply merge function below to create new data frame

def merge(row):
    for b in row.colB.split(";"):
         return pd.Series({
            "colAA": (b, row.colC),
            "colBB": (row.colC, row.colA),

        })

Then apply this function on Df

newDf = df.apply(merge, axis=1).reset_index(drop=True)

# output
    colAA        colBB
0   (129, a)    (a, rqp)
1   (217, u)    (u, pot)
2   (345, u)    (u, pot)
3   (716, b)    (b, ghay)
4   (217, d)    (d, rbba)
5   (345, d)    (d, rbba)
6   (612, a)    (a, tary)
7   (811, a)    (a, tary)
8   (760, a)    (a, tary)
9   (716, t)    (t, kals)


问:
Add column after another column
How can I add a column after another column to a database using Alembic or SQLAlchemy? That would be equivalent to this SQL clause:

ALTER TABLE foo
CHANGE COLUMN bar
bar COLUMN_DEFINITION_HERE
AFTER OTHER_COLUMN;
-- or
ALTER TABLE foo ADD COLUMN baz AFTER bar;
```

I also tried the suggestion in this mailing list thread, but it didn't help.

While the order doesn't matter when querying, it helps readability for large tables when in the SQL shell.

答:
Try this query :

ALTER TABLE table_name ADD New_column_name column_definition AFTER column_name;

Title: Add column after another column

Body:
How can I add a column after another column to a database using Alembic or SQLAlchemy? That would be equivalent to this SQL clause:

ALTER TABLE foo
CHANGE COLUMN bar
bar COLUMN_DEFINITION_HERE
AFTER OTHER_COLUMN;
-- or
ALTER TABLE foo ADD COLUMN baz AFTER bar;

I also tried the suggestion in this mailing list thread, but it didn't help.

While the order doesn't matter when querying, it helps readability for large tables when in the SQL shell.


问:
Uploading Large Files to WCF from Xamarin Android App Crashes
I'm trying to upload a large video (1 GB+) from my xamarin app and it keeps crashing once it reaches about 0.5 GB of my file. The only way I've found to get the videos to post to my WCF service while sending data along with it is using the MultiPart logic but I'm not sure if I'm running out of memory or what because even in debug mode, it simply crashes without any real error message.

I'm trying to run it on a native device (not a sim) and it's a Samsung Galaxy S9 with Android 9.

Here's the upload code that I'm using: (p.s. - as a test, I tried putting the WriteAsync into a for loop thinking that maybe trying to write the whole gig was the problem, but the result was the same. That's why you'll see the MAXFILESIZEPART constant in there which is just an int equal to 10000000.)

```<code>private async Task<byte[]> GetMultipartFormDataAsync(Dictionary<string, object> postParameters, string boundary)
        {
            try
            {

                using (Stream formDataStream = new System.IO.MemoryStream())
                {
                    bool needsCLRF = false;

                    foreach (var param in postParameters)
                    {
                        // Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
                        // Skip it on the first parameter, add it to subsequent parameters.
                        if (needsCLRF)
                            await formDataStream.WriteAsync(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n"));

                        needsCLRF = true;

                        if (param.Value is FileParameter)
                        {
                            FileParameter fileToUpload = (FileParameter)param.Value;

                            // Add just the first part of this param, since we will write the file data directly to the Stream
                            string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n",
                                                boundary,
                                                param.Key,
                                                fileToUpload.FileName ?? param.Key,
                                                fileToUpload.ContentType ?? "application/octet-stream");

                            await formDataStream.WriteAsync(Encoding.UTF8.GetBytes(header), 0, Encoding.UTF8.GetByteCount(header));

                            // Write the file data directly to the Stream, rather than serializing it to a string.
                            if (fileToUpload.File.Length > MAXFILESIZEPART)
                            {
                                for (var i = 0; i < fileToUpload.File.Length; i += MAXFILESIZEPART)
                                {
                                    var len = i + MAXFILESIZEPART > fileToUpload.File.Length
                                        ? fileToUpload.File.Length - i
                                        : MAXFILESIZEPART;
                                    await formDataStream.WriteAsync(fileToUpload.File, i, len);
                                }
                            }
                            else
                            {
                                await formDataStream.WriteAsync(fileToUpload.File, 0, fileToUpload.File.Length);
                            }

                        }
                        else
                        {
                            string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
                                                  boundary,
                                                  param.Key,
                                                  param.Value);
                            await formDataStream.WriteAsync(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
                        }
                    }

                    // Add the end of the request.  Start with a newline
                    string footer = "\r\n--" + boundary + "--\r\n";
                    await formDataStream.WriteAsync(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));

                    // Dump the Stream into a byte[]
                    formDataStream.Position = 0;
                    byte[] formData = new byte[formDataStream.Length];
                    formDataStream.Read(formData, 0, formData.Length);

                    return formData;
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
</code>```

And it's eventually failing on the following line

```<code>await formDataStream.WriteAsync(fileToUpload.File, i, len);
</code>```

but only after a certain point (about 500MB) so I'm assuming it's a memory issue but it doesn't say so. Is there a better way to accomplish this task? I'm doing it so that it also records the progress as the upload happens. I'm trying to accomplish something similar to uploading large videos via the facebook app so that it will upload in the background while you continue working. It works great when working with smaller files (i.e. - < 500 MB) but this is the first time I've tried a file that was almost a gig in size.

NOTE: This happens BEFORE it starts posting anything to the server so it's not IIS or WCF related. This code crashes just writing the bytes to the memory stream.

Any suggestions?

Thanks!

答:
According to your description, the service will stop at a certain time point, and because the file you transfer is about 1G, it is likely to be sendtimeout.No transfer completed within the specified time, causing exception。The SendTimeout that specifies how long the write operation has to complete before timing out. The default value is 1 minute.

I set sendtimeout to 15 seconds in my configuration file.If the data takes more than 15 seconds, an exception will occur. You can set it to a higher value to avoid timeout and exception.

For information about sendtimeout, please refer to the following link:

https://learn.microsoft.com/en-us/dotnet/api/system.servicemodel.channels.binding.sendtimeout?view=dotnet-plat-ext-3.1

UPDATE

I think it might be a memory overflow problem.Large file may cause memory overflow, unable to read at the same time.

You can refer to the following links for solutions

https://learn.microsoft.com/en-us/archive/blogs/johan/are-you-getting-outofmemoryexceptions-when-uploading-large-files

Body:
I'm trying to upload a large video (1 GB+) from my xamarin app and it keeps crashing once it reaches about 0.5 GB of my file. The only way I've found to get the videos to post to my WCF service while sending data along with it is using the MultiPart logic but I'm not sure if I'm running out of memory or what because even in debug mode, it simply crashes without any real error message.

I'm trying to run it on a native device (not a sim) and it's a Samsung Galaxy S9 with Android 9.

Here's the upload code that I'm using: (p.s. - as a test, I tried putting the WriteAsync into a for loop thinking that maybe trying to write the whole gig was the problem, but the result was the same. That's why you'll see the MAXFILESIZEPART constant in there which is just an int equal to 10000000.)

private async Task<byte[]> GetMultipartFormDataAsync(Dictionary<string, object> postParameters, string boundary)
        {
            try
            {

                using (Stream formDataStream = new System.IO.MemoryStream())
                {
                    bool needsCLRF = false;

                    foreach (var param in postParameters)
                    {
                        // Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
                        // Skip it on the first parameter, add it to subsequent parameters.
                        if (needsCLRF)
                            await formDataStream.WriteAsync(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n"));

                        needsCLRF = true;

                        if (param.Value is FileParameter)
                        {
                            FileParameter fileToUpload = (FileParameter)param.Value;

                            // Add just the first part of this param, since we will write the file data directly to the Stream
                            string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n",
                                                boundary,
                                                param.Key,
                                                fileToUpload.FileName ?? param.Key,
                                                fileToUpload.ContentType ?? "application/octet-stream");

                            await formDataStream.WriteAsync(Encoding.UTF8.GetBytes(header), 0, Encoding.UTF8.GetByteCount(header));

                            // Write the file data directly to the Stream, rather than serializing it to a string.
                            if (fileToUpload.File.Length > MAXFILESIZEPART)
                            {
                                for (var i = 0; i < fileToUpload.File.Length; i += MAXFILESIZEPART)
                                {
                                    var len = i + MAXFILESIZEPART > fileToUpload.File.Length
                                        ? fileToUpload.File.Length - i
                                        : MAXFILESIZEPART;
                                    await formDataStream.WriteAsync(fileToUpload.File, i, len);
                                }
                            }
                            else
                            {
                                await formDataStream.WriteAsync(fileToUpload.File, 0, fileToUpload.File.Length);
                            }

                        }
                        else
                        {
                            string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
                                                  boundary,
                                                  param.Key,
                                                  param.Value);
                            await formDataStream.WriteAsync(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
                        }
                    }

                    // Add the end of the request.  Start with a newline
                    string footer = "\r\n--" + boundary + "--\r\n";
                    await formDataStream.WriteAsync(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));

                    // Dump the Stream into a byte[]
                    formDataStream.Position = 0;
                    byte[] formData = new byte[formDataStream.Length];
                    formDataStream.Read(formData, 0, formData.Length);

                    return formData;
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

And it's eventually failing on the following line

await formDataStream.WriteAsync(fileToUpload.File, i, len);

but only after a certain point (about 500MB) so I'm assuming it's a memory issue but it doesn't say so. Is there a better way to accomplish this task? I'm doing it so that it also records the progress as the upload happens. I'm trying to accomplish something similar to uploading large videos via the facebook app so that it will upload in the background while you continue working. It works great when working with smaller files (i.e. - < 500 MB) but this is the first time I've tried a file that was almost a gig in size.

NOTE: This happens BEFORE it starts posting anything to the server so it's not IIS or WCF related. This code crashes just writing the bytes to the memory stream.

Any suggestions?

Thanks!


问:
Hexeditted shared library 'Version x.so not found' error
My library A is dependant on external library B. When I use ld on A.so, I see B is linked as B.so.10, yet on my computer the links are:

B.so -> B.so.10

B.so.10 -> B.so.10.5

Im trying to make A link to JUST B.so and use symbolic links for what version to load. I hexeditted A.so and replaced all findings of B.so.10 with B.so, and ld links it just fine, but when I try to dlopen A.so, it says: 'Error loading A.so: Version B.so not found' I've read about symbol versioning and such, but honestly have no clue where to look for what would be causing the issue?

Ive checked readelf and compared a non editted version to mine and I see nothing in the diffs besides the SO name. Elfedit also did not work snd just turned the binary into garbage data.

答:
If you run readelf -V B.so, you will likely discover that it doesn't define version B.so, but does define version B.so.10.

By replacing all B.so.10 strings with B.so you state to the runtime loader that A.so depends on version B.so instead of B.so.10 that it used to depend on.

Since not such version exists at runtime, loader correctly complains.

Ive checked readelf and compared a non editted version to mine and I see nothing in the diffs besides the SO name.

Check again. In particular, do this:

```<code>diff <(readelf -V A.so.orig) <(readelf -V A.so)
</code>```

You should  see some differences there.

Im trying to make A link to JUST B.so and use symbolic links for what version to load.

You appear to have an XY problem. What are you really trying to achieve?

Update:

The initial problem is im trying to make my software CUDA version agnostic. ...  I can't take this binary and plop it on another system with a different cufft version as cufft links to a specific version even though the ABI hasn't changed in forever.

Ah, you do in fact have an XY problem.

You can not in fact deduce that the ABI has not changed, unless you verify that every structure potentially used in that ABI has not changed (this is different from verifying that the API has not changed, and you likely did that).

If you succeed in patching out the version, the end result will likely be a mystery crash on a system with different version of CUFFT.

If you are lucky, the crash will happen quickly and reproducibly. If you are unlucky, it will happen rarely and will look completely mysterious and unrelated, will happen only on some systems, only on some customer machines, only after you make totally unrelated changes to your library, etc. etc.

TL;DR: You are setting yourself up for significant pain. Just don't do it.

Body:
If you run readelf -V B.so, you will likely discover that it doesn't define version B.so, but does define version B.so.10.

By replacing all B.so.10 strings with B.so you state to the runtime loader that A.so depends on version B.so instead of B.so.10 that it used to depend on.

Since not such version exists at runtime, loader correctly complains.

Ive checked readelf and compared a non editted version to mine and I see nothing in the diffs besides the SO name.

Check again. In particular, do this:

diff <(readelf -V A.so.orig) <(readelf -V A.so)

You should  see some differences there.

Im trying to make A link to JUST B.so and use symbolic links for what version to load.

You appear to have an XY problem. What are you really trying to achieve?

Update:

The initial problem is im trying to make my software CUDA version agnostic. ...  I can't take this binary and plop it on another system with a different cufft version as cufft links to a specific version even though the ABI hasn't changed in forever.

Ah, you do in fact have an XY problem.

You can not in fact deduce that the ABI has not changed, unless you verify that every structure potentially used in that ABI has not changed (this is different from verifying that the API has not changed, and you likely did that).

If you succeed in patching out the version, the end result will likely be a mystery crash on a system with different version of CUFFT.

If you are lucky, the crash will happen quickly and reproducibly. If you are unlucky, it will happen rarely and will look completely mysterious and unrelated, will happen only on some systems, only on some customer machines, only after you make totally unrelated changes to your library, etc. etc.

TL;DR: You are setting yourself up for significant pain. Just don't do it.


问:
change image by click prev/next button
I am trying to change images in "div" by clicking buttons as like "carousel", but could not done and codes does not throw any error.  I could not yet understand what I am doing wrong.

I am calling java script function "setIndex" on clicking with parameters +1 or -1. In java code
i simply change image source as required and simply put display='block' followed by image source.

but the theme is not working and does not change image.

Please help.

My codes are as under:

```<code><!DOCTYPE html>
<html>
<head>
    <title>prev_next#</title>
</head>
<style>
    .divContainer{
        width: 85%;
        margin: auto;
        overflow: hidden;
    }
    #Middle{
        min-height: 460px;
    }
    #divMiddle{
        width: 90%;
        margin: auto;
        border: 2px red solid;
        overflow: hidden;
        max-height: 460px;
    }
    #divSlides{
        float: left;
        width: 100%;
        max-height: 455px;
    }
    #slideImage{
        height: 494px;
        width: 100%;
        margin: auto;
    }
    .alink-left, .alink-right{
        position: absolute;
        top:30%;
        width: auto;
        margin-top: 22px;
        font-size: 40px;
        color:red;
        border:none;
        user-select: none;
        border-radius: 3px 0 0 3px;
        text-decoration: none;
    }
    .alink-left{
       color:yellow;
       left:0;
       margin-left: 10%;
    }
    .alink-right{
        color:red;
        right: 90px;
    }
</style>
<body>
    <section id='Middle'>
        <div class="divContainer" id="divMiddle">
            <div id="divSlides">
                <img id="slideImage" src="../html-web/img/it-slide01.jpg">
                <a class="alink-left"   href="" onclick="setIndex(-1)"> < </a>
                <a class="alink-right"  href="" onclick="setIndex(+1)"> > </a>
            </div>
        </div>
    </section>
</body>
<script>
    var imageNo= 1;
    var ImageSource="";

    function setIndex(idx) {
        imageNo = imageNo + idx ;
        alert(imageNo)
        switch(imageNo){
            case 1:
              slideImage.display='none';
              ImageSource='../html-web/img/it-slide01.jpg';
              break;
            case 2:
              alert('case 2')
              slideImage.display='none';
              ImageSource='../html-web/img/it-slide02.jpg';
              break;
            case 3:
              slideImage.display='none';
              ImageSource='../html-web/img/it-slide03.jpg';
              break;
            case 4:
              slideImage.display='none';
              ImageSource='../html-web/img/it-slide04.jpg';
              break;
            case 5:
              slideImage.display='none';
              ImageSource= '../html-web/img/it-slide05.jpg';
              break;
            case 6:
              slideImage.display='none';
              ImageSource= '../html-web/img/it-slide06.jpg';
              break;
            default:
              slideImage.display='none';
              ImageSource='../html-web/img/it-slide01.jpg';
              if(imageNo>=6||imageNo<=1){imageNo=1}
              break;
        }  // switch
            document.getElementsByTagName('slideImage').display='block';
            document.getElementsByTagName('slideImage').src = ImageSource;
            //slideImage.display='block';
            //slideImage.src = ImageSource;
    } //function setIndex
</script>
</html>
</code>```

答:
The issue is your a href="" make page refresh, so just looking not change!

Add "#" in href like , then your code can work!

Looking below, check "your doing right already!" in js.

var imageNo= 1;
    var ImageSource="";
    var slideImage = document.getElementById('slideImage');
    function setIndex(idx) {
        imageNo = imageNo + idx ;
        switch(imageNo){
            case 1:
              slideImage.display='none';
              ImageSource='https://picsum.photos/100/100/?random=1';
              break;
            case 2:
              slideImage.display='none';
              ImageSource='https://picsum.photos/100/100/?random=2';
              break;
            case 3:
              slideImage.display='none';
              ImageSource='https://picsum.photos/100/100/?random=3';
              break;
            case 4:
              slideImage.display='none';
              ImageSource='https://picsum.photos/100/100/?random=4';
              break;
            case 5:
              slideImage.display='none';
              ImageSource= 'https://picsum.photos/100/100/?random=5';
              break;
            case 6:
              slideImage.display='none';
              ImageSource= 'https://picsum.photos/100/100/?random=6';
              break;
            default:
              slideImage.display='none';
              ImageSource='https://picsum.photos/100/100/?random=7';
              if(imageNo>=6||imageNo<=1){imageNo=1}
              break;
        }  // switch
        //=====================================

        //your doing right already!
            //           document.getElementsByTagName('slideImage').display='block';
            // document.getElementsByTagName('slideImage').src = ImageSource;
            slideImage.display='block';  // <=
            slideImage.src = ImageSource; // <=
        //==========================
    } //function setIndex```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.divContainer{
        width: 85%;
        margin: auto;
        overflow: hidden;
    }
    #Middle{
        min-height: 460px;
    }
    #divMiddle{
        width: 90%;
        margin: auto;
        border: 2px red solid;
        overflow: hidden;
        max-height: 460px;
    }
    #divSlides{
        float: left;
        width: 100%;
        max-height: 455px;
    }
    #slideImage{
        height: 494px;
        width: 100%;
        margin: auto;
    }
    .alink-left, .alink-right{
        position: absolute;
        top:30%;
        width: auto;
        margin-top: 22px;
        font-size: 40px;
        color:red;
        border:none;
        user-select: none;
        border-radius: 3px 0 0 3px;
        text-decoration: none;
    }
    .alink-left{
       color:yellow;
       left:0;
       margin-left: 10%;
    }
    .alink-right{
        color:red;
        right: 90px;
    }</code>```

                 <
                 >

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

<p>================================</p>

<p>then</p>

```document.getElementsByTagName('slideImage')
```

<p>return Array, and 'slideImage' is ID on your html not a tab.</p>

<p>How about document.getElementById('slideImage')?</p>

<p>Or just use slideImage? like you used before.</p>

<p>At last</p>

<p>Try use Array to save your images and use variable to save your object!</p>

```var imageNo= 0;
var slideImage = document.getElementById('slideImage');
function setIndex(idx) {
    imageNo = imageNo + idx ;
    alert(imageNo)
    let imagesArray = [ 'https://picsum.photos/100/100/?random=0',
                        'https://picsum.photos/100/100/?random=1',
                        'https://picsum.photos/100/100/?random=2',
                        'https://picsum.photos/100/100/?random=3',
                        'https://picsum.photos/100/100/?random=4',
                        'https://picsum.photos/100/100/?random=5',
                        'https://picsum.photos/100/100/?random=6'];

    slideImage.src = imagesArray[Math.abs(imageNo) % imagesArray.length];
}
```

Title: change image by click prev/next button

Body:
I am trying to change images in "div" by clicking buttons as like "carousel", but could not done and codes does not throw any error.  I could not yet understand what I am doing wrong.

I am calling java script function "setIndex" on clicking with parameters +1 or -1. In java code
i simply change image source as required and simply put display='block' followed by image source.

but the theme is not working and does not change image.

Please help.

My codes are as under:

<!DOCTYPE html>

    <title>prev_next#</title>

                 <
                 >

Body:
The issue is your a href="" make page refresh, so just looking not change!

Add "#" in href like < a href="#">, then your code can work!

Looking below, check "your doing right already!" in js.

var imageNo= 1;
    var ImageSource="";
    var slideImage = document.getElementById('slideImage');
    function setIndex(idx) {
        imageNo = imageNo + idx ;
        switch(imageNo){
            case 1:
              slideImage.display='none';
              ImageSource='https://picsum.photos/100/100/?random=1';
              break;
            case 2:
              slideImage.display='none';
              ImageSource='https://picsum.photos/100/100/?random=2';
              break;
            case 3:
              slideImage.display='none';
              ImageSource='https://picsum.photos/100/100/?random=3';
              break;
            case 4:
              slideImage.display='none';
              ImageSource='https://picsum.photos/100/100/?random=4';
              break;
            case 5:
              slideImage.display='none';
              ImageSource= 'https://picsum.photos/100/100/?random=5';
              break;
            case 6:
              slideImage.display='none';
              ImageSource= 'https://picsum.photos/100/100/?random=6';
              break;
            default:
              slideImage.display='none';
              ImageSource='https://picsum.photos/100/100/?random=7';
              if(imageNo>=6||imageNo<=1){imageNo=1}
              break;
        }  // switch
        //=====================================

        //your doing right already!
            //           document.getElementsByTagName('slideImage').display='block';
            // document.getElementsByTagName('slideImage').src = ImageSource;
            slideImage.display='block';  // <=
            slideImage.src = ImageSource; // <=
        //==========================
    } //function setIndex

.divContainer{
        width: 85%;
        margin: auto;
        overflow: hidden;
    }
    #Middle{
        min-height: 460px;
    }
    #divMiddle{
        width: 90%;
        margin: auto;
        border: 2px red solid;
        overflow: hidden;
        max-height: 460px;
    }
    #divSlides{
        float: left;
        width: 100%;
        max-height: 455px;
    }
    #slideImage{
        height: 494px;
        width: 100%;
        margin: auto;
    }
    .alink-left, .alink-right{
        position: absolute;
        top:30%;
        width: auto;
        margin-top: 22px;
        font-size: 40px;
        color:red;
        border:none;
        user-select: none;
        border-radius: 3px 0 0 3px;
        text-decoration: none;
    }
    .alink-left{
       color:yellow;
       left:0;
       margin-left: 10%;
    }
    .alink-right{
        color:red;
        right: 90px;
    }

<section id='Middle'>
        <div class="divContainer" id="divMiddle">
            <div id="divSlides">
                <img id="slideImage" src="https://picsum.photos/100/100/?random=1">
                <a class="alink-left"   href="#" onclick="setIndex(-1)"> < </a>
                <a class="alink-right"  href="#" onclick="setIndex(+1)"> > </a>
            </div>
        </div>
    </section>

================================

then

document.getElementsByTagName('slideImage')

return Array, and 'slideImage' is ID on your html not a tab.

How about document.getElementById('slideImage')?

Or just use slideImage? like you used before.

At last

Try use Array to save your images and use variable to save your object!

var imageNo= 0;
var slideImage = document.getElementById('slideImage');
function setIndex(idx) {
    imageNo = imageNo + idx ;
    alert(imageNo)
    let imagesArray = [ 'https://picsum.photos/100/100/?random=0',
                        'https://picsum.photos/100/100/?random=1',
                        'https://picsum.photos/100/100/?random=2',
                        'https://picsum.photos/100/100/?random=3',
                        'https://picsum.photos/100/100/?random=4',
                        'https://picsum.photos/100/100/?random=5',
                        'https://picsum.photos/100/100/?random=6'];

    slideImage.src = imagesArray[Math.abs(imageNo) % imagesArray.length];
}