问:
How to call method in ViewController from viewmodel in swift?
I am using MVVM design pattern in iOS project. I am trying to call method in viewcontroller from viewmodel.

```<code>import Foundation

class NotificationViewModel {

    var onCompletion: ((_ success: Bool) -> ())?

    func saveNotification(notification: Dictionary<String, Any>) {
        print("notification save")
        //other logic
        onCompletion?(true)
    }
   }
</code>```

"saveNotification" method getting called from appdelegate when notification received

```<code>func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo

        guard
            let aps = userInfo[AnyHashable("aps")] as? NSDictionary,
            let alert = aps["alert"] as? NSMutableDictionary
            else {
                // handle any error here
                return
            }

        NotificationViewModel().saveNotification(notification: alert as! Dictionary<String, Any>)
        }
</code>```

trying to call method in viewcontroller when "saveNotification" trigger

```<code>     class AlertViewController: BaseViewController{

            var viewModel = NotificationViewModel()

            override func viewDidLoad() {
                super.viewDidLoad()

                self.viewModel.onCompletion = { success in
                    // this should be executed when `saveNotification()` will be called
// **** this is never getting called ******
                    print("calling from viewmodel")
                    methodToCall()
                }
            }

          func methodToCall(){
            //logic
          }
      }
</code>```

But the method in viewdidload is not getting called anytime.

Please suggest if its possible or any other way to achieve this?
Thanks for help

答:
See the NotificationViewModel() in Appdelegate and viewModel variable in AlertViewController, they are not same, both are 2 different instances of the NotificationViewModel class. You need to go back to the basics and understand the concepts of class, struct, instances etc. Explaining that fully is beyond the scope of this answer. You can start from here for instance.

For now I would suggest, since you have yet to grasp these concepts, you better stick with MVC and use NotificationCenter to pass message from AppDelegate to AlertViewController directly. Here are some useful tutorials about NotificationCenter :-

https://learnappmaking.com/notification-center-how-to-swift/

https://www.hackingwithswift.com/example-code/system/how-to-post-messages-using-notificationcenter

PS. Appreciate that you are trying MVVM architecture from the starting itself, but make sure you keep the foundation/basics also strong along the journey, preferably from the starting itself. All the best :)

Body:
I am using MVVM design pattern in iOS project. I am trying to call method in viewcontroller from viewmodel.

import Foundation

class NotificationViewModel {

    var onCompletion: ((_ success: Bool) -> ())?

    func saveNotification(notification: Dictionary<String, Any>) {
        print("notification save")
        //other logic
        onCompletion?(true)
    }
   }

"saveNotification" method getting called from appdelegate when notification received

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo

        guard
            let aps = userInfo[AnyHashable("aps")] as? NSDictionary,
            let alert = aps["alert"] as? NSMutableDictionary
            else {
                // handle any error here
                return
            }

        NotificationViewModel().saveNotification(notification: alert as! Dictionary<String, Any>)
        }

trying to call method in viewcontroller when "saveNotification" trigger

     class AlertViewController: BaseViewController{

            var viewModel = NotificationViewModel()

            override func viewDidLoad() {
                super.viewDidLoad()

                self.viewModel.onCompletion = { success in
                    // this should be executed when `saveNotification()` will be called
// **** this is never getting called ******
                    print("calling from viewmodel")
                    methodToCall()
                }
            }

          func methodToCall(){
            //logic
          }
      }

But the method in viewdidload is not getting called anytime.

Please suggest if its possible or any other way to achieve this?
Thanks for help


来源: stackexchange

问:
DataGrid ToolTip - Show content
I have a problem with ToolTip (dataGrid), it not showing content from each cell. Maybe I'm not binding to the right property (in this case ToolTip="{Binding ColumnProperty}") </p>

```<code> <DataGrid HorizontalAlignment="Stretch" IsReadOnly="True"
                          ItemsSource="{Binding ProductsList}"
                          HorizontalScrollBarVisibility="Disabled"
                          MaxColumnWidth="200"
                          CanUserSortColumns="False"
                          CanUserAddRows="False"
                          materialDesign:DataGridAssist.CellPadding="4 2 2 2"
                          materialDesign:DataGridAssist.ColumnHeaderPadding="4 2 2 2"
                          ToolTip="{Binding ColumnProperty}"/>
</code>```

答:
You're currently setting the tooltip for the whole Datagrid.
the different types of DataGridColumns may have their own tooltip property, or you can use an item template to set the tooltip for the actual text-elements themselves.</p>

ContentLicense: CC BY-SA 4.0

Title: DataGrid ToolTip - Show content

Body:
I have a problem with ToolTip (dataGrid), it not showing content from each cell. Maybe I'm not binding to the right property (in this case ToolTip="{Binding ColumnProperty}")

 <DataGrid HorizontalAlignment="Stretch" IsReadOnly="True"
                          ItemsSource="{Binding ProductsList}"
                          HorizontalScrollBarVisibility="Disabled"
                          MaxColumnWidth="200"
                          CanUserSortColumns="False"
                          CanUserAddRows="False"
                          materialDesign:DataGridAssist.CellPadding="4 2 2 2"
                          materialDesign:DataGridAssist.ColumnHeaderPadding="4 2 2 2"
                          ToolTip="{Binding ColumnProperty}"/>


问:
how to get parent folder name in spark?
file:/C:/workspace/Spark_Scala_Exercise2/src/main/Resources/exercise-2/input/run_1/batch_id=73/part-00000-7489f493-c825-469a-9877-0b0e2c75cd4b.c000.snappy.parquet like i have many files

from this
i only want batch_id column with 73

答:
Can be done in 2 steps as below</p>

```<code>import java.nio.file.{Path, Paths}

object GetParentFolderName {

  def main(args: Array[String]): Unit = {
    //Create Path from the input string
    val path : Path = Paths.get("file:/C:/workspace/Spark_Scala_Exercise2/src/main/Resources/exercise-2/input/run_1/batch_id=73/part-00000-7489f493-c825-469a-9877-0b0e2c75cd4b.c000.snappy.parquet")

    //Get Parent folder name
    println(path.getParent.getFileName)
  }

}

</code>```

Title: how to get parent folder name in spark?

Body:
Can be done in 2 steps as below

import java.nio.file.{Path, Paths}

object GetParentFolderName {

  def main(args: Array[String]): Unit = {
    //Create Path from the input string
    val path : Path = Paths.get("file:/C:/workspace/Spark_Scala_Exercise2/src/main/Resources/exercise-2/input/run_1/batch_id=73/part-00000-7489f493-c825-469a-9877-0b0e2c75cd4b.c000.snappy.parquet")

    //Get Parent folder name
    println(path.getParent.getFileName)
  }

}


问:
How to make relation between enumtype and itemtype in Hybris
I have an enumtype :

```<code><items>
 <enumtypes>
  <enumtype code="FuelEnumeration" generate="true" autocreate="true" dynamic="true">
   <value code="diesel"></value>
   <value code="gasoline"></value>
   <value code="ethanol"></value>
 </enumtype>
</enumtypes>
</code>```

Here is the itemtype :

```<code><itemtypes>
<itemtype code="Car" extends="Product" autocreate="true" generate="true">
 <attributes> ... <attribute qualifier="fuel" type="FuelEnumeration">
<description>Fuel for this car</description>
<persistence type="property"></persistence>
 </attribute>
</code>```

I want to create a One to Many relation between enumtype and itemtype so that one car can have many FuelEnumeration, How can I do this?

答:
If you really wanted to do one-to-many using relation, below is how you do it.

```<code>    <relation code="Car2FuelRel" generate="true" localized="false" autocreate="true">
        <sourceElement qualifier="car" type="Car" cardinality="one">
            <modifiers read="true" write="true" search="true" optional="true" />
        </sourceElement>
        <targetElement qualifier="fuel" type="FuelEnumeration" cardinality="many" collectiontype="set">
            <modifiers read="true" write="true" search="true" optional="true" />
        </targetElement>
    </relation>
</code>```

However, this is incorrect, because one-to-many means that a Car can have many fuel enum, but a fuel enum can belong to only one car. It's probably better to do to this as many-to-many. Just change the cardinality of sourceElement to many.

Optionally, you can also use a collection as Raushan described. However, collection makes it difficult to search if a Car has a certain fuel value. Hybris recommends to use relations, instead of collections.

SEE:

Relations: https://help.sap.com/viewer/d0224eca81e249cb821f2cdf45a82ace/1905/en-US/bae7ed9732a4423f867114217ae21b46.html

Body:
I have an enumtype :

<items>
 <enumtypes>
  <enumtype code="FuelEnumeration" generate="true" autocreate="true" dynamic="true">
   <value code="diesel"></value>
   <value code="gasoline"></value>
   <value code="ethanol"></value>
 </enumtype>
</enumtypes>

Here is the itemtype :

<itemtypes>
<itemtype code="Car" extends="Product" autocreate="true" generate="true">
 <attributes> ... <attribute qualifier="fuel" type="FuelEnumeration">
<description>Fuel for this car</description>
<persistence type="property"></persistence>
 </attribute>

I want to create a One to Many relation between enumtype and itemtype so that one car can have many FuelEnumeration, How can I do this?

Body:
If you really wanted to do one-to-many using relation, below is how you do it.

    <relation code="Car2FuelRel" generate="true" localized="false" autocreate="true">
        <sourceElement qualifier="car" type="Car" cardinality="one">
            <modifiers read="true" write="true" search="true" optional="true" />
        </sourceElement>
        <targetElement qualifier="fuel" type="FuelEnumeration" cardinality="many" collectiontype="set">
            <modifiers read="true" write="true" search="true" optional="true" />
        </targetElement>
    </relation>

However, this is incorrect, because one-to-many means that a Car can have many fuel enum, but a fuel enum can belong to only one car. It's probably better to do to this as many-to-many. Just change the cardinality of sourceElement to many.

Optionally, you can also use a collection as Raushan described. However, collection makes it difficult to search if a Car has a certain fuel value. Hybris recommends to use relations, instead of collections.

SEE:

Relations: https://help.sap.com/viewer/d0224eca81e249cb821f2cdf45a82ace/1905/en-US/bae7ed9732a4423f867114217ae21b46.html


问:
How to display a classic BalloonTip in system tray of Windows 10 instead of a Toast Notification in C#?
I am building a Windows Forms application for Windows, based on .Net 4.7.2 framework. The application is intended to work on Windows 10 plus Windows Server 2019 systems.

