问:
"bash: sed: command not found" RHEL7 when installing SQL Server
NEED HELP - LINUX NEWBIE - BROKEN LINUX RHEL7

While installing the mssql-tools on RHEL7 and following instructions to add the path for the mssql-tools, we added the following commands:

```<code>echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile
echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc
source ~/.bashrc
</code>```

After rebuilding the server for a second time, I've reached this Microsoft step again.  As it is the cause for my broken copy of RHEL7, having a way to do this properly and not incorrectly as listed above would be helpful.   Most articles list about 50 ways to do this.  I'm looking for one way only and it will be nice if the one way actually works and I don't spend another part of my life rebuilding the server again.

```<code>https://learn.microsoft.com/en-us/sql/linux/quickstart-install-connect-red-hat?view=sql-server-ver15
</code>```

I created an issue in Github for this failing.

```<code>https://github.com/MicrosoftDocs/sql-docs/issues/7288
</code>```

答:
The article listed here seems to do the trick

```<code>https://dba.stackexchange.com/questions/174277/getting-sqlcmd-sqlcmd-command-not-found-in-linux
</code>```

Long and short is the PATH should work as a join if it works like it does in Windows but I wound up using

```<code>sudo ln -s /opt/mssql-tools/bin/* /usr/local/bin/
</code>```

to join that location with the user bin.  There is probably more to it since security is always number one, but at least I was able to complete the installation of SQL Server on the RHEL7 release.

Body:
NEED HELP - LINUX NEWBIE - BROKEN LINUX RHEL7

While installing the mssql-tools on RHEL7 and following instructions to add the path for the mssql-tools, we added the following commands:

echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile
echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc
source ~/.bashrc

After rebuilding the server for a second time, I've reached this Microsoft step again.  As it is the cause for my broken copy of RHEL7, having a way to do this properly and not incorrectly as listed above would be helpful.   Most articles list about 50 ways to do this.  I'm looking for one way only and it will be nice if the one way actually works and I don't spend another part of my life rebuilding the server again.

https://learn.microsoft.com/en-us/sql/linux/quickstart-install-connect-red-hat?view=sql-server-ver15

I created an issue in Github for this failing.

https://github.com/MicrosoftDocs/sql-docs/issues/7288

Body:
The article listed here seems to do the trick

https://dba.stackexchange.com/questions/174277/getting-sqlcmd-sqlcmd-command-not-found-in-linux

Long and short is the PATH should work as a join if it works like it does in Windows but I wound up using