When a user minimizes the app and the app goes to tray, I want to display a classic BalloonTip on the top of it's tray icon, like this:

The problem is that when I do this:

```<code>    private void form1_Resize(object sender, EventArgs e)
    {

        if (this.WindowState == FormWindowState.Minimized)
        {
            this.Hide();
            trayIcon.Visible = true;
            trayIcon.ShowBalloonTip(8000);
        }

    }
</code>```

my "BalloonTip" is displayed like this in the Windows 10 system I am working now:

I know that this is the new style of Windows 10. I am also informed about Windows Group Policy and it's registry settings. I do not want to change the policy of Windows.

EDIT: Also, the Toast Notification appears for only 2-3 seconds instead of 8 seconds I have set it...

How can I accomplish this in C#?

答:
Maybe, the Tulpep.NotificationWindow nuget package can work for you.

Pls have a look at this link : Foxlearn Notification

EDIT:

Create your own form for a custom Balloon Notification and use the below code.

Pls note that button1 is a little button in the top-right with a 'X' and is meant for close.

Next, add a pictureBox to your form, size it so as to fill the form and add the below image to the pictureBox :

Then you can design the notification the way you want, add labels, pictureboxes, etc.

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BubbleNotificationTest
{
    public partial class Form1 : Form
    {
        Timer t = new Timer();
        Timer fadeIn = new Timer();
        Timer fade = new Timer();
        public Form1()
        {
            InitializeComponent();
            Opacity = 0;
            fadeIn.Interval = 100;
            this.BackColor = Color.FromArgb(28, 28, 28);
            this.TransparencyKey = Color.FromArgb(28, 28, 28);
            this.StartPosition = FormStartPosition.Manual;
            this.Location = new Point(Screen.FromControl(this).Bounds.X + 850, Screen.FromControl(this).Bounds.Y + 662);
            fadeIn.Tick += new EventHandler(fadeIn_Tick);
            fadeIn.Start();
            t.Tick += new EventHandler(t_Tick);
            fade.Tick += new EventHandler(fade_Tick);
            fade.Interval = 100;
            t.Interval = 6000;
            t.Start();
        }

        private void fadeIn_Tick(object sender, EventArgs e)
        {
            this.Opacity += 0.05;
            if (this.Opacity == 1)
            {
                fadeIn.Stop();
            }
        }

        private void t_Tick(object sender, EventArgs e)
        {
            fade.Start();
        }

        private void fade_Tick(object sender, EventArgs e)
        {
            this.Opacity -= 0.05;
            if (this.Opacity == 0)
            {
                fade.Stop();
                this.Close();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
</code>```

And here is the result :

Body:
I am building a Windows Forms application for Windows, based on .Net 4.7.2 framework. The application is intended to work on Windows 10 plus Windows Server 2019 systems.

When a user minimizes the app and the app goes to tray, I want to display a classic BalloonTip on the top of it's tray icon, like this:

The problem is that when I do this:

    private void form1_Resize(object sender, EventArgs e)
    {

        if (this.WindowState == FormWindowState.Minimized)
        {
            this.Hide();
            trayIcon.Visible = true;
            trayIcon.ShowBalloonTip(8000);
        }

    }

my "BalloonTip" is displayed like this in the Windows 10 system I am working now:

I know that this is the new style of Windows 10. I am also informed about Windows Group Policy and it's registry settings. I do not want to change the policy of Windows.

EDIT: Also, the Toast Notification appears for only 2-3 seconds instead of 8 seconds I have set it...

How can I accomplish this in C#?

Body:
Maybe, the Tulpep.NotificationWindow nuget package can work for you.

Pls have a look at this link : Foxlearn Notification

EDIT:

Create your own form for a custom Balloon Notification and use the below code.

Pls note that button1 is a little button in the top-right with a 'X' and is meant for close.

Next, add a pictureBox to your form, size it so as to fill the form and add the below image to the pictureBox :

Then you can design the notification the way you want, add labels, pictureboxes, etc.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BubbleNotificationTest
{
    public partial class Form1 : Form
    {
        Timer t = new Timer();
        Timer fadeIn = new Timer();
        Timer fade = new Timer();
        public Form1()
        {
            InitializeComponent();
            Opacity = 0;
            fadeIn.Interval = 100;
            this.BackColor = Color.FromArgb(28, 28, 28);
            this.TransparencyKey = Color.FromArgb(28, 28, 28);
            this.StartPosition = FormStartPosition.Manual;
            this.Location = new Point(Screen.FromControl(this).Bounds.X + 850, Screen.FromControl(this).Bounds.Y + 662);
            fadeIn.Tick += new EventHandler(fadeIn_Tick);
            fadeIn.Start();
            t.Tick += new EventHandler(t_Tick);
            fade.Tick += new EventHandler(fade_Tick);
            fade.Interval = 100;
            t.Interval = 6000;
            t.Start();
        }

        private void fadeIn_Tick(object sender, EventArgs e)
        {
            this.Opacity += 0.05;
            if (this.Opacity == 1)
            {
                fadeIn.Stop();
            }
        }

        private void t_Tick(object sender, EventArgs e)
        {
            fade.Start();
        }

        private void fade_Tick(object sender, EventArgs e)
        {
            this.Opacity -= 0.05;
            if (this.Opacity == 0)
            {
                fade.Stop();
                this.Close();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

And here is the result :


问:
group by clause in sql oracle
so i have to write this query where i need to calculate the average amount of paid and withdraw operation for each account so it must look like this :

my table --> operation (Naccount,date_operation,average,nature_operation(withdraw/paid))

i wrote this query , and the problem is that its calculating and selecting only the account which has both paid and withdraw operation leaving the ones that only has paid or withdraw.

select x.naccount
       avg (x.amount) as paid
       avg (y.amount) as withdraw
from operation x, operation y
where
      x.nature_op = 'paid'
      and
      y.nature_op = 'withdraw'
      and
      x.naccount = y.naccount
group by x.naccount;

答:
You can use the conditional aggregation as follows:</p>

```<code>SELECT
    X.NACCOUNT,
    COALESCE(SUM(CASE WHEN X.NATURE_OP = 'paid' THEN X.AMOUNT END)
                / COALESCE(SUM(CASE WHEN X.NATURE_OP = 'paid' THEN 1 END), 1)
    , 0) AS PAID,
    COALESCE(SUM(CASE WHEN X.NATURE_OP = 'withdraw' THEN X.AMOUNT END)
                / COALESCE(SUM(CASE WHEN X.NATURE_OP = 'withdraw' THEN 1 END), 1)
    , 0) AS WITHDRAW
FROM OPERATION X
GROUP BY X.NACCOUNT;
</code>```

Title: group by clause in sql oracle

Body:
You can use the conditional aggregation as follows:

SELECT
    X.NACCOUNT,
    COALESCE(SUM(CASE WHEN X.NATURE_OP = 'paid' THEN X.AMOUNT END)
                / COALESCE(SUM(CASE WHEN X.NATURE_OP = 'paid' THEN 1 END), 1)
    , 0) AS PAID,
    COALESCE(SUM(CASE WHEN X.NATURE_OP = 'withdraw' THEN X.AMOUNT END)
                / COALESCE(SUM(CASE WHEN X.NATURE_OP = 'withdraw' THEN 1 END), 1)
    , 0) AS WITHDRAW
FROM OPERATION X
GROUP BY X.NACCOUNT;


问:
Crystal Report SP26 SetDataSource() Method failed in computers of clients in Visual Studio 2019
I'm working on Visual Studio 2019 and Crystal Report Service Pack 26. My code read data into ADO.NET dataset and I set those datases as datasourse of my reports. something like this in Visual Basic.Net:

```<code>    Dim ds1 As New DataSet1()

    Dim myRep As New CrystalReport1
    taAccArticleFields_TBL.Fill(ds1.AccArticleFields_TBL)
    myRep.SetDataSource(ds1)
    crvReport.ReportSource = myRep
</code>```

When I run program through VS all is good and reports show without error. But when I want to run my program on another computer which only has CR26 runtime installed, it gives an error on calling SetDataSource method for report as below:

```<code>System.Runtime.InteropServices.COMException (0x800002CD): Error in File temp_04020c6d-5b84-40d9-8558-bf87b6d5e554 4840_5464_{1C1D3ACF-9F25-45E2-B0EE-BB77F1DDA6B6}.rpt: Failed to load database information.
at CrystalDecisions.ReportAppServer.Controllers.DatabaseControllerClass.ReplaceConnection(Object oldConnection, Object newConnection, Object parameterFields, Object crDBOptionUseDefault)
at CrystalDecisions.CrystalReports.Engine.Table.SetDataSource(Object val, Type type)
at CrystalDecisions.CrystalReports.Engine.ReportDocument.SetDataSourceInternal(Object val, Type type)
</code>```

I encounter this with any program I write. Does anyone have idea to solve this?

答:
I was experiencing the same issue and found that by repairing the program in Windows 'Programs and Features' it automatically fixed the problem without the need to even restart the machine!

The idea came from the a discussion on a SAP answers page (https://answers.sap.com/questions/12937477/sp26-and-installation.html) where it was said that -

"the only thing that will help is to reinstall or repair."

It seems to be correct, I just wish I hadn't wasted ages trying to find an answer!

Body:
I'm working on Visual Studio 2019 and Crystal Report Service Pack 26. My code read data into ADO.NET dataset and I set those datases as datasourse of my reports. something like this in Visual Basic.Net:

    Dim ds1 As New DataSet1()

    Dim myRep As New CrystalReport1
    taAccArticleFields_TBL.Fill(ds1.AccArticleFields_TBL)
    myRep.SetDataSource(ds1)
    crvReport.ReportSource = myRep

When I run program through VS all is good and reports show without error. But when I want to run my program on another computer which only has CR26 runtime installed, it gives an error on calling SetDataSource method for report as below:

System.Runtime.InteropServices.COMException (0x800002CD): Error in File temp_04020c6d-5b84-40d9-8558-bf87b6d5e554 4840_5464_{1C1D3ACF-9F25-45E2-B0EE-BB77F1DDA6B6}.rpt: Failed to load database information.
at CrystalDecisions.ReportAppServer.Controllers.DatabaseControllerClass.ReplaceConnection(Object oldConnection, Object newConnection, Object parameterFields, Object crDBOptionUseDefault)
at CrystalDecisions.CrystalReports.Engine.Table.SetDataSource(Object val, Type type)
at CrystalDecisions.CrystalReports.Engine.ReportDocument.SetDataSourceInternal(Object val, Type type)

I encounter this with any program I write. Does anyone have idea to solve this?


问:
How do I share allure test report with stakeholders created with azure devops
I have build a automation framework through protractor and build it on Azure Devops . In azure devops my automated test are running on linux server and allure test report is also getting stored there.
Now I have a requirement to share it with stakeholders and peers through mail.

As allure api needs a server to host test reports . I don't want to host them on any server , I want to share them with mail . is it possible to do so?

Test Framework : Protractor
Language : JS
Reporting : Allure reports
Project Management Tool : Azure Devops

答:
You can use this docker container and exporting an emailable report to send you by email.
https://github.com/fescobar/allure-docker-service#customize-emailable-report</p>


问:
What is the difference between feed, posts and statuses in Facebook Graph API?
I'm trying to write a program that retreives a given user's "statuses" (and by statuses I mean the things he posted himself, anything he wrote as I'm mostly interested in textual statuses)

I cannot figure out the difference from the documentation here https://developers.facebook.com/docs/reference/api/user/ so I don't know which connection type to use; feed, posts or statuses

(Another thing I noticed is that statuses requires an access_token while the other 2 require the access_token only for non public stuff)

Thanks

答:
Feed - https://graph.facebook.com/me/feed - gives you the user's feed - meaning the posts he sees when he is visiting facebook (friends important posts) - notice that facebook filters only things it's algorithm marks as significant to the user and not everything.

Status - what the user posts on his own wall

Posts - what the user posts - including on other people's walls

ContentLicense: CC BY-SA 3.0


问:
Running SQL script using C# code ASP.NET Core
```<code>    public class ClassApp
    {
        static string ServerName = "LAPTOP-xxxxxxRK\\SQLEXPRESS";
        static string DatabaseName = "NewDbInstance";
        private SqlConnection tmpConn;

        public void CreateDb()
        {
            SqlConnection tmpConn;
            string sqlCreateDBQuery;
            tmpConn = new SqlConnection();
            tmpConn.ConnectionString = "SERVER = " + ServerName + "; Trusted_Connection=True;";
            sqlCreateDBQuery = " CREATE DATABASE " + DatabaseName;

            SqlCommand myCommand = new SqlCommand(sqlCreateDBQuery, tmpConn);
            try
            {
                tmpConn.Open();
                Console.WriteLine(sqlCreateDBQuery);
                var result = myCommand.ExecuteNonQuery();
                Console.WriteLine(result);
                Console.WriteLine("Database has been created successfully!");

                if (result == -1)
                {
                    RunScript(DatabaseName);
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

        public void RunScript(string dbName)
        {
            FileInfo file = new FileInfo("C:\\Users\\ADMIN\\script.sql");
            string script = file.OpenText().ReadToEnd();
            script = script.Replace("GO", "");

            SqlConnection tmpConn;
            tmpConn = new SqlConnection();
            tmpConn.ConnectionString = "Server=LAPTOP-xxxxxxRK\\SQLEXPRESS;" + "Database=" + dbName + "; Trusted_Connection=True;";
            tmpConn.Open();
            SqlCommand myCommandnew = new SqlCommand(script, tmpConn);
            var resultnew = myCommandnew.ExecuteNonQuery();   //Error comes here
            Console.WriteLine(resultnew);
            tmpConn.Close();
        }
</code>```

So I have two questions

When I run this SQL file using C# I got the error

'CREATE SCHEMA' must be the first statement in a query batch.

How to solve this problem?

How to modify code like if create database if it does not exists?

答:
Run script to check whether the database exists

```<code>    DECLARE @dbname nvarchar(128)
    SET @dbname = N'DatabaseName'

    IF (EXISTS (SELECT name
    FROM master.dbo.sysdatabases
    WHERE ('[' + name + ']' = @dbname
    OR name = @dbname)))
</code>```

Body:
    public class ClassApp
    {
        static string ServerName = "LAPTOP-xxxxxxRK\\SQLEXPRESS";
        static string DatabaseName = "NewDbInstance";
        private SqlConnection tmpConn;

        public void CreateDb()
        {
            SqlConnection tmpConn;
            string sqlCreateDBQuery;
            tmpConn = new SqlConnection();
            tmpConn.ConnectionString = "SERVER = " + ServerName + "; Trusted_Connection=True;";
            sqlCreateDBQuery = " CREATE DATABASE " + DatabaseName;

            SqlCommand myCommand = new SqlCommand(sqlCreateDBQuery, tmpConn);
            try
            {
                tmpConn.Open();
                Console.WriteLine(sqlCreateDBQuery);
                var result = myCommand.ExecuteNonQuery();
                Console.WriteLine(result);
                Console.WriteLine("Database has been created successfully!");

                if (result == -1)
                {
                    RunScript(DatabaseName);
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

        public void RunScript(string dbName)
        {
            FileInfo file = new FileInfo("C:\\Users\\ADMIN\\script.sql");
            string script = file.OpenText().ReadToEnd();
            script = script.Replace("GO", "");

            SqlConnection tmpConn;
            tmpConn = new SqlConnection();
            tmpConn.ConnectionString = "Server=LAPTOP-xxxxxxRK\\SQLEXPRESS;" + "Database=" + dbName + "; Trusted_Connection=True;";
            tmpConn.Open();
            SqlCommand myCommandnew = new SqlCommand(script, tmpConn);
            var resultnew = myCommandnew.ExecuteNonQuery();   //Error comes here
            Console.WriteLine(resultnew);
            tmpConn.Close();
        }

So I have two questions

When I run this SQL file using C# I got the error

'CREATE SCHEMA' must be the first statement in a query batch.

How to solve this problem?

How to modify code like if create database if it does not exists?

Body:
Run script to check whether the database exists

    DECLARE @dbname nvarchar(128)
    SET @dbname = N'DatabaseName'

    IF (EXISTS (SELECT name
    FROM master.dbo.sysdatabases
    WHERE ('[' + name + ']' = @dbname
    OR name = @dbname)))


问:
Pandas: modify multiple dataframes (in a loop)
I have multiple data frames that I want to do the same function for them. therefore I need to iterate over my frameworks.

```<code># read text files
df1 = pd.read_csv("df1.txt", sep="\t", error_bad_lines=False, index_col =None)
df2 = pd.read_csv("df2.txt", sep="\t", error_bad_lines=False, index_col =None)
df3 = pd.read_csv("df3.txt", sep="\t", error_bad_lines=False, index_col =None)
</code>```

I have used the following code, however, it is not working (it means that all dataframes are still the same, and the changes do not affect them):

```<code>for df in [df1 , df2 , df3]:
    df = df[df["Time"]>= 600.0].reset_index(drop=True)
    df.head()
</code>```

How I can iterate over them? and how can I overwrite dataframes?

答:
The problem is that you're not changing the data frames in place, but rather creating new ones. Here's a piece of code that changes things in-place. I don't have your data, so I create fake data for the sake of this example:

```<code>df1 = pd.DataFrame(range(10))
df2 = pd.DataFrame(range(20))
df3 = pd.DataFrame(range(30))
df_list = [df1, df2, df3]

for df in df_list:
    # use whatever condition you need in the following line
    # for example, df.drop(df[df["Time"] < 600].index, inplace=True)
    # in your case.
    df.drop(df[df[0] % 2 == 0].index, inplace=True)
    df.reset_index(inplace = True)

print(df2) # for example
</code>```

The result for df2 is:

```<code>   index   0
0      1   1
1      3   3
2      5   5
3      7   7
4      9   9
5     11  11
6     13  13
7     15  15
8     17  17
9     19  19
</code>```

Body:
I have multiple data frames that I want to do the same function for them. therefore I need to iterate over my frameworks.

# read text files
df1 = pd.read_csv("df1.txt", sep="\t", error_bad_lines=False, index_col =None)
df2 = pd.read_csv("df2.txt", sep="\t", error_bad_lines=False, index_col =None)
df3 = pd.read_csv("df3.txt", sep="\t", error_bad_lines=False, index_col =None)

I have used the following code, however, it is not working (it means that all dataframes are still the same, and the changes do not affect them):

for df in [df1 , df2 , df3]:
    df = df[df["Time"]>= 600.0].reset_index(drop=True)
    df.head()

How I can iterate over them? and how can I overwrite dataframes?

Body:
The problem is that you're not changing the data frames in place, but rather creating new ones. Here's a piece of code that changes things in-place. I don't have your data, so I create fake data for the sake of this example:

df1 = pd.DataFrame(range(10))
df2 = pd.DataFrame(range(20))
df3 = pd.DataFrame(range(30))
df_list = [df1, df2, df3]

for df in df_list:
    # use whatever condition you need in the following line
    # for example, df.drop(df[df["Time"] < 600].index, inplace=True)
    # in your case.
    df.drop(df[df[0] % 2 == 0].index, inplace=True)
    df.reset_index(inplace = True)

print(df2) # for example

The result for df2 is:

   index   0
0      1   1
1      3   3
2      5   5
3      7   7
4      9   9
5     11  11
6     13  13
7     15  15
8     17  17
9     19  19


问:
Class not found exception while trying to call Java code in a QT project
I am trying to use some code written in Java in a QT Creator project for an Android application. My end goal here is to use classes and methods created with Android Studio in this project.

To test if I understood the QT Java wrapper class I created a Java class from the Android Studio:

File>>New module>>Android Library>>Finish

In this library I created a class as follows:

```<code>package com.example.testclass;

public class MyJavaClass {
   public static int fibonacci (int n){
       if (n <2)
           return n;
       return fibonacci(n-1) + fibonacci(n-2);
   }
}
</code>```

Then 'Build>>Make module'

In my QT project .pro file I added: QT += androidextras and copied .aar file (also tried unzipping and copying the .jar file-likewise tried copying ...\testclass\src\main too) to javalib\  directory in my project file.
Now at this point I tried numerous things to make this file visible to my project. I edited .pro file by adding:

```<code>OTHER_FILES += \
    javalib/java/com/example/testclass/MyJavaClass.java \
    javalib/AndroidManifest.xml
</code>```

I tried to add files through gradle file that already existed in the project and several other things which I cannot remember.

But nevertheless following code to call the 'fibonacci' method from 'MyJavaClass';

```<code>void MainWindow::on_javaButton_clicked()
{
    int fibo = QAndroidJniObject::callStaticMethod<jint>("com/example/testclass/MyJavaClass", "fibonacci", "(I)I", 5);
    qDebug() << "JAVA OUTPUT: " << fibo << endl;
}
</code>```

Throws class not found exception at run time:

```<code>W System.err: java.lang.ClassNotFoundException: Didn't find class "com.example.testclass.MyJavaClass" on path: DexPathList[[],nativeLibraryDirectories=[/system/lib64, /system/vendor/lib64]]
W System.err:   at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:93)
W System.err:   at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
W System.err:   at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
W System.err:   at org.qtproject.qt5.android.QtNative.startQtApplication(Native Method)
W System.err:   at org.qtproject.qt5.android.QtNative$7.run(QtNative.java:390)
W System.err:   at org.qtproject.qt5.android.QtThread$1.run(QtThread.java:61)
W System.err:   at java.lang.Thread.run(Thread.java:764)
D libBlueToothTest.so: JAVA OUTPUT:  0
</code>```

I tried using docs from QT site and other sources like https://www.qtdeveloperdays.com/sites/default/files/BogdanVatra_Extending_Qt_Android_Apps_with_JNI.pdf.

I am new to QT, Android and Java. Despite the documents and examples I am struggling with this and I would appreciate any help.

My .pro file as of now:

```<code>QT       += core gui bluetooth androidextras

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++11

# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    BlueTooth/BlueToothManager.cpp \
    BlueTooth/bluetoothclient.cpp \
    BlueTooth/bluetoothserver.cpp \
    main.cpp \
    mainwindow.cpp \

HEADERS += \
    BlueTooth/BlueToothManager.h \
    BlueTooth/bluetoothclient.h \
    BlueTooth/bluetoothserver.h \
    mainwindow.h \

FORMS += \
    mainwindow.ui

OTHER_FILES += \
    javalib/java/com/example/testclass/MyJavaClass.java \
    javalib/AndroidManifest.xml

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

DISTFILES += \
    android/AndroidManifest.xml \
    android/build.gradle \
    android/gradle/wrapper/gradle-wrapper.jar \
    android/gradle/wrapper/gradle-wrapper.properties \
    android/gradlew \
    android/gradlew.bat \
    android/res/values/libs.xml

contains(ANDROID_TARGET_ARCH,armeabi-v7a) {
    ANDROID_PACKAGE_SOURCE_DIR = \
        $$PWD/android
}

</code>```

My gradle file as of now:

```<code>buildscript {
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.0'
    }
}

repositories {
    google()
    jcenter()
}

apply plugin: 'com.android.application'

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar', '*.aar'])
}

android {
    /*******************************************************
     * The following variables:
     * - androidBuildToolsVersion,
     * - androidCompileSdkVersion
     * - qt5AndroidDir - holds the path to qt android files
     *                   needed to build any Qt application
     *                   on Android.
     *
     * are defined in gradle.properties file. This file is
     * updated by QtCreator and androiddeployqt tools.
     * Changing them manually might break the compilation!
     *******************************************************/

    compileSdkVersion androidCompileSdkVersion.toInteger()

    buildToolsVersion androidBuildToolsVersion

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = [qt5AndroidDir + '/src', 'src', 'java']
            aidl.srcDirs = [qt5AndroidDir + '/src', 'src', 'aidl']
            res.srcDirs = [qt5AndroidDir + '/res', 'res']
            resources.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            assets.srcDirs = ['assets']
            jniLibs.srcDirs = ['libs']
       }
    }

    lintOptions {
        abortOnError false
    }
}
</code>```

答:
Ok I was working on this for far too long. After a lot of trial and error I finally got a solution to this problem. Code for Java nor the C++ side has any problems. Problem is somewhere in gradle or AndroidManifest files.

-I copied ...\AndroidStudioProjects\qtTest\testclass\src\main\java file(contains concatenated folders as per 'package' keyword in Java code also the .java source file) to my Android package directory which in my case was android\ (see next step)

-To call Java methods and classes from QT project you need to add an android package directory to .pro file(I already had one at the bottom which just points to "android" folder in my project directory). I don't know exactly what that file included at the beginning. I assumed it was about wrapping C++ code to build a program for Android. Anyways...

-Next step is to have a correct template for the program. Projects>>Build Steps>>Build Android APK>>Create Templates Takes you to template wizard which already has a package source directory taken from .pro file. I did not remove the tick to "Copy the Gradle files to Android directory" however I don't know if it makes any difference.

-Overwrite everything wizard asks you.

And voilà one clean build after code works without problems!

Body:
I am trying to use some code written in Java in a QT Creator project for an Android application. My end goal here is to use classes and methods created with Android Studio in this project.

To test if I understood the QT Java wrapper class I created a Java class from the Android Studio:

File>>New module>>Android Library>>Finish

In this library I created a class as follows:

package com.example.testclass;

public class MyJavaClass {
   public static int fibonacci (int n){
       if (n <2)
           return n;
       return fibonacci(n-1) + fibonacci(n-2);
   }
}

Then 'Build>>Make module'

In my QT project .pro file I added: QT += androidextras and copied .aar file (also tried unzipping and copying the .jar file-likewise tried copying ...\testclass\src\main too) to javalib\  directory in my project file.
Now at this point I tried numerous things to make this file visible to my project. I edited .pro file by adding:

OTHER_FILES += \
    javalib/java/com/example/testclass/MyJavaClass.java \
    javalib/AndroidManifest.xml

I tried to add files through gradle file that already existed in the project and several other things which I cannot remember.

But nevertheless following code to call the 'fibonacci' method from 'MyJavaClass';

void MainWindow::on_javaButton_clicked()
{
    int fibo = QAndroidJniObject::callStaticMethod<jint>("com/example/testclass/MyJavaClass", "fibonacci", "(I)I", 5);
    qDebug() << "JAVA OUTPUT: " << fibo << endl;
}

Throws class not found exception at run time:

W System.err: java.lang.ClassNotFoundException: Didn't find class "com.example.testclass.MyJavaClass" on path: DexPathList[[],nativeLibraryDirectories=[/system/lib64, /system/vendor/lib64]]
W System.err:   at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:93)
W System.err:   at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
W System.err:   at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
W System.err:   at org.qtproject.qt5.android.QtNative.startQtApplication(Native Method)
W System.err:   at org.qtproject.qt5.android.QtNative$7.run(QtNative.java:390)
W System.err:   at org.qtproject.qt5.android.QtThread$1.run(QtThread.java:61)
W System.err:   at java.lang.Thread.run(Thread.java:764)
D libBlueToothTest.so: JAVA OUTPUT:  0

I tried using docs from QT site and other sources like https://www.qtdeveloperdays.com/sites/default/files/BogdanVatra_Extending_Qt_Android_Apps_with_JNI.pdf.

I am new to QT, Android and Java. Despite the documents and examples I am struggling with this and I would appreciate any help.

My .pro file as of now:

QT       += core gui bluetooth androidextras

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++11

# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    BlueTooth/BlueToothManager.cpp \
    BlueTooth/bluetoothclient.cpp \
    BlueTooth/bluetoothserver.cpp \
    main.cpp \
    mainwindow.cpp \

HEADERS += \
    BlueTooth/BlueToothManager.h \
    BlueTooth/bluetoothclient.h \
    BlueTooth/bluetoothserver.h \
    mainwindow.h \

FORMS += \
    mainwindow.ui

OTHER_FILES += \
    javalib/java/com/example/testclass/MyJavaClass.java \
    javalib/AndroidManifest.xml

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

DISTFILES += \
    android/AndroidManifest.xml \
    android/build.gradle \
    android/gradle/wrapper/gradle-wrapper.jar \
    android/gradle/wrapper/gradle-wrapper.properties \
    android/gradlew \
    android/gradlew.bat \
    android/res/values/libs.xml

contains(ANDROID_TARGET_ARCH,armeabi-v7a) {
    ANDROID_PACKAGE_SOURCE_DIR = \
        $$PWD/android
}

My gradle file as of now:

buildscript {
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.0'
    }
}

repositories {
    google()
    jcenter()
}

apply plugin: 'com.android.application'

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar', '*.aar'])
}

android {
    /*******************************************************
     * The following variables:
     * - androidBuildToolsVersion,
     * - androidCompileSdkVersion
     * - qt5AndroidDir - holds the path to qt android files
     *                   needed to build any Qt application
     *                   on Android.
     *
     * are defined in gradle.properties file. This file is
     * updated by QtCreator and androiddeployqt tools.
     * Changing them manually might break the compilation!
     *******************************************************/

    compileSdkVersion androidCompileSdkVersion.toInteger()

    buildToolsVersion androidBuildToolsVersion

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = [qt5AndroidDir + '/src', 'src', 'java']
            aidl.srcDirs = [qt5AndroidDir + '/src', 'src', 'aidl']
            res.srcDirs = [qt5AndroidDir + '/res', 'res']
            resources.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            assets.srcDirs = ['assets']
            jniLibs.srcDirs = ['libs']
       }
    }

    lintOptions {
        abortOnError false
    }
}


问:
Text not aligning vertically at the center of select dropdown in material UI core
Please see the image. The text is not aligning at the center of the text box like the other text box fields in the form

Drop down not at the center

Here is my code

```<code>                          <FormControl style={{ width: "80%" }} size="small">
        <InputLabel
          htmlFor="Implementation Status"
          style={{ marginLeft: 10 }}
        >
          Implementation Status
        </InputLabel>
        <Select
          labelId="Implementation Status"
          name="name"
          onChange={handleChange("Status")}
          defaultValue={values.Status}
          variant="outlined"
          inputProps={{
            id: "Implementation Status",
            name: "age"
          }}
        >
          <MenuItem value="Implemented">Implemented</MenuItem>
          <MenuItem value="Implementation in Progress">
            Implementation in Progress
          </MenuItem>
          <MenuItem value="Not Implemented">Not Implemented</MenuItem>
        </Select>
      </FormControl>

      <br />
      <br />
</code>```

答:
check this </p>

```<code>import React from "react";
import "./styles.css";
import FormControl from "@material-ui/core/FormControl";
import InputLabel from "@material-ui/core/InputLabel";
import Select from "@material-ui/core/Select";
import MenuItem from "@material-ui/core/MenuItem";
export default function App() {
  return (
    <div className="App">
      <FormControl style={{ width: "80%" }} size="small">
        <InputLabel id="Implementation-Status" style={{ marginLeft: 10,top:"50%",transform:"translate(0,-50%" }}>
          Implementation Status
        </InputLabel>
        <Select
          labelId="Implementation-Status"
          name="name"
          variant="outlined"
          inputProps={{
            id: "Implementation Status",
            name: "age"
          }}
        >
          <MenuItem value="Implemented">Implemented</MenuItem>
          <MenuItem value="Implementation in Progress">
            Implementation in Progress
          </MenuItem>
          <MenuItem value="Not Implemented">Not Implemented</MenuItem>
        </Select>
      </FormControl>
    </div>
  );
}
</code>```

Body:
Please see the image. The text is not aligning at the center of the text box like the other text box fields in the form

Drop down not at the center

Here is my code

                          <FormControl style={{ width: "80%" }} size="small">
        <InputLabel
          htmlFor="Implementation Status"
          style={{ marginLeft: 10 }}
        >
          Implementation Status
        </InputLabel>
        <Select
          labelId="Implementation Status"
          name="name"
          onChange={handleChange("Status")}
          defaultValue={values.Status}
          variant="outlined"
          inputProps={{
            id: "Implementation Status",
            name: "age"
          }}
        >
          <MenuItem value="Implemented">Implemented</MenuItem>
          <MenuItem value="Implementation in Progress">
            Implementation in Progress
          </MenuItem>
          <MenuItem value="Not Implemented">Not Implemented</MenuItem>
        </Select>
      </FormControl>

Body:
check this

import React from "react";
import "./styles.css";
import FormControl from "@material-ui/core/FormControl";
import InputLabel from "@material-ui/core/InputLabel";
import Select from "@material-ui/core/Select";
import MenuItem from "@material-ui/core/MenuItem";
export default function App() {
  return (
    <div className="App">
      <FormControl style={{ width: "80%" }} size="small">
        <InputLabel id="Implementation-Status" style={{ marginLeft: 10,top:"50%",transform:"translate(0,-50%" }}>
          Implementation Status
        </InputLabel>
        <Select
          labelId="Implementation-Status"
          name="name"
          variant="outlined"
          inputProps={{
            id: "Implementation Status",
            name: "age"
          }}
        >
          <MenuItem value="Implemented">Implemented</MenuItem>
          <MenuItem value="Implementation in Progress">
            Implementation in Progress
          </MenuItem>
          <MenuItem value="Not Implemented">Not Implemented</MenuItem>
        </Select>
      </FormControl>
    </div>
  );
}


问:
HTML "checkbox" connect with asp.net core MVC , connecting model to checkbox buttons
So I am making a survey website where you can create survey forms and fill them after, my question is if I have a question where i have a collection of it's options with bool if the option is marked on filling or not, how do I set that value to the model when i click onto Submit form button
In short words get all marked answers from the questions, pass them to the controller as a separate view model that contains only the ID of the question and the given answer

Here is the class of the question :

```<code> public class OptionsQuestionVM
    {
        public Guid Id { get; set; }

        public Guid FormId { get; set; }

        public bool IsAnswered { get; set; }
        public bool IsDeleted { get; set; }

        public string Name { get; set; }
        public ICollection<OptionModelVM> Options { get; set; }
        public bool IsRequired { get; set; }
        public bool HasMultipleAnswers { get; set; }

    }
</code>```

Here is the class of the OptionModelVM:

```<code>public class OptionModelVM
    {
        public Guid Id { get; set; }

        public string Text { get; set; }
        public bool IsMarked { get; set; }
        public OptionsQuestionVM Question { get; set; }
        public Guid OptionsQuestionId { get; set; }
    }
</code>```

And here is my HTML Code for the checkbox that will be displayed for each question and it's available answers:

```<code>@foreach (var item in Model.OptionsQuestions)
                    {
                        if (item.HasMultipleAnswers == true)
                        {
                            <div class="element-checkbox">
                                <hr>
                                <h4>@item.Name</h4>
                                <div class="column column1">

                                    @foreach (var option in item.Options)
                                    {
                                        <label>
                                            <input type="checkbox" name="checkbox[]" value="option 1" />
                                            <span style="font-size:medium">@option.Text</span>
                                        </label>
                                        <br />
                                    }

                                </div><span class="clearfix"></span>
                            </div>
                        }
                        else
                        {

                                <div class="element-checkbox" single>
                                    <hr>
                                    <h4>@item.Name</h4>
                                    <div class="column column1">

                                        @foreach (var option in item.Options)
                                        {
                                            <label>
                                                <input type="checkbox" name="checkbox[]" value="option 1" />
                                                <span style="font-size:medium">@option.Text</span>
                                            </label>
                                            <br />
                                        }

                                    </div><span class="clearfix"></span>
                                </div>

                        }

                    }
</code>```

And also it would help if someone tells me how to set the HasMultipleAnswers bool into the checkbox, so that when its true you can mark more than 1 answer, when false you can choose only 1
Thank you :)

答:
First, you need to create a class to receive the ID of the question and answers, and store the field content required by the class in the corresponding place of the view.

Here is the receive class QuestionAnswer:

```<code>  public class QuestionAnswer
    {
        public Guid QuestionId { get; set; }
        public List<Guid> Answers { get; set; }
    }
</code>```

Secondly, the name of the checkboxes corresponding to different question options must be different.

And if the options that can only be single-selected, you can display them in the form of radio buttons.

Since you are involved in multiple models and need to return specific options, I think using ajax to pass is the best solution.

The following is a modification based on your code：

```<code>@model WebApplication_core_mvc.Models.MyQuestion
@{
    ViewData["Title"] = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@section Scripts{
    <script>
        $(function () {
            $("form").submit(function () {
                event.preventDefault();
                var questionAnswer = [];
                $("input[type=hidden][name=QuestionId]").each(function () {
                    var question = {
                        QuestionId :$(this).val(),
                        Answers: []
                    };
                    $("input[name=" + question.QuestionId + "]").each(function () {
                        if ($(this).is(":checked")) {
                            question.Answers.push($(this).val());
                        }
                    });
                    questionAnswer.push(question);
                });
                $.ajax({
                    url: $("form").attr("action"),
                    method: 'post',
                    data: { "questionAnswer": questionAnswer},
                })
            })
        })
    </script>

}
<h1>Index</h1>
<form asp-action="SubmitAnswers">
    @foreach (var item in Model.OptionsQuestions)
    {
        <input type="hidden" name="QuestionId" value="@item.Id"  />
        if (item.HasMultipleAnswers == true)
        {
            <div class="element-checkbox">
                <hr>
                <h4>@item.Name</h4>
                <div class="column column1">
                    @foreach (var option in item.Options)
                    {
                        <label>
                            <input type="checkbox" name="@item.Id" value="@option.Id" />
                            <span style="font-size:medium">@option.Text</span>
                        </label>
                        <br />
                    }
                </div><span class="clearfix"></span>
            </div>
        }
        else
        {

            <div class="element-checkbox" single>
                <hr>
                <h4>@item.Name</h4>
                <div class="column column1">
                    @foreach (var option in item.Options)
                    {
                        <label>
                            <input type="radio" name="@item.Id" value="@option.Id" />
                            <span style="font-size:medium">@option.Text</span>
                        </label>
                        <br />
                    }
                </div><span class="clearfix"></span>
            </div>

        }
    }
    <input id="Submit1" type="submit" value="submit" />
</form>
</code>```

Controller:

```<code>public IActionResult SubmitAnswers(List<QuestionAnswer> questionAnswer)
{
   //Do what you want...
    return View();
}
</code>```

Here is my test result:

Body:
So I am making a survey website where you can create survey forms and fill them after, my question is if I have a question where i have a collection of it's options with bool if the option is marked on filling or not, how do I set that value to the model when i click onto Submit form button
In short words get all marked answers from the questions, pass them to the controller as a separate view model that contains only the ID of the question and the given answer

Here is the class of the question :

 public class OptionsQuestionVM
    {
        public Guid Id { get; set; }

        public Guid FormId { get; set; }

        public bool IsAnswered { get; set; }
        public bool IsDeleted { get; set; }

        public string Name { get; set; }
        public ICollection<OptionModelVM> Options { get; set; }
        public bool IsRequired { get; set; }
        public bool HasMultipleAnswers { get; set; }

    }

Here is the class of the OptionModelVM:

public class OptionModelVM
    {
        public Guid Id { get; set; }

        public string Text { get; set; }
        public bool IsMarked { get; set; }
        public OptionsQuestionVM Question { get; set; }
        public Guid OptionsQuestionId { get; set; }
    }

And here is my HTML Code for the checkbox that will be displayed for each question and it's available answers:

@foreach (var item in Model.OptionsQuestions)
                    {
                        if (item.HasMultipleAnswers == true)
                        {

@item.Name

                                    @foreach (var option in item.Options)
                                    {

                                            <input type="checkbox" name="checkbox[]" value="option 1" />
                                            @option.Text

                                    }

                        }
                        else
                        {

@item.Name

                                        @foreach (var option in item.Options)
                                        {

                                                <input type="checkbox" name="checkbox[]" value="option 1" />
                                                @option.Text

                                        }

                        }

                    }

And also it would help if someone tells me how to set the HasMultipleAnswers bool into the checkbox, so that when its true you can mark more than 1 answer, when false you can choose only 1
Thank you :)

Body:
First, you need to create a class to receive the ID of the question and answers, and store the field content required by the class in the corresponding place of the view.

Here is the receive class QuestionAnswer:

  public class QuestionAnswer
    {
        public Guid QuestionId { get; set; }
        public List<Guid> Answers { get; set; }
    }

Secondly, the name of the checkboxes corresponding to different question options must be different.

And if the options that can only be single-selected, you can display them in the form of radio buttons.

Since you are involved in multiple models and need to return specific options, I think using ajax to pass is the best solution.

The following is a modification based on your code：

@model WebApplication_core_mvc.Models.MyQuestion
@{
    ViewData["Title"] = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@section Scripts{
    <script>
        $(function () {
            $("form").submit(function () {
                event.preventDefault();
                var questionAnswer = [];
                $("input[type=hidden][name=QuestionId]").each(function () {
                    var question = {
                        QuestionId :$(this).val(),
                        Answers: []
                    };
                    $("input[name=" + question.QuestionId + "]").each(function () {
                        if ($(this).is(":checked")) {
                            question.Answers.push($(this).val());
                        }
                    });
                    questionAnswer.push(question);
                });
                $.ajax({
                    url: $("form").attr("action"),
                    method: 'post',
                    data: { "questionAnswer": questionAnswer},
                })
            })
        })
    </script>

}
<h1>Index</h1>
<form asp-action="SubmitAnswers">
    @foreach (var item in Model.OptionsQuestions)
    {
        <input type="hidden" name="QuestionId" value="@item.Id"  />
        if (item.HasMultipleAnswers == true)
        {
            <div class="element-checkbox">
                <hr>
                <h4>@item.Name</h4>
                <div class="column column1">
                    @foreach (var option in item.Options)
                    {
                        <label>
                            <input type="checkbox" name="@item.Id" value="@option.Id" />
                            <span style="font-size:medium">@option.Text</span>
                        </label>
                        <br />
                    }
                </div><span class="clearfix"></span>
            </div>
        }
        else
        {

            <div class="element-checkbox" single>
                <hr>
                <h4>@item.Name</h4>
                <div class="column column1">
                    @foreach (var option in item.Options)
                    {
                        <label>
                            <input type="radio" name="@item.Id" value="@option.Id" />
                            <span style="font-size:medium">@option.Text</span>
                        </label>
                        <br />
                    }
                </div><span class="clearfix"></span>
            </div>

        }
    }
    <input id="Submit1" type="submit" value="submit" />
</form>

Controller:

public IActionResult SubmitAnswers(List<QuestionAnswer> questionAnswer)
{
   //Do what you want...
    return View();
}

Here is my test result:


问:
Filter a pandas dataframe based on two columns
I am trying to filter a pandas dataframe based on two columns, so that for each value in column 1 only those rows are left where column 2 is the minimum. I know it sounds confusing like this, so here is an example:

```<code>> df = pd.DataFrame([{'a':'anno1', 'ppm':1},{'a':'anno1', 'ppm':2},{'a':'anno2', 'ppm':2},{'a':'anno2', 'ppm':2}])

> df
       a  ppm
0  anno1    1
1  anno1    2
2  anno2    2
3  anno2    2
</code>```

And I want rows 0,2 and 3, because for anno1, the minimum ppm is 1, and for anno2 the minimum ppm is 2 (keep both rows!). So I started with a groupby:

```<code>> grouped_series = df.groupby(['a']).ppm.min()
> grouped_series
a
anno1    1
anno2    2
</code>```

Now I have for each value in a the minimum ppm. But how do I use this series to filter the original dataframe? Or is there even an easier way to do this? I tried several variations of:

```<code>new_df = df.loc[ df.loc[:,'ppm']==grouped_series.loc[df.loc[:,'a']] , :]
</code>```

but this gives me a ValueError: Can only compare identically-labeled Series objects

答:
Use GroupBy.transform for minimal values to Series with same size like df, so compare working nice, also for filtering in boolean indexing in loc not necessary:

```<code>new_df = df[df['ppm'] == df.groupby('a').ppm.transform('min')]
print (new_df)
       a  ppm
0  anno1    1
2  anno2    2
3  anno2    2
</code>```

Body:
I am trying to filter a pandas dataframe based on two columns, so that for each value in column 1 only those rows are left where column 2 is the minimum. I know it sounds confusing like this, so here is an example:

> df = pd.DataFrame([{'a':'anno1', 'ppm':1},{'a':'anno1', 'ppm':2},{'a':'anno2', 'ppm':2},{'a':'anno2', 'ppm':2}])

> df
       a  ppm
0  anno1    1
1  anno1    2
2  anno2    2
3  anno2    2

And I want rows 0,2 and 3, because for anno1, the minimum ppm is 1, and for anno2 the minimum ppm is 2 (keep both rows!). So I started with a groupby:

> grouped_series = df.groupby(['a']).ppm.min()
> grouped_series
a
anno1    1
anno2    2

Now I have for each value in a the minimum ppm. But how do I use this series to filter the original dataframe? Or is there even an easier way to do this? I tried several variations of:

new_df = df.loc[ df.loc[:,'ppm']==grouped_series.loc[df.loc[:,'a']] , :]

but this gives me a ValueError: Can only compare identically-labeled Series objects

Body:
Use GroupBy.transform for minimal values to Series with same size like df, so compare working nice, also for filtering in boolean indexing in loc not necessary:

new_df = df[df['ppm'] == df.groupby('a').ppm.transform('min')]
print (new_df)
       a  ppm
0  anno1    1
2  anno2    2
3  anno2    2


问:
Regex help to filter unexpected string
Sorry, I didn't make my quest clear. In the code comment, I hope the first string match=true, and the second string match=false. With the current Regex, both return true. </p>

```<code>public static void main(String[] args) {
    // create a REGEX String
    // Solved: I should use "^/apps/[^/]*/config.*"
    String REGEX = "^/apps/.*/config.*";

    // creare the string
    // in which you want to search
    //this one match
    String actualString = "/apps/test/config.author.dev";

    //I need this one doesn't match
    //String actualString = "/apps/test/test/config.author.dev";

    // compile the regex to create pattern
    // using compile() method
    Pattern pattern = Pattern.compile(REGEX);

    // check whether Regex string is
    // found in actualString or not
    boolean matches = pattern
                          .matcher(actualString)
                          .matches();

    System.out.println("actualString "
                       + "contains REGEX = "
                       + matches);
}
</code>```

答:
Here is another similar solution to @Pedro Pinheiro . It addresses the problem when you want to count something in a string.
^/apps/[^/]*(?:/\w+){0,0}[^/]*/config.*

Changing the numbers {0,0} it is possible to specify  max numbers or min count for /

Title: Regex help to filter unexpected string

Body:
Sorry, I didn't make my quest clear. In the code comment, I hope the first string match=true, and the second string match=false. With the current Regex, both return true.

public static void main(String[] args) {
    // create a REGEX String
    // Solved: I should use "^/apps/[^/]*/config.*"
    String REGEX = "^/apps/.*/config.*";

    // creare the string
    // in which you want to search
    //this one match
    String actualString = "/apps/test/config.author.dev";

    //I need this one doesn't match
    //String actualString = "/apps/test/test/config.author.dev";

    // compile the regex to create pattern
    // using compile() method
    Pattern pattern = Pattern.compile(REGEX);

    // check whether Regex string is
    // found in actualString or not
    boolean matches = pattern
                          .matcher(actualString)
                          .matches();

    System.out.println("actualString "
                       + "contains REGEX = "
                       + matches);
}


问:
Using MDC or Threadlocal
I'd like to propagate X-Request-Id received from my Nginx to other services in my k8s when calling them using http.

Right now, I'm using request filters to catch that X-Request-Id header and putting it to the MDC.

        final String nginxRequestId = requestContext.getHeaderString("X-Request-Id");
        if (nginxRequestId != null) {
            MDC.put("infra_request", nginxRequestId);
        }
```

Now, I'm calling the endpoint of service B inside the k8s (so no Nginx in the way) and I'd like to obtain that X-Request-Id to put it into the request's header. I can see two options here:

simply get that value from MDC

store that header in the thread local variable (as the service is using Dropwizard) in addition to storing it in MDC

I'd probably do it using the MDC, but I'm not sure whether this is the best practice or whether there could be some catch/problems with that.

答: I think for your purpose it is good to use MDC. Internally MDC uses ThreadLocal. Even if you use ThreadLocal, for a nicer way of implementation you will wrap ThreadLocal variable in a class. MDC does the same for you.</p>

Title: Using MDC or Threadlocal

Body:
I'd like to propagate X-Request-Id received from my Nginx to other services in my k8s when calling them using http.

Right now, I'm using request filters to catch that X-Request-Id header and putting it to the MDC.

        final String nginxRequestId = requestContext.getHeaderString("X-Request-Id");
        if (nginxRequestId != null) {
            MDC.put("infra_request", nginxRequestId);
        }

Now, I'm calling the endpoint of service B inside the k8s (so no Nginx in the way) and I'd like to obtain that X-Request-Id to put it into the request's header. I can see two options here:

simply get that value from MDC

store that header in the thread local variable (as the service is using Dropwizard) in addition to storing it in MDC

I'd probably do it using the MDC, but I'm not sure whether this is the best practice or whether there could be some catch/problems with that.


问:
RangeError: Maximum call stack size exceeded when retrieving arguments inside decorator
I am trying to write a decorator for async methods that times out the method after a certain time period. The decorator takes an argument (the index of the config object that includes the timeout value), and should cancel the method after a timeout if specified, or return the original method.

This is my function:

```<code>export function timeoutWrapper(requestsConfigIndex: number): Function {
  return function setMethodTimeout(
    target: any,
    propertyKey: string | symbol,
    descriptor: PropertyDescriptor,
  ): PropertyDescriptor {
    descriptor.value = function() {
      const context = this;
      const args = arguments;
      const originalMethod = descriptor.value;

      // retrieve requestsConfig from arguments...
      const getTimeout = (args: IArguments): number | undefined => {
        const requestConfig = args[requestsConfigIndex];
        if (requestConfig) {
          return requestConfig.timeout;
        }
        return undefined;
      };

      const timeout = getTimeout(args);

      if (timeout) {
        const timer = setTimeout(() => {
          axios.CancelToken.source().cancel();
          clearTimeout(timer);
          throw new Error('The method did not finish before the specified timeout.');
        }, timeout);
        originalMethod
          .apply(context, args)
          .then((result: any) => {
            clearTimeout(timer);
            return result;
          })
          .catch((e: Error) => {
            clearTimeout(timer);
            throw e;
          });
      } else {
        originalMethod.apply(context, args);
      }
    };
    return descriptor;
  };
}
</code>```

I am using the decorator to wrap one of my class methods:

```<code> @timeoutWrapper(2)
  public async getMap(params: GetMapParams, api: ApiType, reqConfig?: RequestConfiguration): Promise<Blob> {
    // ...
  }
</code>```

However, when called without a timeout, I am getting the following error when running unit tests:

```<code>    RangeError: Maximum call stack size exceeded

      48 |     descriptor: PropertyDescriptor,
      49 |   ): PropertyDescriptor {
    > 50 |     descriptor.value = function() {
         |                        ^
      51 |       const context = this;
      52 |       const args = arguments;
      53 |       const originalMethod = descriptor.value;

      at WmsLayer.descriptor.value (src/utils/cancelRequests.ts:50:24)
</code>```

答: descriptor.value is being called inside its own definitation, so it is causing a never ending recursion, hence causing a Maximum call stack size exceeded error.

Body:
I am trying to write a decorator for async methods that times out the method after a certain time period. The decorator takes an argument (the index of the config object that includes the timeout value), and should cancel the method after a timeout if specified, or return the original method.

This is my function:

export function timeoutWrapper(requestsConfigIndex: number): Function {
  return function setMethodTimeout(
    target: any,
    propertyKey: string | symbol,
    descriptor: PropertyDescriptor,
  ): PropertyDescriptor {
    descriptor.value = function() {
      const context = this;
      const args = arguments;
      const originalMethod = descriptor.value;

      // retrieve requestsConfig from arguments...
      const getTimeout = (args: IArguments): number | undefined => {
        const requestConfig = args[requestsConfigIndex];
        if (requestConfig) {
          return requestConfig.timeout;
        }
        return undefined;
      };

      const timeout = getTimeout(args);

      if (timeout) {
        const timer = setTimeout(() => {
          axios.CancelToken.source().cancel();
          clearTimeout(timer);
          throw new Error('The method did not finish before the specified timeout.');
        }, timeout);
        originalMethod
          .apply(context, args)
          .then((result: any) => {
            clearTimeout(timer);
            return result;
          })
          .catch((e: Error) => {
            clearTimeout(timer);
            throw e;
          });
      } else {
        originalMethod.apply(context, args);
      }
    };
    return descriptor;
  };
}

I am using the decorator to wrap one of my class methods:

 @timeoutWrapper(2)
  public async getMap(params: GetMapParams, api: ApiType, reqConfig?: RequestConfiguration): Promise<Blob> {
    // ...
  }

However, when called without a timeout, I am getting the following error when running unit tests:

    RangeError: Maximum call stack size exceeded

      48 |     descriptor: PropertyDescriptor,
      49 |   ): PropertyDescriptor {
    > 50 |     descriptor.value = function() {
         |                        ^
      51 |       const context = this;
      52 |       const args = arguments;
      53 |       const originalMethod = descriptor.value;

      at WmsLayer.descriptor.value (src/utils/cancelRequests.ts:50:24)


问:
Windows Forms "System.ArgumentException: Parameter is not valid" from Font.GetHeight(Graphics graphics)
I'm supporting a winforms application using dotnet 3.5 and ComponentFactory Krypton v4.4.0.0, I recently implemented the AppDomain.CurrentDomain.UnhandledException and Application.ThreadException handlers to notify me of exceptions happening on the clients, and found lot of errors showing up in the logs. This one is doing my head in at the moment:

```<code>System.ArgumentException: Parameter is not valid.
 at System.Drawing.Font.GetHeight(Graphics graphics)
 at System.Drawing.Font.GetHeight()
 at System.Drawing.Font.get_Height()
 at System.Windows.Forms.Control.set_Font(Font value)
 at System.Windows.Forms.DataGridViewComboBoxEditingControl.ApplyCellStyleToEditingControl(DataGridViewCellStyledataGridViewCellStyle)
 at System.Windows.Forms.DataGridView.BeginEditInternal(Boolean selectAll)
 at System.Windows.Forms.DataGridView.ProcessKeyEventArgs(Message& m)
 at System.Windows.Forms.Control.ProcessKeyMessage(Message& m)
 at System.Windows.Forms.Control.WmKeyChar(Message& m)
 at System.Windows.Forms.Control.WndProc(Message& m)
 at System.Windows.Forms.DataGridView.WndProc(Message& m)
 at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
 at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
 at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam,IntPtr lparam)
</code>```

Note that the stacktrace is entirely in Windows code. There's another that passes through one of my classes:

```<code>System.ArgumentException: Parameter is not valid.
  at System.Drawing.Font.GetHeight(Graphics graphics)
  at System.Drawing.Font.GetHeight()
  at System.Drawing.Font.get_Height()
  at System.Windows.Forms.Control.set_Font(Font value)
  at MyOrg.MyApp.WindowsClient.GuiControls.MaskedTextBoxEditingControl.ApplyCellStyleToEditingControl(DataGridViewCellStyledataGridViewCellStyle)
  at System.Windows.Forms.DataGridView.BeginEditInternal(Boolean selectAll)
  at System.Windows.Forms.DataGridView.ProcessKeyEventArgs(Message& m)
  at System.Windows.Forms.Control.ProcessKeyMessage(Message& m)
  at System.Windows.Forms.Control.WmKeyChar(Message& m)
  at System.Windows.Forms.Control.WndProc(Message& m)
  at System.Windows.Forms.DataGridView.WndProc(Message& m)
  at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
  at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
  at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
</code>```

Here's the code for that snippet:

```<code>public void ApplyCellStyleToEditingControl(DataGridViewCellStyle dataGridViewCellStyle)
{
  this.Font = dataGridViewCellStyle.Font;
  this.ForeColor = dataGridViewCellStyle.ForeColor;
  this.BackColor = dataGridViewCellStyle.BackColor;
  this.TextAlign = translateAlignment(dataGridViewCellStyle.Alignment);
}
</code>```

which doesn't tell me much.

The "System.ArgumentException: Parameter is not valid." error is pretty woeful and gives me very little to go on, but using dotPeek I looked at the code for Font.Get_Height(Graphics g) and discovered it's a GDI+ error, specifically GetFontHeight:

```<code>public float GetHeight(Graphics graphics)
{
  if (graphics == null)
  {
    throw new ArgumentNullException("graphics");
  }
  else
  {
    float size;
    int fontHeight = SafeNativeMethods.Gdip.GdipGetFontHeight(new HandleRef((object) this, this.NativeFont), new HandleRef((object) graphics, graphics.NativeGraphics), out size);
    if (fontHeight != 0)
      throw SafeNativeMethods.Gdip.StatusException(fontHeight);
    else
      return size;
  }
}
</code>```

which is this GDI+ method:
http://www.jose.it-berater.org/gdiplus/reference/flatapi/font/gdipgetfontheight.htm

and my status error is Invalidparameter, as documented here:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms534175(v=vs.85).aspx

Unfortunately none of this helps me to resolve what's wrong with the Graphics object. This is coming from unhandled exceptions from users in the field. I recently had a memory leak that was caused by a leaking EventHandler and consuming all the available GDI handles, but I've fixed that, so now I'm not sure whether this is a memory leak, a GDI handle leak, or just bad config somewhere that's triggered by users doing something out of the ordinary.

anyone have any ideas? Help much appreciated!

答: Do not dock DataGrid view to the parent layout</p>

Body:
I'm supporting a winforms application using dotnet 3.5 and ComponentFactory Krypton v4.4.0.0, I recently implemented the AppDomain.CurrentDomain.UnhandledException and Application.ThreadException handlers to notify me of exceptions happening on the clients, and found lot of errors showing up in the logs. This one is doing my head in at the moment:

System.ArgumentException: Parameter is not valid.
 at System.Drawing.Font.GetHeight(Graphics graphics)
 at System.Drawing.Font.GetHeight()
 at System.Drawing.Font.get_Height()
 at System.Windows.Forms.Control.set_Font(Font value)
 at System.Windows.Forms.DataGridViewComboBoxEditingControl.ApplyCellStyleToEditingControl(DataGridViewCellStyledataGridViewCellStyle)
 at System.Windows.Forms.DataGridView.BeginEditInternal(Boolean selectAll)
 at System.Windows.Forms.DataGridView.ProcessKeyEventArgs(Message& m)
 at System.Windows.Forms.Control.ProcessKeyMessage(Message& m)
 at System.Windows.Forms.Control.WmKeyChar(Message& m)
 at System.Windows.Forms.Control.WndProc(Message& m)
 at System.Windows.Forms.DataGridView.WndProc(Message& m)
 at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
 at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
 at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam,IntPtr lparam)

Note that the stacktrace is entirely in Windows code. There's another that passes through one of my classes:

System.ArgumentException: Parameter is not valid.
  at System.Drawing.Font.GetHeight(Graphics graphics)
  at System.Drawing.Font.GetHeight()
  at System.Drawing.Font.get_Height()
  at System.Windows.Forms.Control.set_Font(Font value)
  at MyOrg.MyApp.WindowsClient.GuiControls.MaskedTextBoxEditingControl.ApplyCellStyleToEditingControl(DataGridViewCellStyledataGridViewCellStyle)
  at System.Windows.Forms.DataGridView.BeginEditInternal(Boolean selectAll)
  at System.Windows.Forms.DataGridView.ProcessKeyEventArgs(Message& m)
  at System.Windows.Forms.Control.ProcessKeyMessage(Message& m)
  at System.Windows.Forms.Control.WmKeyChar(Message& m)
  at System.Windows.Forms.Control.WndProc(Message& m)
  at System.Windows.Forms.DataGridView.WndProc(Message& m)
  at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
  at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
  at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

Here's the code for that snippet:

public void ApplyCellStyleToEditingControl(DataGridViewCellStyle dataGridViewCellStyle)
{
  this.Font = dataGridViewCellStyle.Font;
  this.ForeColor = dataGridViewCellStyle.ForeColor;
  this.BackColor = dataGridViewCellStyle.BackColor;
  this.TextAlign = translateAlignment(dataGridViewCellStyle.Alignment);
}

which doesn't tell me much.

The "System.ArgumentException: Parameter is not valid." error is pretty woeful and gives me very little to go on, but using dotPeek I looked at the code for Font.Get_Height(Graphics g) and discovered it's a GDI+ error, specifically GetFontHeight:

public float GetHeight(Graphics graphics)
{
  if (graphics == null)
  {
    throw new ArgumentNullException("graphics");
  }
  else
  {
    float size;
    int fontHeight = SafeNativeMethods.Gdip.GdipGetFontHeight(new HandleRef((object) this, this.NativeFont), new HandleRef((object) graphics, graphics.NativeGraphics), out size);
    if (fontHeight != 0)
      throw SafeNativeMethods.Gdip.StatusException(fontHeight);
    else
      return size;
  }
}

which is this GDI+ method:
http://www.jose.it-berater.org/gdiplus/reference/flatapi/font/gdipgetfontheight.htm

and my status error is Invalidparameter, as documented here:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms534175(v=vs.85).aspx

Unfortunately none of this helps me to resolve what's wrong with the Graphics object. This is coming from unhandled exceptions from users in the field. I recently had a memory leak that was caused by a leaking EventHandler and consuming all the available GDI handles, but I've fixed that, so now I'm not sure whether this is a memory leak, a GDI handle leak, or just bad config somewhere that's triggered by users doing something out of the ordinary.

anyone have any ideas? Help much appreciated!


问:
How to integrate selenoid and allure
We implement farm of browsers based on GGR + Selenoid. If there any instruction how to integrate Allure reporting with such infrastructure?

On which host allure-results folder will be generated?

Should I create a script that will go through each selenoid host and copy a
folder with results to one node?

How to not mix results from different test runs / CI jobs?

答:
Use the Allure docker container and send the results using API.
https://github.com/fescobar/allure-docker-service#send-results-through-api</p>

Title: How to integrate selenoid and allure


问:
Get npm package name from import through Regex (not relative path)
I want to get npm package name from import through Regex and should not get relative path

exclude those matches which are starts from ./

I tried this: https://regex101.com/r/oyTq9s/1/

```<code>(?<=from ").+(?=")
</code>```

Input:

```<code>import React, { useContext, useEffect } from "react";
import { View, Text, AsyncStorage, Button } from "react-native";
import { createStackNavigator } from `@react-navigation/stack`;
import HomeScreen from "./src/screens/HomeScreen";
import LoginScreen from "./src/screens/login";
import CalendarScreen from "./src/screens/Calendar";
import SignUpScreen from "./src/screens/signUp";
import { scale, vs } from "react-native-size-matters";
import { createDrawerNavigator } from "@react-navigation/drawer";
import { createMaterialBottomTabNavigator } from "@react-navigation/material-bottom-tabs";
import { Icon } from "react-native-elements";
import UserContext, { UserProvider } from "./src/screens/Context/UserContext";
import { NavigationContainer } from "@react-navigation/native";
</code>```

Output should be:

```<code>react
react-native
@react-navigation/stack
react-native-size-matters
@react-navigation/drawer
@react-navigation/material-bottom
react-native-elements
@react-navigation/native
</code>```

答:
Your regex only allows matching from a double quotation mark to the next double quotation mark. You need to add a backtick to each ", that is, you need to use a character class like ["`]</code> and you need to exclude those cases where the first <code>"</code> or <code>` is followed with ./ - you may do that using a *negative lookahead.

Here is an expression that you may use

```<code>(?<=from [`"])(?!\./).+?(?=["`])
</code>```

See the regex demo.

Or, to ensure there is the same char at the start and end:

```<code>(?<=from ([`"]))(?!\./).+?(?=\1)
</code>```

See this regex demo.

Details

(?<=from ([`"]))  - a positive lookbehind that requires from, space and then a backtick or a double quotation mark (captured into Group 1) immediately to the right of the current location.

(?!\./) - a negative lookahead that fails the match if there is a ./ substring immediately to the right of the current location

.+? - any 1 or more chars other than line break chars, as few as possible

(?=\1) - a positive lookahead that requires the same text as captured in Group 1 immediately to the right of the current location.

Body:
I want to get npm package name from import through Regex and should not get relative path

exclude those matches which are starts from ./

I tried this: https://regex101.com/r/oyTq9s/1/

(?<=from ").+(?=")

Input:

import React, { useContext, useEffect } from "react";
import { View, Text, AsyncStorage, Button } from "react-native";
import { createStackNavigator } from `@react-navigation/stack`;
import HomeScreen from "./src/screens/HomeScreen";
import LoginScreen from "./src/screens/login";
import CalendarScreen from "./src/screens/Calendar";
import SignUpScreen from "./src/screens/signUp";
import { scale, vs } from "react-native-size-matters";
import { createDrawerNavigator } from "@react-navigation/drawer";
import { createMaterialBottomTabNavigator } from "@react-navigation/material-bottom-tabs";
import { Icon } from "react-native-elements";
import UserContext, { UserProvider } from "./src/screens/Context/UserContext";
import { NavigationContainer } from "@react-navigation/native";

Output should be:

react
react-native
@react-navigation/stack
react-native-size-matters
@react-navigation/drawer
@react-navigation/material-bottom
react-native-elements
@react-navigation/native

Body:
Your regex only allows matching from a double quotation mark to the next double quotation mark. You need to add a backtick to each ", that is, you need to use a character class like ["`]</code> and you need to exclude those cases where the first <code>"</code> or <code>` is followed with ./ - you may do that using a *negative lookahead.

Here is an expression that you may use

(?<=from [`"])(?!\./).+?(?=["`])

See the regex demo.

Or, to ensure there is the same char at the start and end:

(?<=from ([`"]))(?!\./).+?(?=\1)

See this regex demo.

Details

(?<=from ([`"]))  - a positive lookbehind that requires from, space and then a backtick or a double quotation mark (captured into Group 1) immediately to the right of the current location.

(?!\./) - a negative lookahead that fails the match if there is a ./ substring immediately to the right of the current location

.+? - any 1 or more chars other than line break chars, as few as possible

(?=\1) - a positive lookahead that requires the same text as captured in Group 1 immediately to the right of the current location.


问:
Vue.js route params data getting lost after the full page reload
I am passing a user id from the router-link using params to display the detail of the user in the profile page and i am getting all the required data and also is displayed correctly but as soon as i reload the page the $route.params.id changes into undefined and the data which were shown are gone to get the data i have to again navigate to the index page and revisit the link.

my index.vue page with the router-link is as follow

```<code><h6 class="author">
    <router-link :to="{name: 'FrontProfile' , params: {
         id: post.user.id }}"
         tag="a" active-class="active">{{post.user.name}}
    </router-link>
</h6>
</code>```

my profile page code is :

```<code>data(){
       return {
               id: this.$route.params.id,
               user: {},
               thoughts: {},
               }
        },
methods:{
         viewProfile() {
            axios.get('user_profile/' + this.id).then((response) => {
                this.user = response.data.user_data;
                this.thoughts = response.data.thoughts;
            }).catch(() => {

            });
        },
 watch:{
        '$route' : 'viewProfile'
    },
created() {
        this.viewProfile();
    }
</code>```

What can I try to resolve this problem?

答:
Have you considered to put your id as a computed prop?
If you leave it in the component data, it will just update on create the component, and you can remove the watcher over $route, what is a higher operation than a computed property.

data(){
  return {
    user: {},
    thoughts: {},
  }
},
methods:{
 viewProfile() {
    // You can use destructuring here over your response
    axios.get('user_profile/' + this.id).then(({ data: { user_data, thoughts } }) => {
        this.user = user_data;
        this.thoughts = thoughts;
    }).catch(() => {

    });
},
computed: {
  id() {
    return this.$route.params.id;
  }
},
// because of the vue lifecycle hooks, this should be a `mounted` hook intead of a `created`
mounted() {
  this.viewProfile();
} ```

Body:
I am passing a user id from the router-link using params to display the detail of the user in the profile page and i am getting all the required data and also is displayed correctly but as soon as i reload the page the $route.params.id changes into undefined and the data which were shown are gone to get the data i have to again navigate to the index page and revisit the link.

my index.vue page with the router-link is as follow

    <router-link :to="{name: 'FrontProfile' , params: {
         id: post.user.id }}"
         tag="a" active-class="active">{{post.user.name}}
    </router-link>

my profile page code is :

data(){
       return {
               id: this.$route.params.id,
               user: {},
               thoughts: {},
               }
        },
methods:{
         viewProfile() {
            axios.get('user_profile/' + this.id).then((response) => {
                this.user = response.data.user_data;
                this.thoughts = response.data.thoughts;
            }).catch(() => {

            });
        },
 watch:{
        '$route' : 'viewProfile'
    },
created() {
        this.viewProfile();
    }

What can I try to resolve this problem?


问:
Excel VBA Application.Calculate does not work but Ctrl+Alt+F9 does
I have an unusual problem with Excel 2013. I have a VBA script to pull data from SQL and generate HTML files then import those HTML files into tabs followed by a recalculate call for formulas that are dependent on the data generated prior.

Here is the basic structure:

```<code>Sub RefreshData()

Task1 ' run 1st query and generate HTML file
Task2 ' run 2nd query and generate HTML file
.
.
.
Taskn ' run nth query and generate HTML file
RefreshDataInTabs ' refresh all tabs with generated HTML files
Calculate_AllOpenWorkbooks ' calculate all formulas that depend on data obtained in Tasks above

End Sub
</code>```

Here is the call to calculate...

```<code>Sub Calculate_AllOpenWorkBooks()

Application.Calculate

End Sub.
</code>```

So everything works as expected until call to Calculate_AllOpenWorkBooks. Cells with formulas don't update. "Automatic" Workbook Calculation is selected in the Calculation options windows in Excel Options. Manual Data -> Refresh All doesn't work BUT Ctrl+Alt+F9 does!

答:
```<code>Sub Calculate_AllOpenWorkBooks()

Application.CalculateFull

End Sub
</code>```

and if you need the application to wait:

```<code>Sub Calculate_AllOpenWorkBooks()

Application.CalculateFull

If Not Application.CalculationState = xlDone Then
DoEvents
Else: End If

End Sub
</code>```

Body:
I have an unusual problem with Excel 2013. I have a VBA script to pull data from SQL and generate HTML files then import those HTML files into tabs followed by a recalculate call for formulas that are dependent on the data generated prior.

Here is the basic structure:

Sub RefreshData()

Task1 ' run 1st query and generate HTML file
Task2 ' run 2nd query and generate HTML file
.
.
.
Taskn ' run nth query and generate HTML file
RefreshDataInTabs ' refresh all tabs with generated HTML files
Calculate_AllOpenWorkbooks ' calculate all formulas that depend on data obtained in Tasks above

End Sub

Here is the call to calculate...

Sub Calculate_AllOpenWorkBooks()

Application.Calculate

End Sub.

So everything works as expected until call to Calculate_AllOpenWorkBooks. Cells with formulas don't update. "Automatic" Workbook Calculation is selected in the Calculation options windows in Excel Options. Manual Data -> Refresh All doesn't work BUT Ctrl+Alt+F9 does!

Body:
Sub Calculate_AllOpenWorkBooks()

Application.CalculateFull

End Sub

and if you need the application to wait:

Sub Calculate_AllOpenWorkBooks()

Application.CalculateFull

If Not Application.CalculationState = xlDone Then
DoEvents
Else: End If

End Sub