sudo ln -s /opt/mssql-tools/bin/* /usr/local/bin/

to join that location with the user bin.  There is probably more to it since security is always number one, but at least I was able to complete the installation of SQL Server on the RHEL7 release.


来源: stackexchange

问:
which is the best way to show a status message in asp.net
Which is the best way to show a status message in asp.net. For example, after saving data to DB I want to show a message like 'Data Saved Successfully". I would like to know which is the best way to show this kind of status message in asp.net.

Thanks All.

答:
It depends on how the rest of the site/application is written as there are a number of ways:

1) Javascript - A nice message box returned/displayed to the user with the message

2) Pure server side - A returned value to the return page which is displayed in a styled info box

And that's just scratching the surface ...

ContentLicense: CC BY-SA 3.0


问:
How to calculate percentage difference between two data frames with Pandas and return column and row names?
I use pandas

For example, i have 2 df with same names of columns and rows

```
df1
    name    a   b
0   row1    3   2
1   row2    7   2
2   row3    1   6
```
```
df2
    name    a   b
0   row1    4   2
1   row2    7   2
2   row3    2   3
```

I need to calculate percetage difference, compare 2 df and return answer in this format if the difference more then 30% (no important is this increase or decrease):

"row2": "a"  increase by 33,3 %
"row 3" : "a"  increase by 50 %, "b" decrease by 50%

答:
Define name column as index of both dataframes then merge them:

```<code>df1 = df1.set_index('name').stack()
df2 = df2.set_index('name').stack()

out = pd.concat([df1, df2], keys=['l', 'r'],axis=1) \
        .pct_change(axis=1).mul(100) \
        .query('r.abs() >= 30')['r']
</code>```

Output:

```<code>>>> out
out = pd.concat([df1, df2], keys=['l', 'r'],axis=1) \
        .pct_change(axis=1).mul(100) \
        .query('r.abs() >= 30')['r']
</code>```

Output:

```<code>>>> out
name
row1  a     33.333333
row3  a    100.000000
      b    -50.000000
Name: r, dtype: float64
</code>```

With formatting:

```<code>lst = list(out.index.get_level_values(0) + ': '
           + out.index.get_level_values(1)
           + np.where(out > 0, ' increase by ', ' decrease by ')
           + out.map(lambda x: f"{x:.2f}%"))
print(lst)

# Output
['row1: a increase by 33.33%',
 'row3: a increase by 100.00%',
 'row3: b decrease by -50.00%']
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I use pandas

For example, i have 2 df with same names of columns and rows

df1
    name    a   b
0   row1    3   2
1   row2    7   2
2   row3    1   6

df2
    name    a   b
0   row1    4   2
1   row2    7   2
2   row3    2   3

I need to calculate percetage difference, compare 2 df and return answer in this format if the difference more then 30% (no important is this increase or decrease):

"row2": "a"  increase by 33,3 %
"row 3" : "a"  increase by 50 %, "b" decrease by 50%

Body:
Define name column as index of both dataframes then merge them:

df1 = df1.set_index('name').stack()
df2 = df2.set_index('name').stack()

out = pd.concat([df1, df2], keys=['l', 'r'],axis=1) \
        .pct_change(axis=1).mul(100) \
        .query('r.abs() >= 30')['r']

Output:

>>> out
out = pd.concat([df1, df2], keys=['l', 'r'],axis=1) \
        .pct_change(axis=1).mul(100) \
        .query('r.abs() >= 30')['r']

Output:

>>> out
name
row1  a     33.333333
row3  a    100.000000
      b    -50.000000
Name: r, dtype: float64

With formatting:

lst = list(out.index.get_level_values(0) + ': '
           + out.index.get_level_values(1)
           + np.where(out > 0, ' increase by ', ' decrease by ')
           + out.map(lambda x: f"{x:.2f}%"))
print(lst)

# Output
['row1: a increase by 33.33%',
 'row3: a increase by 100.00%',
 'row3: b decrease by -50.00%']


问:
Fire event at Infinite horizontal scroll end in ionic 5
I am trying to build infinite scrolling content horizontally. Following code does the job on the first load.

HTML:

```<code>  <div class="thumnails">
    <div class="list-thumbnail">
      <div class="img-thumb" *ngFor="let user of userList">
        <ion-grid>
          <ion-row>
            {{user.name}}
          </ion-row>
        </ion-grid>
      </div>
    </div>
  </div>
</code>```

SCSS:

```<code>.thumnails{
    overflow-x: scroll;
    overflow-y: hidden;
    .list-thumbnail{
      height: 100%;
      white-space: nowrap;
      .img-thumb{
        display: inline-block;
        border: 1px solid #ddd;
        border-radius: 4px;
        padding: 3px;
      }
    }
  }
  ::-webkit-scrollbar {
    display: none;
  }
</code>```

After this, I need to fire a method when a user reaches the end on scroll. Ionic has the component ion-infinite-scroll which works in vertical scroll but it's not firing when I use it with the above code.

Is there a way to fire an event at the end of the horizontal scroll?

答:
Here is my solution. Is not beautiful and I did not test it for performance issues but it does exactly what you want

HTML:

```<code><ion-content>
  <div class="thumnails" (scroll)="scrollEv($event)">
    <div class="list-thumbnail">
      <div class="img-thumb" *ngFor="let user of userList">
        <span class="id" hidden>{{ user.id }}</span>
        <ion-grid>
          <ion-row>
            {{ user.name }}
          </ion-row>
        </ion-grid>
      </div>
    </div>
  </div>
</ion-content>
</code>```

TS:

```<code>  userList: Array<any> = [];
  // elements count till the end of list to trigger the `getData()` function
  elementsToTrigger: number = 10;

  constructor() { }

  ngOnInit() {
    this.getData();
  }

  scrollEv(ev) {
    // get the last visible on screen element of the list by it's coordenates:
    // x => the offsetWidth of the body - 5px so it doesn't get out of boundaries
    // y => distance the list is from the top. Note that here the list is fixed at the top because it's the only element on screen, but if, at some point,
    // it will scroll or be placed at someplace else you should get this distance manually before this next line.
    let elByCoords = document.elementFromPoint(document.body.offsetWidth - 5, 0);
    let elId = elByCoords.children[0].textContent;

    // check if the last element visible on screen is the "elementsToTrigger'th to last" and if so get more data
    // here you should also check if all data has been loaded so you don't keep sending requests to your backend
    if ((this.userList.length - this.userList.findIndex(user => user.id === +elId)) <= this.elementsToTrigger) {
      this.getData();
    }
  }

  getData() {
    // here goes your logic to retrieve more results from database.
    let startAt: number = this.userList?.length || 0;
    let arr = [];
    for (let i = startAt; i < startAt + 50; i++) {
      arr.push({ id: i, name: `User ${i}` });
    }
    this.userList = (this.userList || []).concat(arr);
  }

</code>```

You may need to play a little with document.elementFromPoint(x, y) to find the correct values

Body:
I am trying to build infinite scrolling content horizontally. Following code does the job on the first load.

HTML:

        <ion-grid>
          <ion-row>
            {{user.name}}
          </ion-row>
        </ion-grid>

SCSS:

.thumnails{
    overflow-x: scroll;
    overflow-y: hidden;
    .list-thumbnail{
      height: 100%;
      white-space: nowrap;
      .img-thumb{
        display: inline-block;
        border: 1px solid #ddd;
        border-radius: 4px;
        padding: 3px;
      }
    }
  }
  ::-webkit-scrollbar {
    display: none;
  }

After this, I need to fire a method when a user reaches the end on scroll. Ionic has the component ion-infinite-scroll which works in vertical scroll but it's not firing when I use it with the above code.

Is there a way to fire an event at the end of the horizontal scroll?

Body:
Here is my solution. Is not beautiful and I did not test it for performance issues but it does exactly what you want

HTML:

<ion-content>
  <div class="thumnails" (scroll)="scrollEv($event)">
    <div class="list-thumbnail">
      <div class="img-thumb" *ngFor="let user of userList">
        <span class="id" hidden>{{ user.id }}</span>
        <ion-grid>
          <ion-row>
            {{ user.name }}
          </ion-row>
        </ion-grid>
      </div>
    </div>
  </div>
</ion-content>

TS:

  userList: Array<any> = [];
  // elements count till the end of list to trigger the `getData()` function
  elementsToTrigger: number = 10;

  constructor() { }

  ngOnInit() {
    this.getData();
  }

  scrollEv(ev) {
    // get the last visible on screen element of the list by it's coordenates:
    // x => the offsetWidth of the body - 5px so it doesn't get out of boundaries
    // y => distance the list is from the top. Note that here the list is fixed at the top because it's the only element on screen, but if, at some point,
    // it will scroll or be placed at someplace else you should get this distance manually before this next line.
    let elByCoords = document.elementFromPoint(document.body.offsetWidth - 5, 0);
    let elId = elByCoords.children[0].textContent;

    // check if the last element visible on screen is the "elementsToTrigger'th to last" and if so get more data
    // here you should also check if all data has been loaded so you don't keep sending requests to your backend
    if ((this.userList.length - this.userList.findIndex(user => user.id === +elId)) <= this.elementsToTrigger) {
      this.getData();
    }
  }

  getData() {
    // here goes your logic to retrieve more results from database.
    let startAt: number = this.userList?.length || 0;
    let arr = [];
    for (let i = startAt; i < startAt + 50; i++) {
      arr.push({ id: i, name: `User ${i}` });
    }
    this.userList = (this.userList || []).concat(arr);
  }

You may need to play a little with document.elementFromPoint(x, y) to find the correct values


问:
Constructors, destructors and ternary operator
I have this simple class with two specialized constructors.

```<code>#include <iostream>

class test_01
{
  std::string name;
  uint16_t value;
public:
  test_01(std::string name);
  test_01(uint16_t value);
  ~test_01();
  void show_message(std::string message);
};

test_01::test_01(std::string name)
{
  std::cout << "Constructor string is called" << std::endl;
  test_01::name = name;
}

test_01::test_01(uint16_t value)
{
  std::cout << "Constructor uint16 is called" << std::endl;
  test_01::value = value;
}

test_01::~test_01()
{
  std::cout << "Destructor is called" << std::endl;
}

void test_01::show_message(std::string message)
{
  std::cout << message.c_str() << std::endl;
}

int main()
{
  bool result = true;

  test_01 t = result ? test_01("test") : test_01(57);
  t.show_message("hello");
}
</code>```

Each constructor is called depending on an external condition. When the ternary operator is executed a destructor is called. Thus.

Constructor string is called

Destructor is called

hello

Destructor is called

I don't understand why the first destructor is called

Thanks !

答:
Because there are two test_01 objects created, so two must be destroyed.

```<code>                     first is exactly one of
                     vvvvvvvvvvvvvvv or  vvvvvvvvvvvv
test_01 t = result ? test_01("test")  :  test_01(57);
        ^ second is here
</code>```

Had you added logging to the copy or move constructors, you would see, a temporary object is copied/moved into t object, which is move/copy constructed from this temporary.

Body:
I have this simple class with two specialized constructors.

#include <iostream>

class test_01
{
  std::string name;
  uint16_t value;
public:
  test_01(std::string name);
  test_01(uint16_t value);
  ~test_01();
  void show_message(std::string message);
};

test_01::test_01(std::string name)
{
  std::cout << "Constructor string is called" << std::endl;
  test_01::name = name;
}

test_01::test_01(uint16_t value)
{
  std::cout << "Constructor uint16 is called" << std::endl;
  test_01::value = value;
}

test_01::~test_01()
{
  std::cout << "Destructor is called" << std::endl;
}

void test_01::show_message(std::string message)
{
  std::cout << message.c_str() << std::endl;
}

int main()
{
  bool result = true;

  test_01 t = result ? test_01("test") : test_01(57);
  t.show_message("hello");
}

Each constructor is called depending on an external condition. When the ternary operator is executed a destructor is called. Thus.

Constructor string is called

Destructor is called

hello

Destructor is called

I don't understand why the first destructor is called

Thanks !

Body:
Because there are two test_01 objects created, so two must be destroyed.

                     first is exactly one of
                     vvvvvvvvvvvvvvv or  vvvvvvvvvvvv
test_01 t = result ? test_01("test")  :  test_01(57);
        ^ second is here

Had you added logging to the copy or move constructors, you would see, a temporary object is copied/moved into t object, which is move/copy constructed from this temporary.


问:
What is the difference between a LEFT JOIN and a sub-query?
I am attempting to find all of the results in table1 that do not have an associated record in table2. I have 2 queries:

SELECT * FROM table1 LEFT JOIN table2 ON table1.id = table2.table1_id WHERE table2.table1_id IS null
This works and returns all of the results in table1 that are not in table 2

SELECT * FROM table1 WHERE table1.id NOT IN (SELECT table2.table1_id FROM table2) This does not work. It returns zero results. I've ran each of the parts individually and it appears this should work.

Will someone please explain why one works where the other doesn't

Edit: Added purpose of queries

Edit 2: Added sqlFiddle. http://sqlfiddle.com/#!17/ab473/1 It works on here, so I have no idea why it isn't working on my local computer

Edit 3: sqlFiddle replicating the issue http://sqlfiddle.com/#!17/bd92f7/1. Removing the null value resolved the issue.

答:
I think that both of your queries are not ideal:

The first query can return a row from table1 more than once if there is more than one matching row in table2. Sure, you can fix that with a DISTINCT, but the performance is not ideal.

The second query won't work if there is a row in table2 where table1_id IS NULL:

x NOT IN (1, 2, NULL) is equivalent to x <> 1 AND x <> 2 AND x <> NULL

now x <> NULL is always NULL, no matter what x is

<anything> AND NULL is never TRUE

so the condition with never be TRUE, which explains why you get no result

The best (and most efficient) query is:

```<code>SELECT * FROM table1
WHERE NOT EXISTS (SELECT 1 FROM table2
                  WHERE table1.id = table2.table1_id);
</code>```

Body:
I think that both of your queries are not ideal:

The first query can return a row from table1 more than once if there is more than one matching row in table2. Sure, you can fix that with a DISTINCT, but the performance is not ideal.

The second query won't work if there is a row in table2 where table1_id IS NULL:

x NOT IN (1, 2, NULL) is equivalent to x <> 1 AND x <> 2 AND x <> NULL

now x <> NULL is always NULL, no matter what x is

<anything> AND NULL is never TRUE

so the condition with never be TRUE, which explains why you get no result

The best (and most efficient) query is:

SELECT * FROM table1
WHERE NOT EXISTS (SELECT 1 FROM table2
                  WHERE table1.id = table2.table1_id);


问:
Silverlight website
I am looking for develop a website in silverlight 4.
I am confused  about which silver light template in VS 2010 is best for creating silver light website[internet application]?
Which is best design pattern[mvc or mvvm] to implement the same silver light website.
please give your valuable suggestion . so i can move further.

Thanks in advance!!

答: I would go for the Silverlight Navigation Application template if you want more than one page!</p>

Title: Silverlight website


问:
Logging the username of a user that modifies values in a spreadsheet
So I have a large shared (OneDrive) Excel file where multiple people are meant to update the inputs of a model. I would like to log on each row the username and date of the last user who modified that row. Ideally I would need this to be a value, not a formula, because otherwise when another user opens the file the formula will change all usernames in the file change to theirs.

Any ideas?

答: As per the comments, excel.worksheet.change is what I was looking for thank you</p>


问:
How to use Postgres JSONB datatype with JPA?
Im not finding a way to map the JSON and JSONB datatypes from PostgreSQL using JPA (EclipseLink). Is some one using this datatypes with JPA and can give me some working examples?</p>

答:
For anyone looking for a Mysql solution with the JSON column type, here it is. FWIW I am using EclipseLink but this is a pure JPA solution.

```<code>@Column(name = "JSON_DATA", columnDefinition="JSON")
@Convert(converter=JsonAttributeConverter.class)
private Object jsonData;
</code>```

and

```<code>@Converter
public class JsonAttributeConverter implements AttributeConverter <Object, String>
{

    private JsonbConfig cfg = new JsonbConfig().withFormatting(true);

    private Jsonb jsonb = JsonbBuilder.create(cfg);

    @Override
    public String convertToDatabaseColumn(Object object)
    {
        if (object == null) return null;

        return jsonb.toJson(object);
    }

    @Override
    public Object convertToEntityAttribute(String value)
    {
        if (value == null) return null;

        return jsonb.fromJson(value, value.getClass());
    }

}
</code>```

Body:
For anyone looking for a Mysql solution with the JSON column type, here it is. FWIW I am using EclipseLink but this is a pure JPA solution.

@Column(name = "JSON_DATA", columnDefinition="JSON")
@Convert(converter=JsonAttributeConverter.class)
private Object jsonData;

and

@Converter
public class JsonAttributeConverter implements AttributeConverter <Object, String>
{

    private JsonbConfig cfg = new JsonbConfig().withFormatting(true);

    private Jsonb jsonb = JsonbBuilder.create(cfg);

    @Override
    public String convertToDatabaseColumn(Object object)
    {
        if (object == null) return null;

        return jsonb.toJson(object);
    }

    @Override
    public Object convertToEntityAttribute(String value)
    {
        if (value == null) return null;

        return jsonb.fromJson(value, value.getClass());
    }

}


问:
w: Detected multiple Kotlin daemon sessions at build/kotlin/sessions
Performing ./gradlew assembleRelease and hit the issue of this. Below shows the entire error log...

```<code>> Task :app:mergeDexRelease FAILED
java.nio.file.NoSuchFileException: /Users/path/Desktop/project/android/app/build/intermediates/external_file_lib_dex_archives/release/out
        at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:92)
        at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:111)
        at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:116)
        at java.base/sun.nio.fs.UnixFileSystemProvider.newDirectoryStream(UnixFileSystemProvider.java:412)
        at java.base/java.nio.file.Files.newDirectoryStream(Files.java:472)
        at java.base/java.nio.file.Files.list(Files.java:3699)
        at com.android.build.gradle.internal.tasks.DexMergingParams.getAllDexFiles(DexMergingTask.kt:502)
        at com.android.build.gradle.internal.tasks.DexMergingTaskRunnable.run(DexMergingTask.kt:423)
        at com.android.build.gradle.internal.tasks.Workers$ActionFacade.run(Workers.kt:335)
        at org.gradle.workers.internal.AdapterWorkAction.execute(AdapterWorkAction.java:57)
        at org.gradle.workers.internal.DefaultWorkerServer.execute(DefaultWorkerServer.java:63)
        at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1.create(NoIsolationWorkerFactory.java:66)
        at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1.create(NoIsolationWorkerFactory.java:62)
        at org.gradle.internal.classloader.ClassLoaderUtils.executeInClassloader(ClassLoaderUtils.java:98)
        at org.gradle.workers.internal.NoIsolationWorkerFactory$1.lambda$execute$0(NoIsolationWorkerFactory.java:62)
        at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:44)
        at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:41)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
        at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
        at org.gradle.workers.internal.AbstractWorker.executeWrappedInBuildOperation(AbstractWorker.java:41)
        at org.gradle.workers.internal.NoIsolationWorkerFactory$1.execute(NoIsolationWorkerFactory.java:59)
        at org.gradle.workers.internal.DefaultWorkerExecutor.lambda$submitWork$2(DefaultWorkerExecutor.java:198)
        at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
        at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runExecution(DefaultConditionalExecutionQueue.java:215)
        at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runBatch(DefaultConditionalExecutionQueue.java:164)
        at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.run(DefaultConditionalExecutionQueue.java:131)
        at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
        at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
        at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
        at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
        at java.base/java.lang.Thread.run(Thread.java:834)

w: Detected multiple Kotlin daemon sessions at build/kotlin/sessions

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:mergeDexRelease'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > java.nio.file.NoSuchFileException: /Users/path/Desktop/project/android/app/build/intermediates/external_file_lib_dex_archives/release/out
</code>```

Some story

During the debugging of this "multiple Koltin" issue, I found out that my NDK wasn't install. Hence I went to SDK Manager and install the NDK (Side by side). Then issue of toolchain occurred, shown as below.

```<code>No toolchains found in the NDK toolchains folder for ABI with prefix: arm-linux-androideabi
</code>```

Fixed was done by downloading older NDK version, android-ndk-r19c and pointed the NDK path in my local.properties.

Local.properties

```<code>sdk.dir=/Users/path/Library/Android/sdk
ndk.dir=/Users/path/Library/Android/android-ndk-r19c
</code>```

TLDR

What I've tried

./gradlew clean && ./gradlew assembleRelease

Appending the following code + Step 1

```<code># FILE 1: Gradle.properties
org.gradle.jvmargs=-Xmx4096m -XX:MaxPermSize=1024m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

# FILE 2: app/build.gradle ( under android{} )
dexOptions {
        incremental true
        javaMaxHeapSize "4g"
}
</code>```

My project env

```<code>react: 16.13.1 => 16.13.1
react-native: 0.63.2 => 0.63.2
</code>```

My Project Structure

Any idea what causes this issue and how to fix this?

答:
I solve this issue with this solution.

In gradle.properties add following code

```<code>org.gradle.daemon=true
org.gradle.configureondemand=true
org.gradle.jvmargs=-Xmx4g -XX:MaxPermSize=2048m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
</code>```

Additionally, insert these lines in app/build.gradle

```<code>android{

    dexOptions {
       javaMaxHeapSize "3g"
    }
}
</code>```

After making these changes run .\gradle clean and .\gradle assembleRelease

Body:
Performing ./gradlew assembleRelease and hit the issue of this. Below shows the entire error log...

> Task :app:mergeDexRelease FAILED
java.nio.file.NoSuchFileException: /Users/path/Desktop/project/android/app/build/intermediates/external_file_lib_dex_archives/release/out
        at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:92)
        at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:111)
        at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:116)
        at java.base/sun.nio.fs.UnixFileSystemProvider.newDirectoryStream(UnixFileSystemProvider.java:412)
        at java.base/java.nio.file.Files.newDirectoryStream(Files.java:472)
        at java.base/java.nio.file.Files.list(Files.java:3699)
        at com.android.build.gradle.internal.tasks.DexMergingParams.getAllDexFiles(DexMergingTask.kt:502)
        at com.android.build.gradle.internal.tasks.DexMergingTaskRunnable.run(DexMergingTask.kt:423)
        at com.android.build.gradle.internal.tasks.Workers$ActionFacade.run(Workers.kt:335)
        at org.gradle.workers.internal.AdapterWorkAction.execute(AdapterWorkAction.java:57)
        at org.gradle.workers.internal.DefaultWorkerServer.execute(DefaultWorkerServer.java:63)
        at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1.create(NoIsolationWorkerFactory.java:66)
        at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1.create(NoIsolationWorkerFactory.java:62)
        at org.gradle.internal.classloader.ClassLoaderUtils.executeInClassloader(ClassLoaderUtils.java:98)
        at org.gradle.workers.internal.NoIsolationWorkerFactory$1.lambda$execute$0(NoIsolationWorkerFactory.java:62)
        at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:44)
        at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:41)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
        at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
        at org.gradle.workers.internal.AbstractWorker.executeWrappedInBuildOperation(AbstractWorker.java:41)
        at org.gradle.workers.internal.NoIsolationWorkerFactory$1.execute(NoIsolationWorkerFactory.java:59)
        at org.gradle.workers.internal.DefaultWorkerExecutor.lambda$submitWork$2(DefaultWorkerExecutor.java:198)
        at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
        at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runExecution(DefaultConditionalExecutionQueue.java:215)
        at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runBatch(DefaultConditionalExecutionQueue.java:164)
        at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.run(DefaultConditionalExecutionQueue.java:131)
        at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
        at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
        at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
        at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
        at java.base/java.lang.Thread.run(Thread.java:834)

w: Detected multiple Kotlin daemon sessions at build/kotlin/sessions

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:mergeDexRelease'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > java.nio.file.NoSuchFileException: /Users/path/Desktop/project/android/app/build/intermediates/external_file_lib_dex_archives/release/out

Some story

During the debugging of this "multiple Koltin" issue, I found out that my NDK wasn't install. Hence I went to SDK Manager and install the NDK (Side by side). Then issue of toolchain occurred, shown as below.

No toolchains found in the NDK toolchains folder for ABI with prefix: arm-linux-androideabi

Fixed was done by downloading older NDK version, android-ndk-r19c and pointed the NDK path in my local.properties.

Local.properties

sdk.dir=/Users/path/Library/Android/sdk
ndk.dir=/Users/path/Library/Android/android-ndk-r19c

TLDR

What I've tried

./gradlew clean && ./gradlew assembleRelease

Appending the following code + Step 1

# FILE 1: Gradle.properties
org.gradle.jvmargs=-Xmx4096m -XX:MaxPermSize=1024m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

# FILE 2: app/build.gradle ( under android{} )
dexOptions {
        incremental true
        javaMaxHeapSize "4g"
}

My project env

react: 16.13.1 => 16.13.1
react-native: 0.63.2 => 0.63.2

My Project Structure

Any idea what causes this issue and how to fix this?

Body:
I solve this issue with this solution.

In gradle.properties add following code

org.gradle.daemon=true
org.gradle.configureondemand=true
org.gradle.jvmargs=-Xmx4g -XX:MaxPermSize=2048m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

Additionally, insert these lines in app/build.gradle

android{

    dexOptions {
       javaMaxHeapSize "3g"
    }
}

After making these changes run .\gradle clean and .\gradle assembleRelease


问:
Why doesn't nested parameter expansion work correctly in GitLab CI/CD?
Using a bash runner, is there any reason why the following variable expansion shouldn't work?

```<code>variables:
  GIT_BRANCH: "${CI_MERGE_REQUEST_SOURCE_BRANCH_NAME:-${CI_COMMIT_BRANCH:-$CI_DEFAULT_BRANCH}}"

job1:
  script:
    - echo $GIT_BRANCH
</code>```

The job outputs }.

I'm using GitLab Enterprise Edition 14.1.8-ee.

答:
As stated by the other answers, this syntax won't expand how you expect. As a workaround, you might be able to use rules:variables: to get the same effect.

my_job:
  rules:
    - if: '$CI_MERGE_REQUEST_SOURCE_BRANCH_NAME'
      variables:
        GIT_BRANCH: $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME
    - if: '$CI_COMMIT_BRANCH'
      variables:
        GIT_BRANCH: $CI_COMMIT_BRANCH
    - when: on_success
  variables:
    GIT_BRANCH: $CI_DEFAULT_BRANCH
```

You could also consider simply setting the variable directly in the job script using export. Then the bash variable expansion will work as expected.

Body:
Using a bash runner, is there any reason why the following variable expansion shouldn't work?

variables:
  GIT_BRANCH: "${CI_MERGE_REQUEST_SOURCE_BRANCH_NAME:-${CI_COMMIT_BRANCH:-$CI_DEFAULT_BRANCH}}"

job1:
  script:
    - echo $GIT_BRANCH

The job outputs }.

I'm using GitLab Enterprise Edition 14.1.8-ee.

Body:
As stated by the other answers, this syntax won't expand how you expect. As a workaround, you might be able to use rules:variables: to get the same effect.

my_job:
  rules:
    - if: '$CI_MERGE_REQUEST_SOURCE_BRANCH_NAME'
      variables:
        GIT_BRANCH: $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME
    - if: '$CI_COMMIT_BRANCH'
      variables:
        GIT_BRANCH: $CI_COMMIT_BRANCH
    - when: on_success
  variables:
    GIT_BRANCH: $CI_DEFAULT_BRANCH

You could also consider simply setting the variable directly in the job script using export. Then the bash variable expansion will work as expected.


问:
Automatically expand JTree to until height threshold is met
I have a JTree on a JScrollPane as part of my GUI. I've set up an AncestorListener where I respond to the ancestorAdded event. In the event, I would like to automatically expand as many  visible nodes as possible. By visible, I mean that I want to expand as many nodes as possible such that the total height of the tree does not exceed the maximum height of the JScrollPane's viewport. If my viewport had 500px of visible space, I want the tree expanded until the total expanded height is less than or equal to 500px.

I've tried to achieve this a few different ways. It boils down to this: I can't seem to retrieve an updated height for the tree after programatically expanding a node. How can I recalculate the height of the tree? tree.getHeight(), for example, always returns the same value even after I expand a node. Invoking tree.invalidate() between calculations didn't help either.

答:
How can I recalculate the height of the tree?

Maybe getVisibleRowCount()*getRowHeight() will give you the correct size.

The documentation for getRowHeight() states that it may return <= 0 and leave the row height up to the renderer, which may be the case for you as you're using a JTreeTable.


问:
How to check HTTP status of a file online without fully downloading the file?
I have a database of thousands of files online, and I want to check what their status is (e.g. if the file exists, if it sends us to a 404, etc.) and update this in my database.

I've used urllib.request to download files to a python script. However, obviously downloading terabytes of files is going to take a long time. Parallelizing the process would help, but ultimately I just don't want to download all the data, just check the status. Is there an ideal way to check (using urllib or another package) the HTTP response code of a certain URL?

Additionally, if I can get the file size from the server (which would be in the HTTP response), then I can also update this in my database.

答:
The requests module can check the status response of a request.
Just do:

```<code>import requests

url = 'https://www.google.com'  # Change to your link
response = requests.get(url)
print(response.status_code)
</code>```

this code shows me 200, so the request has been successful

Body:
The requests module can check the status response of a request.
Just do:

import requests

url = 'https://www.google.com'  # Change to your link
response = requests.get(url)
print(response.status_code)

this code shows me 200, so the request has been successful


问:
Click button in Cisco Anyconnect login prompt using Python
I am writing a Python script to auto login to my company's VPN at startup if certain network conditions are met. We use Cisco AnyConnect Secure Mobility Client to connect.

Due to the MFA method used for the vpn (Azure), I cannot use the vpncli tool that comes with Anyconnect to handle the connection.
This means I need to use the vpn UI and click a "Connect" button in the prompt.

I've seen people use Selenium for this in web browsers, but this isn't a browser prompt.

Does anyone know if there is a way to do this programmatically?

Thanks,

Josh

答: It sounds like Sikuli(X) is what you want. I haven't used it, but it seems like doing what you want with it should be relatively straightforward, as indicated by this tutorial.</p>


问:
MySQL select all rows from last N groups
I have a dataset like this, where there can be multiple transactions per trade

```<code>| tx_id | trade_id |
--------------------
| 100   | 11       |
| 99    | 11       |
| 98    | 11       |
| 97    | 10       |
| 96    | 10       |
| 95    | 9        |
| 94    | 9        |
| 93    | 8        |
...
</code>```

I want to select all of the transactions from the last N trades. For instance if I wanted to select all rows from the last 2 trades, I would get:

```<code>| tx_id | trade_id |
--------------------
| 100   | 11       |
| 99    | 11       |
| 98    | 11       |
| 97    | 10       |
| 96    | 10       |
</code>```

I cannot guarantee that the trade_id will always have an interval of 1.

How can I accomplish this in mysql?

答:
This will also work with mysql 5

Changing the linit , you can choose how many trades you want to receive

```<code>CREATE TABLE tab1 (
  `tx_id` INTEGER,
  `trade_id` INTEGER
);

INSERT INTO tab1
  (`tx_id`, `trade_id`)
VALUES
  ('100', '11'),
  ('99', '11'),
  ('98', '11'),
  ('97', '10'),
  ('96', '10'),
  ('95', '9'),
  ('94', '9'),
  ('93', '8');
</code>```

```<code>SELECT t1.* FROM tab1 t1 JOIN (SELECT DISTINCT `trade_id` FROM tab1 ORDER BY `trade_id`  DESC LIMIT 2) t2
ON t1.`trade_id` = t2.`trade_id`
</code>```
```
tx_id | trade_id
----: | -------:
  100 |       11
   99 |       11
   98 |       11
   97 |       10
   96 |       10
```

db<>fiddle here

Body:
I have a dataset like this, where there can be multiple transactions per trade

| tx_id | trade_id |
--------------------
| 100   | 11       |
| 99    | 11       |
| 98    | 11       |
| 97    | 10       |
| 96    | 10       |
| 95    | 9        |
| 94    | 9        |
| 93    | 8        |
...

I want to select all of the transactions from the last N trades. For instance if I wanted to select all rows from the last 2 trades, I would get:

| tx_id | trade_id |
--------------------
| 100   | 11       |
| 99    | 11       |
| 98    | 11       |
| 97    | 10       |
| 96    | 10       |

I cannot guarantee that the trade_id will always have an interval of 1.

How can I accomplish this in mysql?

Body:
This will also work with mysql 5

Changing the linit , you can choose how many trades you want to receive

CREATE TABLE tab1 (
  `tx_id` INTEGER,
  `trade_id` INTEGER
);

INSERT INTO tab1
  (`tx_id`, `trade_id`)
VALUES
  ('100', '11'),
  ('99', '11'),
  ('98', '11'),
  ('97', '10'),
  ('96', '10'),
  ('95', '9'),
  ('94', '9'),
  ('93', '8');

SELECT t1.* FROM tab1 t1 JOIN (SELECT DISTINCT `trade_id` FROM tab1 ORDER BY `trade_id`  DESC LIMIT 2) t2
ON t1.`trade_id` = t2.`trade_id`

tx_id | trade_id
----: | -------:
  100 |       11
   99 |       11
   98 |       11
   97 |       10
   96 |       10

db<>fiddle here


问:
An item with the same key has already been added
I get this error whenever I submit the form also the action method is not being called because of this:

An item with the same key has already been added.

And the exception details:

[ArgumentException: An item with the
  same key has already been added.]

  System.ThrowHelper.ThrowArgumentException(ExceptionResource
  resource) +52

  System.Collections.Generic.Dictionary`2.Insert(TKey
  key, TValue value, Boolean add)
  +9382923    System.Linq.Enumerable.ToDictionary(IEnumerable`1
  source, Func`2 keySelector, Func`2
  elementSelector, IEqualityComparer`1
  comparer) +252

  System.Linq.Enumerable.ToDictionary(IEnumerable`1
  source, Func`2 keySelector,
  IEqualityComparer`1 comparer) +91

  System.Web.Mvc.ModelBindingContext.get_PropertyMetadata()
  +228    System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext
  controllerContext, ModelBindingContext
  bindingContext, PropertyDescriptor
  propertyDescriptor) +392

  System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext
  controllerContext, ModelBindingContext
  bindingContext) +147

  System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext
  controllerContext, ModelBindingContext
  bindingContext, Object model) +98

  System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext
  controllerContext, ModelBindingContext
  bindingContext) +2504

  System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext
  controllerContext, ModelBindingContext
  bindingContext) +548

  System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext
  controllerContext, ParameterDescriptor
  parameterDescriptor) +473

  System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext
  controllerContext, ActionDescriptor
  actionDescriptor) +181

  System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext
  controllerContext, String actionName)
  +830    System.Web.Mvc.Controller.ExecuteCore()
  +136    System.Web.Mvc.ControllerBase.Execute(RequestContext
  requestContext) +111

  System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext
  requestContext) +39

  System.Web.Mvc.<>c__DisplayClass8.b__4()
  +65    System.Web.Mvc.Async.<>c__DisplayClass1.b__0()
  +44    System.Web.Mvc.Async.<>c__DisplayClass8`1.b__7(IAsyncResult
  _) +42    System.Web.Mvc.Async.WrappedAsyncResult`1.End()
  +141    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult
  asyncResult, Object tag) +54

  System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult
  asyncResult, Object tag) +40

  System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult
  asyncResult) +52

  System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult
  result) +38

  System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
  +8836913    System.Web.HttpApplication.ExecuteStep(IExecutionStep
  step, Boolean& completedSynchronously)
  +184

ViewPage

```<code><%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/XYZ.Master"
    Inherits="System.Web.Mvc.ViewPage<XYZ.Models.Admin.AdminSegmentCommissionsModel>" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
        Create
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
        <% using (Html.BeginForm()) {%>
            <div class="box3">
                <div class="userinfo">
                    <h3>Admin Segment Commissions</h3>
                </div>
                <div class="buttons-panel">
                    <ul>
                       <li>
                           <input type="submit" value="Save" class="save" />
                       </li>
                       <li>
                           <%:Html.ActionLink("Cancel", "Index", new { controller = "AdminSegmentCommissions" }, new { @class = "cancel" })%>
                           <%--<input type="button" value="Cancel" class="cancel" onclick="document.location.href='/AirlineLedgerTransactionReceiver/Index'" />--%>
                       </li>
                   </ul>
               </div>
           </div>
           <div class="row-1">
               <div class="form-box1 round-corner">
                   <div class="form-box1-row">
                       <div class="form-box1-row-content float-left">
                           <div>
                               <label>
                                   <%: Html.LabelFor(model => model.FromSegmentNumber) %></label>
                                   <%: Html.TextBoxFor(model => model.FromSegmentNumber) %>
                                   <%: Html.ValidationMessageFor(model => model.FromSegmentNumber) %>
                          </div>
                      </div>
                  </div>
              </div>
          </div>
      <%} %>
</code>```

答: I had the same issue when executing a Stord Procedure and It has been returned two columns with the same name. When mapping that column inside the model class there is a conflict. To solve that issue always use unique names for returned columns.</p>

Body:
I get this error whenever I submit the form also the action method is not being called because of this:

An item with the same key has already been added.

And the exception details:

[ArgumentException: An item with the
  same key has already been added.]

  System.ThrowHelper.ThrowArgumentException(ExceptionResource
  resource) +52

  System.Collections.Generic.Dictionary`2.Insert(TKey
  key, TValue value, Boolean add)
  +9382923    System.Linq.Enumerable.ToDictionary(IEnumerable`1
  source, Func`2 keySelector, Func`2
  elementSelector, IEqualityComparer`1
  comparer) +252

  System.Linq.Enumerable.ToDictionary(IEnumerable`1
  source, Func`2 keySelector,
  IEqualityComparer`1 comparer) +91

  System.Web.Mvc.ModelBindingContext.get_PropertyMetadata()
  +228    System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext
  controllerContext, ModelBindingContext
  bindingContext, PropertyDescriptor
  propertyDescriptor) +392

  System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext
  controllerContext, ModelBindingContext
  bindingContext) +147

  System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext
  controllerContext, ModelBindingContext
  bindingContext, Object model) +98

  System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext
  controllerContext, ModelBindingContext
  bindingContext) +2504

  System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext
  controllerContext, ModelBindingContext
  bindingContext) +548

  System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext
  controllerContext, ParameterDescriptor
  parameterDescriptor) +473

  System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext
  controllerContext, ActionDescriptor
  actionDescriptor) +181

  System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext
  controllerContext, String actionName)
  +830    System.Web.Mvc.Controller.ExecuteCore()
  +136    System.Web.Mvc.ControllerBase.Execute(RequestContext
  requestContext) +111

  System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext
  requestContext) +39

  System.Web.Mvc.<>c__DisplayClass8.b__4()
  +65    System.Web.Mvc.Async.<>c__DisplayClass1.b__0()
  +44    System.Web.Mvc.Async.<>c__DisplayClass8`1.b__7(IAsyncResult
  _) +42    System.Web.Mvc.Async.WrappedAsyncResult`1.End()
  +141    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult
  asyncResult, Object tag) +54

  System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult
  asyncResult, Object tag) +40

  System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult
  asyncResult) +52

  System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult
  result) +38

  System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
  +8836913    System.Web.HttpApplication.ExecuteStep(IExecutionStep
  step, Boolean& completedSynchronously)
  +184

ViewPage

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/XYZ.Master"
    Inherits="System.Web.Mvc.ViewPage<XYZ.Models.Admin.AdminSegmentCommissionsModel>" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
        Create
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
        <% using (Html.BeginForm()) {%>

Admin Segment Commissions

                           <input type="submit" value="Save" class="save" />

                           <%:Html.ActionLink("Cancel", "Index", new { controller = "AdminSegmentCommissions" }, new { @class = "cancel" })%>
                           <%--<input type="button" value="Cancel" class="cancel" onclick="document.location.href='/AirlineLedgerTransactionReceiver/Index'" />--%>

                                   <%: Html.LabelFor(model => model.FromSegmentNumber) %>
                                   <%: Html.TextBoxFor(model => model.FromSegmentNumber) %>
                                   <%: Html.ValidationMessageFor(model => model.FromSegmentNumber) %>

      <%} %>


问:
Calculating distance from centroid to another point in Python
I have a data frame like below

```<code>STORE_ID LATITUDE LONGITUDE GROUP
1        18.2738  28.38833  2
2        18.3849  28.29374  1
3        18.3948  28.29303  1
4        18.1949  28.28248  1
5        18.2947  28.47392  1
6        18.7493  28.29475  2
7        18.4729  28.38392  3
8        18.1927  28.29485  2
9        18.2948  28.29384  1
10       18.1038  28.29489  3
11       18.7482  28.29374  1
12       18.9283  28.28484  2
</code>```

And a second data frame like below

```<code>Tele_Booth_ID LATITUDE LONGITUDE
1             18.5638  28.19374
2             18.2947  28.03727
3             18.3849  28.26395
4             18.9482  28.91847
</code>```

The first data frame has longitudes and latitudes of stores in a certain area. The store are grouped together into clusters represented by the GROUP field.

The second dataframe has longitudes and latitudes for telephone booths in that same area.

Using both these data frames I want to find the optimal locations to place more telephone booths.

If a store group has no telephone booths in the cluster or near the cluster, I would want to put a booth there. If a store group has a booth within the cluster, I would not want another booth there.

Using python how can I calculate the center point for each store group and then calculate the distance of each store group to the nearest booth?

答:
While I am unsure of how accurate the computation of the centroid of point might be, using the ability to group on store groups You can create a new dataframe which contains the mean of the Lat and Lon of each group as follows:

Given a df1 as shown:

```<code>    Store   Lat Lon Group
0   1   18.2738 28.38833    2
1   3   18.3948 28.29303    1
2   4   18.1949 28.28248    1
3   5   18.2947 28.47392    1
4   6   18.7493 28.29475    2
5   7   18.4729 28.38392    3
6   8   18.1927 28.29485    2
7   9   18.2948 28.29384    1
8   10  18.1038 28.29489    3
9   11  18.7482 28.29374    1
10  12  18.9283 28.28484    2
</code>```

Create a Dataframe of centered Lat and Lon as follows:

```<code>dfc = df1.groupby('Group').Lat.mean().to_frame().join(df1.groupby('Group').Lon.mean().to_frame())
</code>```

This will yield the dfc dataframe shown below:

```<code>         Lat    Lon
Group
1   18.385480   28.327402
2   18.536025   28.315693
3   18.288350   28.339405
</code>```

You can now utilize these mean Lat/Lon points to compute distance to Telephone booths as follows:

The booth dataframe is df2 shown below:

```<code>    Booth   Lat Lon
0   1   18.5638 28.19374
1   2   18.2947 28.03727
2   3   18.3849 28.26395
3   4   18.9482 28.91847

# to compute the distance between two sets of coordinates
def dist(loc1: tuple[float], loc2: tuple[float]) -> float:
    dx = loc1[0] - loc2[0]
    dy = loc1[1] - loc2[1]
    return (dx**2 + dy**2)**0.5
</code>```

Using the above compute distance from each group centroid to each booth as follows:

```<code>for i in range(df2.shape[0]):
    dfc[f'B-{i+1:02}'] = dfc.apply(lambda row: dist((row.Lat, row.Lon), tuple(df2.iloc[i].to_list()[1:])), axis=1)
</code>```

This yields the following:

```<code>       Lat       Lon        B-01        B-02        B-03           B-04
Group
1   18.385480   28.327402   0.222853    0.304003    0.063455    0.816098
2   18.536025   28.315693   0.125075    0.368452    0.159737    0.730225
3   18.288350   28.339405   0.311594    0.302202    0.122537    0.877906
</code>```

Body:
I have a data frame like below

STORE_ID LATITUDE LONGITUDE GROUP
1        18.2738  28.38833  2
2        18.3849  28.29374  1
3        18.3948  28.29303  1
4        18.1949  28.28248  1
5        18.2947  28.47392  1
6        18.7493  28.29475  2
7        18.4729  28.38392  3
8        18.1927  28.29485  2
9        18.2948  28.29384  1
10       18.1038  28.29489  3
11       18.7482  28.29374  1
12       18.9283  28.28484  2

And a second data frame like below

Tele_Booth_ID LATITUDE LONGITUDE
1             18.5638  28.19374
2             18.2947  28.03727
3             18.3849  28.26395
4             18.9482  28.91847

The first data frame has longitudes and latitudes of stores in a certain area. The store are grouped together into clusters represented by the GROUP field.

The second dataframe has longitudes and latitudes for telephone booths in that same area.

Using both these data frames I want to find the optimal locations to place more telephone booths.

If a store group has no telephone booths in the cluster or near the cluster, I would want to put a booth there. If a store group has a booth within the cluster, I would not want another booth there.

Using python how can I calculate the center point for each store group and then calculate the distance of each store group to the nearest booth?

Body:
While I am unsure of how accurate the computation of the centroid of point might be, using the ability to group on store groups You can create a new dataframe which contains the mean of the Lat and Lon of each group as follows:

Given a df1 as shown:

    Store   Lat Lon Group
0   1   18.2738 28.38833    2
1   3   18.3948 28.29303    1
2   4   18.1949 28.28248    1
3   5   18.2947 28.47392    1
4   6   18.7493 28.29475    2
5   7   18.4729 28.38392    3
6   8   18.1927 28.29485    2
7   9   18.2948 28.29384    1
8   10  18.1038 28.29489    3
9   11  18.7482 28.29374    1
10  12  18.9283 28.28484    2

Create a Dataframe of centered Lat and Lon as follows:

dfc = df1.groupby('Group').Lat.mean().to_frame().join(df1.groupby('Group').Lon.mean().to_frame())

This will yield the dfc dataframe shown below:

         Lat    Lon
Group
1   18.385480   28.327402
2   18.536025   28.315693
3   18.288350   28.339405

You can now utilize these mean Lat/Lon points to compute distance to Telephone booths as follows:

The booth dataframe is df2 shown below:

    Booth   Lat Lon
0   1   18.5638 28.19374
1   2   18.2947 28.03727
2   3   18.3849 28.26395
3   4   18.9482 28.91847

# to compute the distance between two sets of coordinates
def dist(loc1: tuple[float], loc2: tuple[float]) -> float:
    dx = loc1[0] - loc2[0]
    dy = loc1[1] - loc2[1]
    return (dx**2 + dy**2)**0.5

Using the above compute distance from each group centroid to each booth as follows:

for i in range(df2.shape[0]):
    dfc[f'B-{i+1:02}'] = dfc.apply(lambda row: dist((row.Lat, row.Lon), tuple(df2.iloc[i].to_list()[1:])), axis=1)

This yields the following:

       Lat       Lon        B-01        B-02        B-03           B-04
Group
1   18.385480   28.327402   0.222853    0.304003    0.063455    0.816098
2   18.536025   28.315693   0.125075    0.368452    0.159737    0.730225
3   18.288350   28.339405   0.311594    0.302202    0.122537    0.877906


问:
Mock an external service instantiated in python constructor
I'm working on unit tests for a service I made that uses confluent-kafka. The goal is to test successful function calls, exception errors, etc. The problem I'm running into is since I'm instantiating the client in the constructor of my service the tests are failing since I'm unsure how to patch a constructor. My question is how do I mock my service in order to properly test its functionality.

Example_Service.py:

```<code>from confluent_kafka.schema_registry import SchemaRegistryClient

class ExampleService:
  def __init__(self, config):
    self.service = SchemaRegistryClient(config)

  def get_schema(self):
    return self.service.get_schema()
</code>```

Example_Service_tests.py

```<code>from unittest import mock

@mock.patch.object(SchemaRegistryClient, "get_schema")
def test_get_schema_success(mock_client):
    schema_Id = ExampleService.get_schema()
    mock_service.assert_called()
</code>```

答:
The problem is that you aren't creating an instance of ExampleService; __init__ never gets called.

You can avoid patching anything by allowing your class to accept a client maker as an argument (which can default to SchemaRegistryClient:

```<code>class ExampleService:
    def __init__(self, config, *, client_factory=SchemaRegistryClient):
        self.service = client_factory(config)

    ...
</code>```

Then in your test, you can simply pass an appropriate stub as an argument:

```<code>def test_get_schema_success():
    mock_client = Mock()
    schema_Id = ExampleService(some_config, client_factory=mock_client)
    mock_client.assert_called()
</code>```

Body:
I'm working on unit tests for a service I made that uses confluent-kafka. The goal is to test successful function calls, exception errors, etc. The problem I'm running into is since I'm instantiating the client in the constructor of my service the tests are failing since I'm unsure how to patch a constructor. My question is how do I mock my service in order to properly test its functionality.

Example_Service.py:

from confluent_kafka.schema_registry import SchemaRegistryClient

class ExampleService:
  def __init__(self, config):
    self.service = SchemaRegistryClient(config)

  def get_schema(self):
    return self.service.get_schema()

Example_Service_tests.py

from unittest import mock

@mock.patch.object(SchemaRegistryClient, "get_schema")
def test_get_schema_success(mock_client):
    schema_Id = ExampleService.get_schema()
    mock_service.assert_called()

Body:
The problem is that you aren't creating an instance of ExampleService; __init__ never gets called.

You can avoid patching anything by allowing your class to accept a client maker as an argument (which can default to SchemaRegistryClient:

class ExampleService:
    def __init__(self, config, *, client_factory=SchemaRegistryClient):
        self.service = client_factory(config)

    ...

Then in your test, you can simply pass an appropriate stub as an argument:

def test_get_schema_success():
    mock_client = Mock()
    schema_Id = ExampleService(some_config, client_factory=mock_client)
    mock_client.assert_called()


问:
Should a internal C# app be compiled with business logic?
[background]

So, I've got a C# application that was written before I got here.  I'm not in the dev org, at this time, but I am the tech lead in my sub-group within the internet marketing org.  My responsibility is process automation, minimal desktop support, and custom apps that make our lives easier.

[/background]

[app details]

We've got an app that creates a custom database file from a list of URLs.  It was designed to have one input file, and two output files for the two applications that use these sort of db files.  The rule for the difference between the two output files is compiled into the code.

[/app details]

Should an internal C# app be compiled with business logic that can't be changed without it being re-built?

答:
If the logic does not need to be changed then yes it should probably be compiled along with the code.

On the other hand if there are certain factors that could change the behavior of this business logic then you should probably provide a mean of changing it such as xml configuration files that alter its behavior.

OwnerDisplayName: Sean Ochoa

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Konstantinos


问:
Import Images from File delphi
I'm familiar with delphi scripting so I basically need a strong direction to start from. I've done importing images from files in other languages and it has been quite trivial, but I can find little documentation about this for delphi.

I need to be able to register a control event on a button that will open up a "choose folder/file" dialouge, and then import an image into an object that I can append to a List of some sort.

Anyone have any documentation on this?

答:
Although your question is rather broad and "delphi scripting" sounds interesting here is an example that might get you started:

Project: Let the user select an image and display this image

This form contains a TButton, a TOpenPictureDialog and a simple TImage for displaying one image (sorry, no list of pictures in this example).

Part 1 ("register a control event on a button"):

Attach an OnClick event handler to the button by double clicking the button in the form designer. If your button's Name is btnOpenPicture then the auto-generated handler will have the name btnOpenPictureClick (see the following code). The code in this handler will be executed when the user clicks the button.

```<code>procedure TForm1.btnOpenPictureClick(Sender: TObject);
begin
  if OpenPictureDialog1.Execute(Self.Handle) then
    Image1.Picture.LoadFromFile(OpenPictureDialog1.FileName);
end;
</code>```

Part 2 ("'choose folder/file' dialouge") is represented by OpenPictureDialog1.Execute which opens a dialog where the user can choose a picture. The Execute command waits until the user closes the dialog and returns True if the user chose not to cancel the dialog but rather chose an image file (the filename is stored in OpenPictureDialog1.FileName).

Part 3 ("import an image into an object") would then be Image1.Picture.LoadFromFile which instructs the TImage component to load and display the file the user chose.

I cannot immediately name a component included in Delphi which could be used easily as a list for displaying images visually (that's your "append to a List of some sort"). I only know some third-party components which are not available for free, thus not good for quick experimenting.

Maybe this can be a base for asking more specific questions (as already encouraged by the commentators of your question). I already have one: "Is there a VCL component I could use for displaying a list of images?"

Title: Import Images from File delphi

Body:
Although your question is rather broad and "delphi scripting" sounds interesting here is an example that might get you started:

Project: Let the user select an image and display this image

This form contains a TButton, a TOpenPictureDialog and a simple TImage for displaying one image (sorry, no list of pictures in this example).

Part 1 ("register a control event on a button"):

Attach an OnClick event handler to the button by double clicking the button in the form designer. If your button's Name is btnOpenPicture then the auto-generated handler will have the name btnOpenPictureClick (see the following code). The code in this handler will be executed when the user clicks the button.

procedure TForm1.btnOpenPictureClick(Sender: TObject);
begin
  if OpenPictureDialog1.Execute(Self.Handle) then
    Image1.Picture.LoadFromFile(OpenPictureDialog1.FileName);
end;

Part 2 ("'choose folder/file' dialouge") is represented by OpenPictureDialog1.Execute which opens a dialog where the user can choose a picture. The Execute command waits until the user closes the dialog and returns True if the user chose not to cancel the dialog but rather chose an image file (the filename is stored in OpenPictureDialog1.FileName).

Part 3 ("import an image into an object") would then be Image1.Picture.LoadFromFile which instructs the TImage component to load and display the file the user chose.

I cannot immediately name a component included in Delphi which could be used easily as a list for displaying images visually (that's your "append to a List of some sort"). I only know some third-party components which are not available for free, thus not good for quick experimenting.

Maybe this can be a base for asking more specific questions (as already encouraged by the commentators of your question). I already have one: "Is there a VCL component I could use for displaying a list of images?"


问:
Pyspark Cumulative sum within Partition for moving last 2 (N) rows
Let's say I have the following dataframe which is sorted for ease visually:

How would I utilize window functions to create a new column that sums the previous row ordered by Month column within each period partition:

The following is my attempt at it, but I'm obviously doing something wrong with respect to the rowsBetween function.

```<code>df = df.withColumn('CustLast2', sum('Cust').over(Window.partitionBy("period").orderBy('Month').rowsBetween(Window.currentRow, -1))
</code>```

答:
You can solve this problem using the code below:</p>
```<code>(df.withColumn('last_value', F.lag(F.col('Cust')).over(W.partitionBy(['Period']).orderBy(F.col('Month'))))
   .withColumn('last_value', F.when(F.col('last_value').isNull(), 0).otherwise(F.col('last_value')))
   .withColumn('cumSum', F.col('Cust') + F.col('last_value')))
</code>```

Body:
Let's say I have the following dataframe which is sorted for ease visually:

How would I utilize window functions to create a new column that sums the previous row ordered by Month column within each period partition:

The following is my attempt at it, but I'm obviously doing something wrong with respect to the rowsBetween function.

df = df.withColumn('CustLast2', sum('Cust').over(Window.partitionBy("period").orderBy('Month').rowsBetween(Window.currentRow, -1))

Body:
You can solve this problem using the code below:

(df.withColumn('last_value', F.lag(F.col('Cust')).over(W.partitionBy(['Period']).orderBy(F.col('Month'))))
   .withColumn('last_value', F.when(F.col('last_value').isNull(), 0).otherwise(F.col('last_value')))
   .withColumn('cumSum', F.col('Cust') + F.col('last_value')))


问:
Python Overridden __add__ Doesn't Work for a += b
I've been working on a Vector object class to allow me to solve math problems quickly using Python.

For Example:
If we set vector = Vector(1, 2, 3) and we run vector *= 2, then vector will be equal to <2, 4, 6>

The Issue: Whenever I run vector += 2, it errors saying

```<code>Traceback (most recent call last):
  File "C:\Users\User\PycharmProjects\Math\matrices.py", line 149, in <module>
    main()
  File "C:\Users\User\PycharmProjects\Math\matrices.py", line 139, in main
    vector += 2
TypeError: 'int' object is not iterable

Process finished with exit code 1
</code>```

Here is my Vector class

```<code>class Vector(list):
    def __init__(self, *args):
        super().__init__()
        for arg in args:
            self.append(arg)

    def __mul__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        return Vector(*[row * other for row in self])

    def __truediv__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        return Vector(*[row / other for row in self])

    def __add__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        print(type(other))
        return Vector(*[row + other for row in self])

    def __sub__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        return Vector(*[row - other for row in self])

    def __str__(self):
        return "<" + ", ".join([str(e) for e in self]) + ">"
</code>```

Here is my main function

```<code>def main():
    vector = Vector(1, 2, 3)
    vector *= 2
    print(vector)
    vector += 2
    print(vector)
</code>```

What I've done to find the solution:

I've tried to do vector = vector + 2 and that works, but I would
rather understand why it's not working and be able to fix it.

I've tried googling how operator overloading works in Python

I've tried looking through operator overloading threads on StackOverflow, but I don't see any that answer my question. They're all about how a = a + b, not a += b.

I've tried using iadd, but it doesn't work.

答:
Just add the line __iadd__ = __add__:

class Vector(list):
    def __init__(self, *args):
        super().__init__()
        for arg in args:
            self.append(arg)

    def __mul__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        return Vector(*[row * other for row in self])

    def __truediv__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        return Vector(*[row / other for row in self])

    def __add__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        print(type(other))
        return Vector(*[row + other for row in self])

    __iadd__ = __add__

    def __sub__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        return Vector(*[row - other for row in self])

    def __str__(self):
        return "<" + ", ".join([str(e) for e in self]) + ">"

vector = Vector(1, 2, 3)
vector *= 2
print(vector)
vector += 2
print(vector)
```
<p>Prints:</p>
```<2, 4, 6>
<class 'int'>
<4, 6, 8>
```

Body:
I've been working on a Vector object class to allow me to solve math problems quickly using Python.

For Example:
If we set vector = Vector(1, 2, 3) and we run vector *= 2, then vector will be equal to <2, 4, 6>

The Issue: Whenever I run vector += 2, it errors saying

Traceback (most recent call last):
  File "C:\Users\User\PycharmProjects\Math\matrices.py", line 149, in <module>
    main()
  File "C:\Users\User\PycharmProjects\Math\matrices.py", line 139, in main
    vector += 2
TypeError: 'int' object is not iterable

Process finished with exit code 1

Here is my Vector class

class Vector(list):
    def __init__(self, *args):
        super().__init__()
        for arg in args:
            self.append(arg)

    def __mul__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        return Vector(*[row * other for row in self])

    def __truediv__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        return Vector(*[row / other for row in self])

    def __add__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        print(type(other))
        return Vector(*[row + other for row in self])

    def __sub__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        return Vector(*[row - other for row in self])

    def __str__(self):
        return "<" + ", ".join([str(e) for e in self]) + ">"

Here is my main function

def main():
    vector = Vector(1, 2, 3)
    vector *= 2
    print(vector)
    vector += 2
    print(vector)

What I've done to find the solution:

I've tried to do vector = vector + 2 and that works, but I would
rather understand why it's not working and be able to fix it.

I've tried googling how operator overloading works in Python

I've tried looking through operator overloading threads on StackOverflow, but I don't see any that answer my question. They're all about how a = a + b, not a += b.

I've tried using iadd, but it doesn't work.

Body:
Just add the line __iadd__ = __add__:

class Vector(list):
    def __init__(self, *args):
        super().__init__()
        for arg in args:
            self.append(arg)

    def __mul__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        return Vector(*[row * other for row in self])

    def __truediv__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        return Vector(*[row / other for row in self])

    def __add__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        print(type(other))
        return Vector(*[row + other for row in self])

    __iadd__ = __add__

    def __sub__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        return Vector(*[row - other for row in self])

    def __str__(self):
        return "<" + ", ".join([str(e) for e in self]) + ">"

vector = Vector(1, 2, 3)
vector *= 2
print(vector)
vector += 2
print(vector)

Prints:

<2, 4, 6>
<class 'int'>
<4, 6, 8>


问:
Create an array of objects from another array grouping duplicates in Javascript
I need to re-organize an array of objects (from a database) into different groups according to one of the attributes of objects. To make it clearer, let's take the following example:

The ORM (Sequelize) returns the following array object:

```<code>[
  {
    id: 182,
    employeeId: 'a',
    skillId: 207,
    score: 3,
  },
  {
    id: 512,
    employeeId: 'a',
    skillId: 212,
    score: 4,
  },
  {
    id: 908,
    employeeId: 'b',
    skillId: 134,
    score: 2,
  },
  {
    id: 876,
    employeeId: 'c',
    skillId: 212,
    score: 3,
  },
]
</code>```

I need to re-categorize the object grouping the entries by employeeId. Like this:

```<code>[
  {
    employeeId: 'a',
    skills:
           [
             { skillId: 203, score: 3},
             { skillId: 212, score: 4}
           ]
  },
  {
    employeeId: 'b',
    skills:
           [
             { skillId: 134, score: 2}
           ]
   },
   {
    employeeId: 'c',
    skills:
           [
             { skillId: 212, score: 3}
           ]
   }
]
</code>```

It didn't look hard at first but I'm hitting a roadblock, I already tried using reduce, forEarch and map but I only got to make an array of employeeIds, can't really get to include the skills array in each object of the array.

Any help would be appreciated.

答:
This approach uses classes to build up the employee object and could be easily extended in the future.

const input = [{
    id: 182,
    employeeId: 'a',
    skillId: 207,
    score: 3,
  },
  {
    id: 512,
    employeeId: 'a',
    skillId: 212,
    score: 4,
  },
  {
    id: 908,
    employeeId: 'b',
    skillId: 134,
    score: 2,
  },
  {
    id: 876,
    employeeId: 'c',
    skillId: 212,
    score: 3,
  },
];

const employeeMap = {};

class Skill {
  constructor({
    skillId,
    score
  }) {
    this.skillId = skillId;
    this.score = score;
  }
}

class Employee {
  constructor(rawEmployee) {
    this.employeeId = rawEmployee.employeeId;
    this.skills = [];
  }
  addSkill(rawEmployee) {
    this.skills.push(new Skill(rawEmployee));
  }
}

for (let i = 0; i < input.length; i++) {
  const rawEmployee = input[i];
  let employee = employeeMap[rawEmployee.employeeId];
  if (!employee) {
    employee = new Employee(rawEmployee);
    employeeMap[employee.employeeId] = employee;
  }
  if (employee) {
    employee.addSkill(rawEmployee);
  }
}

const employeeArray = [];

for (let key in employeeMap) {
  employeeArray.push(employeeMap[key]);
}

console.log(employeeArray);
console.log(JSON.stringify(employeeArray));```

Body:
I need to re-organize an array of objects (from a database) into different groups according to one of the attributes of objects. To make it clearer, let's take the following example:

The ORM (Sequelize) returns the following array object:

[
  {
    id: 182,
    employeeId: 'a',
    skillId: 207,
    score: 3,
  },
  {
    id: 512,
    employeeId: 'a',
    skillId: 212,
    score: 4,
  },
  {
    id: 908,
    employeeId: 'b',
    skillId: 134,
    score: 2,
  },
  {
    id: 876,
    employeeId: 'c',
    skillId: 212,
    score: 3,
  },
]

I need to re-categorize the object grouping the entries by employeeId. Like this:

[
  {
    employeeId: 'a',
    skills:
           [
             { skillId: 203, score: 3},
             { skillId: 212, score: 4}
           ]
  },
  {
    employeeId: 'b',
    skills:
           [
             { skillId: 134, score: 2}
           ]
   },
   {
    employeeId: 'c',
    skills:
           [
             { skillId: 212, score: 3}
           ]
   }
]

It didn't look hard at first but I'm hitting a roadblock, I already tried using reduce, forEarch and map but I only got to make an array of employeeIds, can't really get to include the skills array in each object of the array.

Any help would be appreciated.


问:
JSON request for envelope with single document, two signers, pre-fill fields
I have an envelope with a single document and two signers saved as a server-side template.  The signers execute the agreement in a specific order.  The document has a number of pre-fill fields in it.

I am trying to automate sending this agreement out using Integromat.  Unfortunately, Integromat's module doesn't allow for pre-fill fields in templates, leaving me to create the API request manually.  This is where I get stuck.

The closest I have come is the JSON request below, POSTed to:
…/v2.1/accounts/{accountId}/envelopes, with capitalised values filled in automatically:

```<code>{
  "templateId": "TEMPLATE_ID",
  "templateRoles": [
    {
      "email": "CLIENT_EMAIL",
      "name": "CLIENT_NAME",
      "roleName": "Recipient",
      "tabs": {
        "prefillTabs": {
          "textTabs": [{
            "tabLabel": "Prefill: Purpose",
            "value": "PURPOSE_FIELD_DATA"
          }]
        }
      }
    }, {
      "email": "STAFF_EMAIL",
      "name": "STAFF_NAME",
      "roleName": "Company"
    }
  ],
  "status": "sent"
}
</code>```

The response from the API is:

The operation failed with an error. [400] A Required field is
incomplete. TabId: GUI_HERE

What I can't figure out is how to get the pre-fill data submitted since it's not tied to a particular signer.  I have scoured the v2.1 API documentation but there is no scenario simple enough for this request.

Apologies if I am missing something obvious here; this is my first rodeo with DocuSign's API.

Do you have any idea what I am doing wrong or, better yet, what the body of the request should be for this (presumably) simple scenario?

答:
Update: For pre-fill tabs, you need to have both the tabId and tabLabel, not enough to just have tabLabel like regular tabs.

My guess is a mismatch of the tabId field for the tabs on your template vs. what's in the API request:
You had this value in your request:

```<code>Prefill: Purpose
</code>```

Does it match how the template was set?

Body:
I have an envelope with a single document and two signers saved as a server-side template.  The signers execute the agreement in a specific order.  The document has a number of pre-fill fields in it.

I am trying to automate sending this agreement out using Integromat.  Unfortunately, Integromat's module doesn't allow for pre-fill fields in templates, leaving me to create the API request manually.  This is where I get stuck.

The closest I have come is the JSON request below, POSTed to:
…/v2.1/accounts/{accountId}/envelopes, with capitalised values filled in automatically:

{
  "templateId": "TEMPLATE_ID",
  "templateRoles": [
    {
      "email": "CLIENT_EMAIL",
      "name": "CLIENT_NAME",
      "roleName": "Recipient",
      "tabs": {
        "prefillTabs": {
          "textTabs": [{
            "tabLabel": "Prefill: Purpose",
            "value": "PURPOSE_FIELD_DATA"
          }]
        }
      }
    }, {
      "email": "STAFF_EMAIL",
      "name": "STAFF_NAME",
      "roleName": "Company"
    }
  ],
  "status": "sent"
}

The response from the API is:

The operation failed with an error. [400] A Required field is
incomplete. TabId: GUI_HERE

What I can't figure out is how to get the pre-fill data submitted since it's not tied to a particular signer.  I have scoured the v2.1 API documentation but there is no scenario simple enough for this request.

Apologies if I am missing something obvious here; this is my first rodeo with DocuSign's API.

Do you have any idea what I am doing wrong or, better yet, what the body of the request should be for this (presumably) simple scenario?

Body:
Update: For pre-fill tabs, you need to have both the tabId and tabLabel, not enough to just have tabLabel like regular tabs.

My guess is a mismatch of the tabId field for the tabs on your template vs. what's in the API request:
You had this value in your request:

Prefill: Purpose

Does it match how the template was set?


问:
How to get actual width/height of some element after loading whose width/height originally set by PERCENTAGE?
I have an iframe, whose content points to an HTML document.

In that HTML document, there's an EMBED element pointing to a PDF document. This EMBED originally set up with width and height in PERCENTAGE (such as: width: 100%; height: 100%).

My question is:

After the iframe has been loaded, how can I retrieve the actual, absolute width and height (in any unit px, pt, em etc.) of the EMBED element.

I've been trying on all possible js properties (width, height, style: clientWidth, clientHeight, offsetWidth, offsetHeight...) and in jQuery as well (such as outerWidth, outerHeight etc.) but it seems hopeless.

答:
This should return what you need:

```<code>document.getElementById("id").clientHeight
document.getElementById("id").clientWidth
</code>```

id is a unique ID of the EMBED element.

For more about this:

https://developer.mozilla.org/en/DOM:element.clientHeight

https://developer.mozilla.org/en/DOM:element.clientWidth

Body:
This should return what you need:

document.getElementById("id").clientHeight
document.getElementById("id").clientWidth

id is a unique ID of the EMBED element.

For more about this:

https://developer.mozilla.org/en/DOM:element.clientHeight

https://developer.mozilla.org/en/DOM:element.clientWidth


问:
Best way to handle long generation of file to download
I have web application that uses 3rd party API (PowerBI API for Embeded reports) to generate/export file (page from report) for user to download.
App can wait up to 1 min for 3rd party API response. From UX blocking UI for user for all that time isn't good. Is there any other way to handle this long downloading?

From 3rd-party API I receive stream.

There are three steps to follow:

Sending an export request.

Polling.

Getting the file.

On 2nd step I can track the export progress, but don't know how this can be applied for UI/UX.

答:
While using exportToFile API to export report, there are some limitations that might be a reason for long downloading.

The number of Power BI exports is limited to 50 report pages per minute per capacity.

Concurrent request- exportToFile supports concurrent export job requests. A job that exceeds its number of concurrent requests doesn't terminate.
Concurrency applies to pages within the report, a single report containing 10 report pages/tabs will not complete until each one is rendered individually. How fast this is will depend on the capacity size.

Embedded Capacities- You need to have the reports hosted within a workspace that is running within an embedded capacity. The larger the capacity the more reports you can run concurrently and your reports will render fast. You can refer to the link to find out the maximum concurrent pages for each SKU.

There is nothing to do with Polling for fast downloading. We can only track the progress and status of export to file Job by using PercentComplete and ExportState.

Please find the references here:
https://learn.microsoft.com/power-bi/developer/embedded/export-to?tabs=gen2

https://learn.microsoft.com/rest/api/power-bi/reports/get-export-to-file-status#exportsta


问:
Updating a node with merge using Py2Neo
I'm trying to merge and then update a graph using the py2neo library. My code looks roughly like

from py2neo import Graph, Node, Relationship

graph = Graph(host, auth=(user, password,))

tx = graph.begin()
alice = Node("Person", name="Alice")
bob = Node("Person", name="Bob")
KNOWS = Relationship(alice, "KNOWS", bob)
tx.create(KNOWS)
graph.commit(tx)
```
<p>This creates the nodes and edges as expected as</p>
```(:Person {name: "Alice"})-[:KNOWS]->(:Person {name: "Bob"})
```
<p>If I try to modify <code>alice</code> in a new transaction though, I get no change</p>
<p>e.g.</p>
<pre class="lang-py prettyprint-override"><code>new_tx = graph.begin()
alice["age"] = 32
new_tx.merge(alice, "Person", "name")
graph.commit(new_tx)
</code>```

I suspect I have misunderstood how the Transaction works here. I would expect the above to be equivalent to either finding Alice and updating with the new property or creating a new node.

Update: I have discovered the Graph.push method, but would still appreciate advice on best practice.

答:
You need to define a primary key to let the MERGE know which property to use as a primary key. From the documentation:

The primary property key used for Cypher MATCH and MERGE operations.
If undefined, the special value of "id" is used to hinge
uniqueness on the internal node ID instead of a property. Note that
this alters the behaviour of operations such as Graph.create() and
Graph.merge() on GraphObject instances.

It's probably best practice to define a custom class for every node type and define the primary key there.

```<code>class Person(GraphObject):
    __primarykey__ = "name"

    name = Property()
    born = Property()

    acted_in = RelatedTo(Movie)
    directed = RelatedTo(Movie)
    produced = RelatedTo(Movie)
</code>```

Title: Updating a node with merge using Py2Neo

Body:
I'm trying to merge and then update a graph using the py2neo library. My code looks roughly like

from py2neo import Graph, Node, Relationship

graph = Graph(host, auth=(user, password,))

tx = graph.begin()
alice = Node("Person", name="Alice")
bob = Node("Person", name="Bob")
KNOWS = Relationship(alice, "KNOWS", bob)
tx.create(KNOWS)
graph.commit(tx)

This creates the nodes and edges as expected as

(:Person {name: "Alice"})-[:KNOWS]->(:Person {name: "Bob"})

If I try to modify alice in a new transaction though, I get no change

e.g.

new_tx = graph.begin()
alice["age"] = 32
new_tx.merge(alice, "Person", "name")
graph.commit(new_tx)

I suspect I have misunderstood how the Transaction works here. I would expect the above to be equivalent to either finding Alice and updating with the new property or creating a new node.

Update: I have discovered the Graph.push method, but would still appreciate advice on best practice.

Body:
You need to define a primary key to let the MERGE know which property to use as a primary key. From the documentation:

The primary property key used for Cypher MATCH and MERGE operations.
If undefined, the special value of "id" is used to hinge
uniqueness on the internal node ID instead of a property. Note that
this alters the behaviour of operations such as Graph.create() and
Graph.merge() on GraphObject instances.

It's probably best practice to define a custom class for every node type and define the primary key there.

class Person(GraphObject):
    __primarykey__ = "name"

    name = Property()
    born = Property()

    acted_in = RelatedTo(Movie)
    directed = RelatedTo(Movie)
    produced = RelatedTo(Movie)


问:
python, GTK4, Gtk.ListStore.append and "AttributeError: 'ListStore' object has no attribute 'insert_with_valuesv'"
I'm new to coding and this is probably a stupid question...

I'm setting up a simple Gtk.ListStore(str) but as soon as I append(['whatever']) I get a "AttributeError: 'ListStore' object has no attribute 'insert_with_valuesv'".

I'm on Fedora 34(beta), python 3.9, GTK4.

This is a minimum example where the error happens:

```<code>#!/usr/bin/python
import gi
gi.require_version('Gtk','4.0')
from gi.repository import Gtk

simple = Gtk.ListStore(str)
simple.append(['whatever'])
</code>```
```<code>Traceback (most recent call last):
  File "/home/dedum/prova/provagtk2.py", line 7, in <module>
    simple.append(['whatever'])
  File "/usr/lib/python3.9/site-packages/gi/overrides/Gtk.py", line 1009, in append
    return self._do_insert(-1, row)
  File "/usr/lib/python3.9/site-packages/gi/overrides/Gtk.py", line 1001, in _do_insert
    treeiter = self.insert_with_valuesv(position, columns, row)
AttributeError: 'ListStore' object has no attribute 'insert_with_valuesv'
</code>```

What am I doing wrong?

答:
Your code is correct, the problem is an interaction bug between Gtk+ 4.1 or later and pygobject 3.42 or earlier. It was fixed in the following commit:

db472c14: gtk overrides: restore Gtk.ListStore.insert_with_valuesv with newer gtk4
https://gitlab.gnome.org/GNOME/pygobject/-/commit/db472c14416da879fdd1ba685928be9b7c919e57

We'll need to wait for a new release of pygobject for now, so use insert_with_values() instead of append() for now.

Body:
I'm new to coding and this is probably a stupid question...

I'm setting up a simple Gtk.ListStore(str) but as soon as I append(['whatever']) I get a "AttributeError: 'ListStore' object has no attribute 'insert_with_valuesv'".

I'm on Fedora 34(beta), python 3.9, GTK4.

This is a minimum example where the error happens:

#!/usr/bin/python
import gi
gi.require_version('Gtk','4.0')
from gi.repository import Gtk

simple = Gtk.ListStore(str)
simple.append(['whatever'])

Traceback (most recent call last):
  File "/home/dedum/prova/provagtk2.py", line 7, in <module>
    simple.append(['whatever'])
  File "/usr/lib/python3.9/site-packages/gi/overrides/Gtk.py", line 1009, in append
    return self._do_insert(-1, row)
  File "/usr/lib/python3.9/site-packages/gi/overrides/Gtk.py", line 1001, in _do_insert
    treeiter = self.insert_with_valuesv(position, columns, row)
AttributeError: 'ListStore' object has no attribute 'insert_with_valuesv'

What am I doing wrong?


问:
r one sided geom_quasirandom
I am interested in plotting the distribution of some continuous variables by groups using the geom_quasirandom() function.

I would like to know how do plot only one side, for example only points on the right side rather than on both sides.

```<code>ggplot(iris,aes(Species, Sepal.Length)) + geom_quasirandom()
</code>```

I am interested in a plot like this. I am not interested in solutions based on geom_beeswarm because I have a lot of datapoints and geom_beeswarm just creates a crowded mess for my dataset. So any solution specific to geom_quasirandom() will be helpful. Thanks.

答:
It's funny, the first example below is actually in the README for {ggbeeswarm} but it doesn't seem to work with my versions of R and the package.

library(tidyverse)
library(ggbeeswarm)

# doesn't look asymetric as shown in the vingette
ggplot(iris,aes(Species, Sepal.Length)) + geom_beeswarm(side = 1L)
#> Warning: Ignoring unknown parameters: side
```
<p><img src="https://i.imgur.com/665vhE3.png" alt="" /></p>
<p>However using the {see} package you can get pretty close to what I think you're asking for.</p>
<pre class="lang-r prettyprint-override"><code>library(see)
# this works if you turn off the violin half
ggplot(iris,aes(Species, Sepal.Length)) +
  geom_violindot(fill = NA, color = NA, color_dots = "black", size_dots = 1, fill_dots = "black")
</code>```

Created on 2022-02-08 by the reprex package (v2.0.1)

Title: r one sided geom_quasirandom

Body:
I am interested in plotting the distribution of some continuous variables by groups using the geom_quasirandom() function.

I would like to know how do plot only one side, for example only points on the right side rather than on both sides.

ggplot(iris,aes(Species, Sepal.Length)) + geom_quasirandom()

I am interested in a plot like this. I am not interested in solutions based on geom_beeswarm because I have a lot of datapoints and geom_beeswarm just creates a crowded mess for my dataset. So any solution specific to geom_quasirandom() will be helpful. Thanks.

Body:
It's funny, the first example below is actually in the README for {ggbeeswarm} but it doesn't seem to work with my versions of R and the package.

library(tidyverse)
library(ggbeeswarm)

# doesn't look asymetric as shown in the vingette
ggplot(iris,aes(Species, Sepal.Length)) + geom_beeswarm(side = 1L)
#> Warning: Ignoring unknown parameters: side

However using the {see} package you can get pretty close to what I think you're asking for.

library(see)
# this works if you turn off the violin half
ggplot(iris,aes(Species, Sepal.Length)) +
  geom_violindot(fill = NA, color = NA, color_dots = "black", size_dots = 1, fill_dots = "black")

Created on 2022-02-08 by the reprex package (v2.0.1)