问:
Window form does not close
Hey guys i am new to the Windows application.

I have a form on which Login button click event i have shown to other Forms. Example like i have a login page after user authentication other two Forms shown. But i want after authentication of user Login Form should be close, But others two remain open.

Following is code, my Login Form name is LogIn.cs

```<code>private void btnLogIn_Click(object sender, EventArgs e)
{
    if(ValidateUser())
    {
       //Form1

        DetailForm form = new DetailForm(txtUserName.Text.ToString());
        form.Show();

        //Form2

        Progressbar progress = new Progressbar();
        progress.Show();
    }
}
</code>```

please write some code

答:
```<code>private void btnLogIn_Click(object sender, EventArgs e)
{
    if(ValidateUser())
    {
       //Form1

        DetailForm form = new DetailForm(txtUserName.Text.ToString());
        form.Show();

        //Form2

        Progressbar progress = new Progressbar();
        progress.Show();
        this.Close();
    }
}
</code>```

Title: Window form does not close

Body:
Hey guys i am new to the Windows application.

I have a form on which Login button click event i have shown to other Forms. Example like i have a login page after user authentication other two Forms shown. But i want after authentication of user Login Form should be close, But others two remain open.

Following is code, my Login Form name is LogIn.cs

private void btnLogIn_Click(object sender, EventArgs e)
{
    if(ValidateUser())
    {
       //Form1

        DetailForm form = new DetailForm(txtUserName.Text.ToString());
        form.Show();

        //Form2

        Progressbar progress = new Progressbar();
        progress.Show();
    }
}

please write some code


来源: stackexchange

问:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/spark/ml/feature/VectorAssembler in IntelliJ
I am trying to build a model in Spark ML using Linear Regression in IntellijIDEA.

Before fitting the model, i am supposed to create a VectorAssembler having feature column.

```<code>import org.apache.spark.ml.feature.VectorAssembler
import org.apache.spark.ml.linalg.Vectors

//creating features column
val assembler = new VectorAssembler()
  .setInputCols(Array("col4","col5","col6","col7"))
  .setOutputCol("features")
</code>```

Exception in thread "main" java.lang.NoClassDefFoundError:
  org/apache/spark/ml/feature/VectorAssembler   at
  energydata$.main(energydata.scala:35)     at
  energydata.main(energydata.scala) Caused by:
  java.lang.ClassNotFoundException:
  org.apache.spark.ml.feature.VectorAssembler   at
  java.net.URLClassLoader.findClass(URLClassLoader.java:381)    at
  java.lang.ClassLoader.loadClass(ClassLoader.java:424)     at
  sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)     at
  java.lang.ClassLoader.loadClass(ClassLoader.java:357)     ... 2 more

But this gives error in Intellij. When i tried the same in spark-shell, it works.

can anybody suggest where I might be going wrong here??

```<code>name := "hello"

version := "1.0"

scalaVersion := "2.11.8"

libraryDependencies += "org.apache.spark" % "spark-core_2.11" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-sql_2.11" % "2.1.0"
libraryDependencies += "com.datastax.spark" %% "spark-cassandra-connector" % "2.0.6"
libraryDependencies += "org.apache.spark" %% "spark-mllib" % "2.1.0" % "provided"
</code>```

答:
I have also face same error while running spark application. i have just remove (%%"provide")
scope of dependency spark sql</p>

ContentLicense: CC BY-SA 3.0

Body:
I am trying to build a model in Spark ML using Linear Regression in IntellijIDEA.

Before fitting the model, i am supposed to create a VectorAssembler having feature column.

import org.apache.spark.ml.feature.VectorAssembler
import org.apache.spark.ml.linalg.Vectors

//creating features column
val assembler = new VectorAssembler()
  .setInputCols(Array("col4","col5","col6","col7"))
  .setOutputCol("features")

Exception in thread "main" java.lang.NoClassDefFoundError:
  org/apache/spark/ml/feature/VectorAssembler   at
  energydata$.main(energydata.scala:35)     at
  energydata.main(energydata.scala) Caused by:
  java.lang.ClassNotFoundException:
  org.apache.spark.ml.feature.VectorAssembler   at
  java.net.URLClassLoader.findClass(URLClassLoader.java:381)    at
  java.lang.ClassLoader.loadClass(ClassLoader.java:424)     at
  sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)     at
  java.lang.ClassLoader.loadClass(ClassLoader.java:357)     ... 2 more

But this gives error in Intellij. When i tried the same in spark-shell, it works.

can anybody suggest where I might be going wrong here??

name := "hello"

version := "1.0"

scalaVersion := "2.11.8"

libraryDependencies += "org.apache.spark" % "spark-core_2.11" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-sql_2.11" % "2.1.0"
libraryDependencies += "com.datastax.spark" %% "spark-cassandra-connector" % "2.0.6"
libraryDependencies += "org.apache.spark" %% "spark-mllib" % "2.1.0" % "provided"

ContentLicense: CC BY-SA 4.0


问:
In Micrsoft SQL is an UPDLOCK hint sufficient to avoid deadlocks in an SP that either inserts if not exists or updates otherwise?
I have a C# program with multiple threads that calls an SP to get a unique incrementing value.

I'm trying to prevent deadlocks using query hints UPDLOCK and HOLDLOCK.

The SP

Selects value from a table,

insert if the value is not found (initial value is 1)

Or updates the table by incrementing the value from the first select

Returns the incremented value in an output parameter.

Here the table

```<code>CREATE TABLE MyCounters(
    [Id] [bigint] IDENTITY(1,1) NOT NULL,
    [Key] [nvarchar](20) NOT NULL UNIQUE,
    [Counter] [bigint] NOT NULL,
 CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
</code>```

Questions

Will a single UPDLOCK be sufficient in the first select to prevent deadlocks?

Or do I need to select with UPDLOCK and HOLDLOCK?

Or do I need a second dummy select with UPDLOCK and HOLDLOCK to only lock the entire table for inserts but not for updates?

I've read this question but there no insert is used.

Below the simplified SP and after that a script I used to test in 2 tabs in SQL management studio. With only a single UPDLOCK the test script works (i.e. no deadlocks and counters at the correct values).

```<code>BEGIN TRANSACTION

DECLARE @Key nvarchar(3)
SET @Key = 'AA'
DECLARE @counter bigint
SET @counter=NULL

-- *** Question 1 *** Will a single UPDLOCK be sufficient in the first select to prevent deadlocks?
-- *** Question 2 *** 1. Or do I need to select with UPDLOCK and HOLDLOCK?
SELECT @counter=Counter FROM MyCounters WITH (UPDLOCK) WHERE Key = @Key

IF (@counter IS NULL)
BEGIN
    -- *** Question 3 *** Or do I need a second dummy select with UPDLOCK and HOLDLOCK to only lock the entire table for inserts but not update?
    -- lock the entire table before inserting (select into variable)
    --DECLARE @temp bigint
    --SELECT TOP 1 @temp = Counter FROM MyCounters WITH (UPDLOCK, HOLDLOCK)

    SET @counter=1
    INSERT INTO MyCounters ([Key],Counter) VALUES (@Key, @counter)
END
ELSE
BEGIN
    SET @counter=@counter+1
    UPDATE MyCounters SET Counter = @counter WHERE Key = @Key
END

SELECT @Key, @counter

COMMIT
</code>```

Below the test script (which I ran in multiple tabs in SQL management studio)

```<code>BEGIN TRANSACTION

WAITFOR DELAY '00:00:05' --to give me a chance to start the script in multiple tabs

DECLARE @i int
SET @i=0
WHILE @i < 100
BEGIN

    DECLARE @Key nvarchar(3)
    SET @Key = 'A'+CONVERT(nvarchar(10),@i)
    DECLARE @counter bigint
    SET @counter=NULL
    SELECT @counter=Counter FROM MyCounters WITH (UPDLOCK) WHERE Key = @Key

    IF (@counter IS NULL)
    BEGIN
        -- lock the entire table before inserting (select into variable)
        --DECLARE @temp bigint
        --SELECT TOP 1 @temp = Counter FROM MyCounters WITH (UPDLOCK, HOLDLOCK)

        SET @counter=1
        INSERT INTO MyCounters ([Key],Counter) VALUES (@Key, @counter)
    END
    ELSE
    BEGIN
        SET @counter=@counter+1
        UPDATE MyCounters SET Counter = @counter WHERE Key = @Key
    END

    SELECT @i, @Key, @counter

    SET @i = @i + 1

END;

COMMIT
</code>```

答:
-- *** Question 1 *** Will a single UPDLOCK be sufficient in the first select to prevent deadlocks?
-- *** Question 2 *** 1. Or do I need to select with UPDLOCK and HOLDLOCK? SELECT @counter=Counter FROM MyCounters WITH (UPDLOCK) WHERE
Key = @Key

In in the default READ COMMITTED isolation level, the UPDLOCK will be released when the statement completes. Specify UPDLOCK,HOLDLOCK to retain locks until the transaction commits or rolls back.

I suggest you change the clustered primary key from the IDENTITY column to the natural key column Key or make the unique constraint the clustered index.  This will improve performance. If you don't actually use the Id column, remove it entirely. Throwing an unused IDENTITY surrogate key on tables is a common anti-pattern.

```<code>--clustered unique constraint
CREATE TABLE dbo.MyCounters(
    [Id] [bigint] IDENTITY(1,1) NOT NULL,
    [Key] [nvarchar](20) NOT NULL CONSTRAINT UQ_MyCounters_Key UNIQUE CLUSTERED,
    [Counter] [bigint] NOT NULL,
 CONSTRAINT [PK_Table_1] PRIMARY KEY NONCLUSTERED
    (
        [Id] ASC
    )
);

--remove unneeded surrogate key
CREATE TABLE dbo.MyCounters(
    [Key] [nvarchar](20) NOT NULL CONSTRAINT PK_MyCounters PRIMARY KEY CLUSTERED,
    [Counter] [bigint] NOT NULL
);
</code>```

Also, add SET XACT_ABORT ON; to procs with explicit transactions to ensure the transaction is rolled back immediately after errors or client timeouts.

Body:
I have a C# program with multiple threads that calls an SP to get a unique incrementing value.

I'm trying to prevent deadlocks using query hints UPDLOCK and HOLDLOCK.

The SP

Selects value from a table,

insert if the value is not found (initial value is 1)

Or updates the table by incrementing the value from the first select

Returns the incremented value in an output parameter.

Here the table

CREATE TABLE MyCounters(
    [Id] [bigint] IDENTITY(1,1) NOT NULL,
    [Key] [nvarchar](20) NOT NULL UNIQUE,
    [Counter] [bigint] NOT NULL,
 CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

Questions

Will a single UPDLOCK be sufficient in the first select to prevent deadlocks?

Or do I need to select with UPDLOCK and HOLDLOCK?

Or do I need a second dummy select with UPDLOCK and HOLDLOCK to only lock the entire table for inserts but not for updates?

I've read this question but there no insert is used.

Below the simplified SP and after that a script I used to test in 2 tabs in SQL management studio. With only a single UPDLOCK the test script works (i.e. no deadlocks and counters at the correct values).

BEGIN TRANSACTION

DECLARE @Key nvarchar(3)
SET @Key = 'AA'
DECLARE @counter bigint
SET @counter=NULL

-- *** Question 1 *** Will a single UPDLOCK be sufficient in the first select to prevent deadlocks?
-- *** Question 2 *** 1. Or do I need to select with UPDLOCK and HOLDLOCK?
SELECT @counter=Counter FROM MyCounters WITH (UPDLOCK) WHERE Key = @Key

IF (@counter IS NULL)
BEGIN
    -- *** Question 3 *** Or do I need a second dummy select with UPDLOCK and HOLDLOCK to only lock the entire table for inserts but not update?
    -- lock the entire table before inserting (select into variable)
    --DECLARE @temp bigint
    --SELECT TOP 1 @temp = Counter FROM MyCounters WITH (UPDLOCK, HOLDLOCK)

    SET @counter=1
    INSERT INTO MyCounters ([Key],Counter) VALUES (@Key, @counter)
END
ELSE
BEGIN
    SET @counter=@counter+1
    UPDATE MyCounters SET Counter = @counter WHERE Key = @Key
END

SELECT @Key, @counter

COMMIT

Below the test script (which I ran in multiple tabs in SQL management studio)

BEGIN TRANSACTION

WAITFOR DELAY '00:00:05' --to give me a chance to start the script in multiple tabs

DECLARE @i int
SET @i=0
WHILE @i < 100
BEGIN

    DECLARE @Key nvarchar(3)
    SET @Key = 'A'+CONVERT(nvarchar(10),@i)
    DECLARE @counter bigint
    SET @counter=NULL
    SELECT @counter=Counter FROM MyCounters WITH (UPDLOCK) WHERE Key = @Key

    IF (@counter IS NULL)
    BEGIN
        -- lock the entire table before inserting (select into variable)
        --DECLARE @temp bigint
        --SELECT TOP 1 @temp = Counter FROM MyCounters WITH (UPDLOCK, HOLDLOCK)

        SET @counter=1
        INSERT INTO MyCounters ([Key],Counter) VALUES (@Key, @counter)
    END
    ELSE
    BEGIN
        SET @counter=@counter+1
        UPDATE MyCounters SET Counter = @counter WHERE Key = @Key
    END

    SELECT @i, @Key, @counter

    SET @i = @i + 1

END;

COMMIT

Body:
-- *** Question 1 *** Will a single UPDLOCK be sufficient in the first select to prevent deadlocks?
-- *** Question 2 *** 1. Or do I need to select with UPDLOCK and HOLDLOCK? SELECT @counter=Counter FROM MyCounters WITH (UPDLOCK) WHERE
Key = @Key

In in the default READ COMMITTED isolation level, the UPDLOCK will be released when the statement completes. Specify UPDLOCK,HOLDLOCK to retain locks until the transaction commits or rolls back.

I suggest you change the clustered primary key from the IDENTITY column to the natural key column Key or make the unique constraint the clustered index.  This will improve performance. If you don't actually use the Id column, remove it entirely. Throwing an unused IDENTITY surrogate key on tables is a common anti-pattern.

--clustered unique constraint
CREATE TABLE dbo.MyCounters(
    [Id] [bigint] IDENTITY(1,1) NOT NULL,
    [Key] [nvarchar](20) NOT NULL CONSTRAINT UQ_MyCounters_Key UNIQUE CLUSTERED,
    [Counter] [bigint] NOT NULL,
 CONSTRAINT [PK_Table_1] PRIMARY KEY NONCLUSTERED
    (
        [Id] ASC
    )
);

--remove unneeded surrogate key
CREATE TABLE dbo.MyCounters(
    [Key] [nvarchar](20) NOT NULL CONSTRAINT PK_MyCounters PRIMARY KEY CLUSTERED,
    [Counter] [bigint] NOT NULL
);

Also, add SET XACT_ABORT ON; to procs with explicit transactions to ensure the transaction is rolled back immediately after errors or client timeouts.


问:
How can I chain functions when i call it in Swift?
I am beginner in swift and I'm doing exercises to learn.

I have to filter any numbers that are even, sort the array, map them to string and print the result one item per line.

The problem is, when I call the function, I´m not able to chain the closures, and it only prints the third function.

```<code>import Foundation

let luckyNumbers = [7, 4, 38, 21, 16, 15, 12, 33, 31, 49]

func doImportantWorkChain (first: ([Int]) -> [Int], second: ([Int]) -> [Int], third: ([Int]) -> [String]) {
    first(luckyNumbers)
    second(luckyNumbers)
    third(luckyNumbers)

    third(luckyNumbers).forEach {
        print($0)
    }
}

doImportantWorkChain { number in
    return number.filter {
        return $0.isMultiple(of: 2)
    }
} second: { number in
    return number.sorted {
        return $0 < $1
    }
} third: { number in
    return number.map {
       ("\($0) is the lucky number")
    }
}
</code>```

Output

```<code>7 is the lucky number
4 is the lucky number
38 is the lucky number
21 is the lucky number
16 is the lucky number
15 is the lucky number
12 is the lucky number
33 is the lucky number
31 is the lucky number
49 is the lucky number
</code>```

Output I have to get

```<code>4 is the lucky number
12 is the lucky number
16 is the lucky number
38 is the lucky number
</code>```

I know that I have to use: luckyNumbers.first { }.second { }

When I try to write like this Xcode give me error: value of type '(([Int]) -> [Int], ([Int]) -> [Int], ([Int]) -> [String]) -> ()' has no member 'first'

So I erase first and give me this errors:

Expected member name following '.'

Top-level statement cannot begin with a closure expression

Value of type '(_) -> _' has no member 'second'

```<code>doImportantWorkChain.first{ number in
    return number.filter {
        return $0.isMultiple(of: 2)
    }
}.second{ number in
    return number.sorted {
        return $0 < $1
    }
}.third{ number in
    return number.map {
       ("\($0) is the lucky number")
    }
}
</code>```

Also I try to chain it when when I call them inside the function but doesn't work either.

答:
You are not using results from previous functions to next.

If you do so then you will end up with error on this third(luckyNumbers).forEach line as function expected [Int] and you will be going to pass [String] as output from this third(luckyNumbers) call.

To work this code, you can have following modifications and run

```<code> let luckyNumbers = [7, 4, 38, 21, 16, 15, 12, 33, 31, 49]

 func doImportantWorkChain (first: ([Int]) -> [Int], second: ([Int]) ->
    [Int], third: ([Int]) -> [String]) {
    let first_result = first(luckyNumbers)
    let second_result = second(first_result)
    let third_result = third(second_result)

    for result in third_result {
      print(result)
    }
 }

doImportantWorkChain { number in
  return number.filter {
      return $0.isMultiple(of: 2)
  }
} second: { number in
  return number.sorted {
      return $0 < $1
  }
} third: { number in
  return number.map {
     ("\($0) is the lucky number")
  }
}
</code>```

Body:
I am beginner in swift and I'm doing exercises to learn.

I have to filter any numbers that are even, sort the array, map them to string and print the result one item per line.

The problem is, when I call the function, I´m not able to chain the closures, and it only prints the third function.

import Foundation

let luckyNumbers = [7, 4, 38, 21, 16, 15, 12, 33, 31, 49]

func doImportantWorkChain (first: ([Int]) -> [Int], second: ([Int]) -> [Int], third: ([Int]) -> [String]) {
    first(luckyNumbers)
    second(luckyNumbers)
    third(luckyNumbers)

    third(luckyNumbers).forEach {
        print($0)
    }
}

doImportantWorkChain { number in
    return number.filter {
        return $0.isMultiple(of: 2)
    }
} second: { number in
    return number.sorted {
        return $0 < $1
    }
} third: { number in
    return number.map {
       ("\($0) is the lucky number")
    }
}

Output

7 is the lucky number
4 is the lucky number
38 is the lucky number
21 is the lucky number
16 is the lucky number
15 is the lucky number
12 is the lucky number
33 is the lucky number
31 is the lucky number
49 is the lucky number

Output I have to get

4 is the lucky number
12 is the lucky number
16 is the lucky number
38 is the lucky number

I know that I have to use: luckyNumbers.first { }.second { }

When I try to write like this Xcode give me error: value of type '(([Int]) -> [Int], ([Int]) -> [Int], ([Int]) -> [String]) -> ()' has no member 'first'

So I erase first and give me this errors:

Expected member name following '.'

Top-level statement cannot begin with a closure expression

Value of type '(_) -> _' has no member 'second'

doImportantWorkChain.first{ number in
    return number.filter {
        return $0.isMultiple(of: 2)
    }
}.second{ number in
    return number.sorted {
        return $0 < $1
    }
}.third{ number in
    return number.map {
       ("\($0) is the lucky number")
    }
}

Also I try to chain it when when I call them inside the function but doesn't work either.

Body:
You are not using results from previous functions to next.

If you do so then you will end up with error on this third(luckyNumbers).forEach line as function expected [Int] and you will be going to pass [String] as output from this third(luckyNumbers) call.

To work this code, you can have following modifications and run

 let luckyNumbers = [7, 4, 38, 21, 16, 15, 12, 33, 31, 49]

 func doImportantWorkChain (first: ([Int]) -> [Int], second: ([Int]) ->
    [Int], third: ([Int]) -> [String]) {
    let first_result = first(luckyNumbers)
    let second_result = second(first_result)
    let third_result = third(second_result)

    for result in third_result {
      print(result)
    }
 }

doImportantWorkChain { number in
  return number.filter {
      return $0.isMultiple(of: 2)
  }
} second: { number in
  return number.sorted {
      return $0 < $1
  }
} third: { number in
  return number.map {
     ("\($0) is the lucky number")
  }
}


问:
Nothing happens when automatically sending bump via a bot for discord.js
I aim to create a node.js bot for Discord allowing me to bump SEO site bots automatically. The bump works when done manually and my bot works very well and sends automatic bump messages but nothing happens. Do you know if the developers of SEO bots block the sending of automatic bumps from homemade bots?

Thank you in advance for your answer,

答: These sites are blocking the use of bots here. You could bypass this with a self-bot, but they're heavily against Discord's ToS.</p>


问:
How do I reference a documented Python function parameter using Sphinx markup?
I'd like to reference a previously-documented function parameter elsewhere in a Python docstring.  Consider the following (admittedly completely artificial) example:

```<code>def foo(bar):
    """Perform foo action
    :param bar: The bar parameter
    """

    def nested():
        """Some nested function that depends on enclosing scope's bar parameter.
        I'd like to reference function foo's bar parameter here
        with a link, is that possible?"""
        return bar * bar

    # ...
    return nested()
</code>```

Is there a simple way to embed a parameter reference using Sphinx markup, or will this happen automagically?

(I'm a complete Sphinx newbie.  I've been scanning the Sphinx docs and haven't found an answer to this question, or an example demonstrating proper markup.)

答:
Not to say that sphinx-paramlinks is not a fine solution, but I'm a bit
stubborn about adding more extensions to my project.

You won't get the benefit of the visual highlight, or an anchor icon, which is a bummer, but a reStructuredText hyperlink target before that section at least gets you close:

    def from_existing_id(cls, jobid, **kwargs):
        """Instantiates a new :class:`Job` object from an existing job ID.

        :param jobid: the ID of the previous job
        :param kwargs: keyword arguments supported by :meth:`deserialize`,
            *e.g.*, :ref:`ignore_missing <deserialize_params>`.
        """
        ⋮

    # elsewhere
    def deserialize(self, filename, copy_inputs=False, ignore_missing=False):
        """Reads a disk file into the current :class:`Job` object's config.

        .. _deserialize_params:

        :param filename: the filename to read from to disk
        :param copy_inputs: copy input files to output directory
        :param ignore_missing: don't bail if input files are missing
        """
        ⋮
```

The longer your parameter list gets, the less useful this becomes, though.

Body:
I'd like to reference a previously-documented function parameter elsewhere in a Python docstring.  Consider the following (admittedly completely artificial) example:

def foo(bar):
    """Perform foo action
    :param bar: The bar parameter
    """

    def nested():
        """Some nested function that depends on enclosing scope's bar parameter.
        I'd like to reference function foo's bar parameter here
        with a link, is that possible?"""
        return bar * bar

    # ...
    return nested()

Is there a simple way to embed a parameter reference using Sphinx markup, or will this happen automagically?

(I'm a complete Sphinx newbie.  I've been scanning the Sphinx docs and haven't found an answer to this question, or an example demonstrating proper markup.)

Body:
Not to say that sphinx-paramlinks is not a fine solution, but I'm a bit
stubborn about adding more extensions to my project.

You won't get the benefit of the visual highlight, or an anchor icon, which is a bummer, but a reStructuredText hyperlink target before that section at least gets you close:

    def from_existing_id(cls, jobid, **kwargs):
        """Instantiates a new :class:`Job` object from an existing job ID.

        :param jobid: the ID of the previous job
        :param kwargs: keyword arguments supported by :meth:`deserialize`,
            *e.g.*, :ref:`ignore_missing <deserialize_params>`.
        """
        ⋮

    # elsewhere
    def deserialize(self, filename, copy_inputs=False, ignore_missing=False):
        """Reads a disk file into the current :class:`Job` object's config.

        .. _deserialize_params:

        :param filename: the filename to read from to disk
        :param copy_inputs: copy input files to output directory
        :param ignore_missing: don't bail if input files are missing
        """
        ⋮

The longer your parameter list gets, the less useful this becomes, though.


问:
Is header propagation only java-agent can do?
I have three services A, B, C, and the calling relationship between them is A->B->C.

I would like to pass in a special http header when calling A, and subsequent requests caused by this request will automatically carry this http header.

Is it the fact that only java-agent can do it without hacking into the service code? Envoy seems to require users to modify the service code to explicitly configure the http headers.

Environment:

K8s-1.20.6 on TencentCloud

Istio-1.12.1 (installed using demo profile)

答:
Is header propagation only java-agent can do?

No, there are couple of ways to achive header propagation in istio, based on you specific situation.

Header propagation may be accomplished through client libraries, such as Zipkin or Jaeger. It may also be accomplished manually, as documented in the Distributed Tracing Task.

Look also at the topic What is the best practice of HTTP header propagation?

As you can see, there is no one perfect way to help you achieve your goal. See also:

Using OpenTracing with Istio/Envoy
Headers propagation with hpropagate


问:
Form fields stability php
How can I make fields still in the form fields after submitting the form and return with invalid input data?

```<code> <form action="" method="post">
             <label for="cellPhoneNo">البريد الالكتروني</label>
                <input type="text" name="emailAddress" class="textField"/>
                <span>*</span>
                <span><?php
                       if($emailValidator != CORRECT_VALUE)
                        echo $errorMessage[$emailValidator];?>
                </span>
                <br>

</form>
</code>```

and here's where I check the input

```<code> $emailValidator=checkInput($_POST['emailAddress'],INVALID_EMAIL_ADDRESS,'/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$/');
</code>```

when user submit invalid email address, the validation result shows the error message to user. How can I make the invalid error email address still in the input?

答:
add to input

```<code> <input type="text" name="emailAddress" class="textField" value="<?  echo (isset($_POST) ? $_POST['emailAddress'] : "") ?>"/>
</code>```

instead of "" you can insert your default value or just leave it like this :)

Title: Form fields stability php

Body:
How can I make fields still in the form fields after submitting the form and return with invalid input data?

 <form action="" method="post">
             البريد الالكتروني
                <input type="text" name="emailAddress" class="textField"/>
                *
                <?php
                       if($emailValidator != CORRECT_VALUE)
                        echo $errorMessage[$emailValidator];?>

</form>

and here's where I check the input

 $emailValidator=checkInput($_POST['emailAddress'],INVALID_EMAIL_ADDRESS,'/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$/');

when user submit invalid email address, the validation result shows the error message to user. How can I make the invalid error email address still in the input?

Body:
add to input

 <input type="text" name="emailAddress" class="textField" value="<?  echo (isset($_POST) ? $_POST['emailAddress'] : "") ?>"/>

instead of "" you can insert your default value or just leave it like this :)


问:
Google Maps Autocomplete strictbounds parameter doesn't work
I have tryied to used Google Maps strictbounds parameter to restrict autocomplete results to an specific area. My current code is:

var autocomplete = new google.maps.places.Autocomplete(spaceAddress, { types: [ 'geocode' ], strictbounds: {location: "-23.544085,-46.7125434", radius: "12000"}, language: "pt-BR" });

Althoug it doesn't break my application, it also doesn't restrict the results to the selected area. Alternatively, I used the country restriction below, but the customer doesn't like it!

Here's the complete code in use by now:

```<code>document.addEventListener("DOMContentLoaded", function() {
  var spaceAddress = document.getElementById('space_address');
  if (spaceAddress) {
  var autocomplete = new google.maps.places.Autocomplete(spaceAddress, { types: [ 'geocode' ], strictbounds: {location: "-23.544085,-46.7125434", radius: "12000"}, language: "pt-BR" });
  google.maps.event.addDomListener(spaceAddress, 'keydown', function(e) {
    if (e.key === "Enter") {
      e.preventDefault();
      const spaceAddress = document.getElementById('space_address').value;
      if (spaceAddress != '' && spaceAddress != null) {
      codeAddress(spaceAddress);
      }
    }
    });
  }
</code>```

Could someone please enlighten me?!

答:
Unfortunately I can't comment yet, so a new answer. The answer from danbeggan works, but there is a tiny error in his code. The attribute is called strictBounds, here is the correct code:

var circle = new google.maps.Circle({ center: new google.maps.LatLng(-23.544085, -46.7125434), radius: 12000 })
var autocomplete = new google.maps.places.Autocomplete(spaceAddress, { types: [ 'geocode' ], bounds: circle.getBounds(), strictBounds: true });
```

Note: radius is in meter

Body:
I have tryied to used Google Maps strictbounds parameter to restrict autocomplete results to an specific area. My current code is:

var autocomplete = new google.maps.places.Autocomplete(spaceAddress, { types: [ 'geocode' ], strictbounds: {location: "-23.544085,-46.7125434", radius: "12000"}, language: "pt-BR" });

Althoug it doesn't break my application, it also doesn't restrict the results to the selected area. Alternatively, I used the country restriction below, but the customer doesn't like it!

Here's the complete code in use by now:

document.addEventListener("DOMContentLoaded", function() {
  var spaceAddress = document.getElementById('space_address');
  if (spaceAddress) {
  var autocomplete = new google.maps.places.Autocomplete(spaceAddress, { types: [ 'geocode' ], strictbounds: {location: "-23.544085,-46.7125434", radius: "12000"}, language: "pt-BR" });
  google.maps.event.addDomListener(spaceAddress, 'keydown', function(e) {
    if (e.key === "Enter") {
      e.preventDefault();
      const spaceAddress = document.getElementById('space_address').value;
      if (spaceAddress != '' && spaceAddress != null) {
      codeAddress(spaceAddress);
      }
    }
    });
  }

Could someone please enlighten me?!

Body:
Unfortunately I can't comment yet, so a new answer. The answer from danbeggan works, but there is a tiny error in his code. The attribute is called strictBounds, here is the correct code:

var circle = new google.maps.Circle({ center: new google.maps.LatLng(-23.544085, -46.7125434), radius: 12000 })
var autocomplete = new google.maps.places.Autocomplete(spaceAddress, { types: [ 'geocode' ], bounds: circle.getBounds(), strictBounds: true });

Note: radius is in meter


问:
javascript filter array multiple conditions
I want to simplify an array of objects. Let's assume that I have following array:

```<code>var users = [{
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    address: 'USA'
    },
    {
        name: 'Tom',
        email: 'tom@mail.com',
        age: 35,
        address: 'England'
    },
    {
        name: 'Mark',
        email: 'mark@mail.com',
        age: 28,
        address: 'England'
}];
</code>```

And filter object:

```<code>var filter = {address: 'England', name: 'Mark'};
</code>```

For example i need to filter all users by address and name, so i do loop through filter object properties and check it out:

```<code>function filterUsers (users, filter) {
    var result = [];
    for (var prop in filter) {
        if (filter.hasOwnProperty(prop)) {

            //at the first iteration prop will be address
            for (var i = 0; i < filter.length; i++) {
                if (users[i][prop] === filter[prop]) {
                    result.push(users[i]);
                }
            }
        }
    }
    return result;
}
</code>```

So during first iteration when prop - address will be equal 'England' two users will be added to array result (with name Tom and Mark), but on the second iteration when prop name will be equal Mark only the last user should be added to array result, but i end up with two elements in array.

I have got a little idea as why is it happening but still stuck on it and could not find a good solution to fix it. Any help is appreciable. Thanks.

答:
```<code>users.filter(o => o.address == 'England' && o.name == 'Mark')
</code>```

Much better for es6. or you can use || (or) operator like this

```<code>users.filter(o => {return (o.address == 'England' || o.name == 'Mark')})
</code>```

Body:
I want to simplify an array of objects. Let's assume that I have following array:

var users = [{
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    address: 'USA'
    },
    {
        name: 'Tom',
        email: 'tom@mail.com',
        age: 35,
        address: 'England'
    },
    {
        name: 'Mark',
        email: 'mark@mail.com',
        age: 28,
        address: 'England'
}];

And filter object:

var filter = {address: 'England', name: 'Mark'};

For example i need to filter all users by address and name, so i do loop through filter object properties and check it out:

function filterUsers (users, filter) {
    var result = [];
    for (var prop in filter) {
        if (filter.hasOwnProperty(prop)) {

            //at the first iteration prop will be address
            for (var i = 0; i < filter.length; i++) {
                if (users[i][prop] === filter[prop]) {
                    result.push(users[i]);
                }
            }
        }
    }
    return result;
}

So during first iteration when prop - address will be equal 'England' two users will be added to array result (with name Tom and Mark), but on the second iteration when prop name will be equal Mark only the last user should be added to array result, but i end up with two elements in array.

I have got a little idea as why is it happening but still stuck on it and could not find a good solution to fix it. Any help is appreciable. Thanks.

Body:
users.filter(o => o.address == 'England' && o.name == 'Mark')

Much better for es6. or you can use || (or) operator like this

users.filter(o => {return (o.address == 'England' || o.name == 'Mark')})


问:
Target second span text when a common class is being used
I have some html snippet

```<code><p>
<span class="et-product-amount">1</span><span> x </span><bdi><span class="et-cart-product-price">CA$</span><span id="sec_price_4082395074_1161" class="et-cart-product-price">89</span></bdi>
</p>
</code>```

The first instance of .et-cart-product-price shows the currency symbol and the second shows the price.

To get the currency symbol i am using jquery like this

```<code>var currency_currency_symbol = $("span.et-cart-product-price").text();
</code>```

How can i select the text in the first and second occurrence of the et-cart-product-price class respectively?.

答:
Your selector finds multiple elements.

By calling text() on the array, the values are merged.

Since you want both values in a separate variable, you'll need to alter the selector, and use (eg) map() to convert the DOM element to the value you need. I've use a list syntax to assign the array values to 2 variables:

var currency_currency_spans = Array.from($("span.et-cart-product-price"));

var [ symbol, price ] = currency_currency_spans.map(e => e.innerHTML);
console.log('Symbol:', symbol);
console.log('Price:', price);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
  <span class="et-product-amount">1</span>
  <span> x </span>
  <bdi>
    <span class="et-cart-product-price">CA$</span>
    <span id="sec_price_4082395074_1161" class="et-cart-product-price">89</span>      </bdi>
</p></code>```

Body:
I have some html snippet

1 x <bdi>CA$89</bdi>

The first instance of .et-cart-product-price shows the currency symbol and the second shows the price.

To get the currency symbol i am using jquery like this

var currency_currency_symbol = $("span.et-cart-product-price").text();

How can i select the text in the first and second occurrence of the et-cart-product-price class respectively?.

Body:
Your selector finds multiple elements.

By calling text() on the array, the values are merged.

Since you want both values in a separate variable, you'll need to alter the selector, and use (eg) map() to convert the DOM element to the value you need. I've use a list syntax to assign the array values to 2 variables:

var currency_currency_spans = Array.from($("span.et-cart-product-price"));

var [ symbol, price ] = currency_currency_spans.map(e => e.innerHTML);
console.log('Symbol:', symbol);
console.log('Price:', price);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
  <span class="et-product-amount">1</span>
  <span>&nbsp;x&nbsp;</span>
  <bdi>
    <span class="et-cart-product-price">CA$</span>
    <span id="sec_price_4082395074_1161" class="et-cart-product-price">89</span>      </bdi>
</p>


问:
color a cell base on column name with jquery
I need to color a cell if the value is "ok" and if the cell is part of the column named "name".

var intervalId = window.setInterval(function(){
    var tableRow = $("td").filter(function() {

        if($(this).text() === "ok") {
            $(this).addClass( "table-danger" );
        }

    }).closest("tr");
  }, 1000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.table-danger {
  background: red;
}</code>```

            Header 1
            Header 2
            name

            ok;
            aa;
            ok

            cc;
            aa;
            else

            bb;
            aa;
            else

            bb;
            aa;
            ok

```

I can do the color with that function, but it will color all cell with "ok".
How can I adapt my function ?

答:
You can use

```<code>td:nth-child
</code>```

to select td's that are in a specific column, note that this is 1-based, so 3rd column is td:nth-child(3)

Keeping the original code of looping through and addClass as they are found:

```<code>$("td:nth-child(3)").each(function() {
  if ($(this).text() === "ok") {
    $(this).addClass("table-danger");
  }
})
</code>```

normally, you would return true in the filter (in the original code) and mass-apply addClass, ie:

```<code>var cells = $("td:nth-child(3)").filter(function() {
  return $(this).text() === "ok";
})
cells.addClass("table-danger");
</code>```

var cells = $("td:nth-child(3)").filter(function() {
  return $(this).text() === "ok";
})
cells.addClass("table-danger");```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.table-danger {
  background-color: pink
}</code>```

      Header 1
      Header 2
      name

      ok
      aa;
      ok

      cc;
      aa;
      else

      bb;
      aa;
      else

      bb;
      aa;
      ok

```
</div>
</div>
</p>
<p>If the column is unknown, but needs to be the "name" column, then you'll need to find that column first, <code>filter</code> is again ideal for this.</p>
```var column = $("thead th").filter(function() {
  return $(this).text() === "name";
});
var colIndex = column.index() + 1; /// from 0-based to 1-based
```
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var column = $("thead th").filter(function() {
  return $(this).text() === "name";
});
var colIndex = column.index() + 1; /// from 0-based to 1-based

$(`td:nth-child(${colIndex})`).each(function() {

  if ($(this).text() === "ok") {
    $(this).addClass("table-danger");
  }

})</code>```

.table-danger {
  background-color: pink
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>name</th>
      <th>Header 1</th>
      <th>Header 2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>ok</td>
      <td>aa;</td>
      <td>ok</td>
    </tr>
    <tr>
      <td>cc;</td>
      <td>aa;</td>
      <td>else</td>
    </tr>
    <tr>
      <td>bb;</td>
      <td>aa;</td>
      <td>else</td>
    </tr>
    <tr>
      <td>bb;</td>
      <td>aa;</td>
      <td>ok</td>
    </tr>
  </tbody>
</table></code>```

Body:
I need to color a cell if the value is "ok" and if the cell is part of the column named "name".

var intervalId = window.setInterval(function(){
    var tableRow = $("td").filter(function() {

        if($(this).text() === "ok") {
            $(this).addClass( "table-danger" );
        }

    }).closest("tr");
  }, 1000);

.table-danger {
  background: red;
}

            Header 1
            Header 2
            name

            ok;
            aa;
            ok

            cc;
            aa;
            else

            bb;
            aa;
            else

            bb;
            aa;
            ok

I can do the color with that function, but it will color all cell with "ok".
How can I adapt my function ?

Body:
You can use

td:nth-child

to select td's that are in a specific column, note that this is 1-based, so 3rd column is td:nth-child(3)

Keeping the original code of looping through and addClass as they are found:

$("td:nth-child(3)").each(function() {
  if ($(this).text() === "ok") {
    $(this).addClass("table-danger");
  }
})

normally, you would return true in the filter (in the original code) and mass-apply addClass, ie:

var cells = $("td:nth-child(3)").filter(function() {
  return $(this).text() === "ok";
})
cells.addClass("table-danger");

var cells = $("td:nth-child(3)").filter(function() {
  return $(this).text() === "ok";
})
cells.addClass("table-danger");

.table-danger {
  background-color: pink
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>Header 1</th>
      <th>Header 2</th>
      <th>name</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>ok</td>          <!-- NO color -->
      <td>aa;</td>
      <td>ok</td>          <!-- color -->
    </tr>
    <tr>
      <td>cc;</td>
      <td>aa;</td>
      <td>else</td>
    </tr>
    <tr>
      <td>bb;</td>
      <td>aa;</td>
      <td>else</td>
    </tr>
    <tr>
      <td>bb;</td>
      <td>aa;</td>
      <td>ok</td>
    </tr>
  </tbody>
</table>

If the column is unknown, but needs to be the "name" column, then you'll need to find that column first, filter is again ideal for this.

var column = $("thead th").filter(function() {
  return $(this).text() === "name";
});
var colIndex = column.index() + 1; /// from 0-based to 1-based

var column = $("thead th").filter(function() {
  return $(this).text() === "name";
});
var colIndex = column.index() + 1; /// from 0-based to 1-based

$(`td:nth-child(${colIndex})`).each(function() {

  if ($(this).text() === "ok") {
    $(this).addClass("table-danger");
  }

})

.table-danger {
  background-color: pink
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>name</th>
      <th>Header 1</th>
      <th>Header 2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>ok</td>
      <td>aa;</td>
      <td>ok</td>
    </tr>
    <tr>
      <td>cc;</td>
      <td>aa;</td>
      <td>else</td>
    </tr>
    <tr>
      <td>bb;</td>
      <td>aa;</td>
      <td>else</td>
    </tr>
    <tr>
      <td>bb;</td>
      <td>aa;</td>
      <td>ok</td>
    </tr>
  </tbody>
</table>


问:
How to compare given value with Pandas dataframe values without using a for loop
I have the following example dataframe:

```<code>d = {'target': [1, 2, 4, 3, 6, 5]}
df = pd.DataFrame(data=d)
df
</code>```

Output:

```<code>    target
0   1
1   2
2   4
3   3
4   6
5   5
</code>```

I need a function that will do the following:

Let the function have the name find_index_of_first_hit(value).

The function...

will be comparing the function input value with elements of the column target.

will search for the first column value that is greater than or equal to the function input value.

and will return the index of the dataframe row for the very first match.

Example:

```<code>find_index_of_first_hit(3)
</code>```

Should return 2 which is the index of the target column value 4, which is where the column value (which is 4) is >= the function input value 3 for the first time in the column. And the index is 2, which is expected to be returned.

The function is expected to return -1 if none of column values are >= the function input value.

The original dataframe is fairly large and I wonder how I can write such a program without using for loop.

This function needs to be written in Python and it needs to be a fast solution, which is why I would like to avoid for loop. Performance is important here.

How can I write such a Python function doing this work?

答:
Use Series.idxmax with test if value exist in if-else with Series.any:

```<code>def find_index_of_first_hit(val):
    a = df['target'].ge(val)
    return a.idxmax() if a.any() else -1

print (find_index_of_first_hit(3))
2
print (find_index_of_first_hit(30))
-1
</code>```

Body:
I have the following example dataframe:

d = {'target': [1, 2, 4, 3, 6, 5]}
df = pd.DataFrame(data=d)
df

Output:

    target
0   1
1   2
2   4
3   3
4   6
5   5

I need a function that will do the following:

Let the function have the name find_index_of_first_hit(value).

The function...

will be comparing the function input value with elements of the column target.

will search for the first column value that is greater than or equal to the function input value.

and will return the index of the dataframe row for the very first match.

Example:

find_index_of_first_hit(3)

Should return 2 which is the index of the target column value 4, which is where the column value (which is 4) is >= the function input value 3 for the first time in the column. And the index is 2, which is expected to be returned.

The function is expected to return -1 if none of column values are >= the function input value.

The original dataframe is fairly large and I wonder how I can write such a program without using for loop.

This function needs to be written in Python and it needs to be a fast solution, which is why I would like to avoid for loop. Performance is important here.

How can I write such a Python function doing this work?

Body:
Use Series.idxmax with test if value exist in if-else with Series.any:

def find_index_of_first_hit(val):
    a = df['target'].ge(val)
    return a.idxmax() if a.any() else -1

print (find_index_of_first_hit(3))
2
print (find_index_of_first_hit(30))
-1


问:
How method hiding works in C#? (Part Two)
The following program prints

```<code>A:C(A,B)
B:C(A,B)
</code>```

(as it should)

```<code>public interface I
{
    string A();
}

public class C : I
{
    public string A()
    {
        return "A";
    }

    public string B()
    {
        return "B";
    }
}

public class A
{
    public virtual void Print(C c)
    {
        Console.WriteLine("A:C(" + c.A() + "," + c.B() + ")");
    }
}

public class B : A
{
    public new void Print(C c)
    {
        Console.WriteLine("B:C(" + c.A() + "," + c.B() + ")");
    }

    public void Print(I i)
    {
        Console.WriteLine("B:I(" + i.A() + ")");
    }
}

class Program
{
    public static void Main(string[] args)
    {
        A a = new A();
        B b = new B();
        C c = new C();
        a.Print(c);
        b.Print(c);
    }
}
</code>```

however, if I change keyword 'new' to 'override' in class B like so:

```<code>    public override void Print(C c)
</code>```

all of a sudden program starts to print:

```<code>A:C(A,B)
B:I(A)
</code>```

Why?

答:
Ok,  so

```<code>    public new void Print(C c)
    {
        Console.WriteLine("B:C(" + c.A() + "," + c.B() + ")");
    }

    public void Print(I i)
    {
        Console.WriteLine("B:I(" + i.A() + ")");
    }
</code>```

This declares a new method for the print.  Now because B inherits from A, you are simly calling the new method twice.  When you overide the method, this then changes the method signature when you call for A, but when you call the B signature, then it has its own method signature.

I am not sure if I am explaining clear but good question.

using new:

A and B get the same implementation of the Print Method.

using override:

A has a different method signature to B as, you have not changed the method signature in B only in A.

using the new it basically ignores this:

```<code>    public void Print(I i)
    {
        Console.WriteLine("B:I(" + i.A() + ")");
    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
The following program prints

A:C(A,B)
B:C(A,B)

(as it should)

public interface I
{
    string A();
}

public class C : I
{
    public string A()
    {
        return "A";
    }

    public string B()
    {
        return "B";
    }
}

public class A
{
    public virtual void Print(C c)
    {
        Console.WriteLine("A:C(" + c.A() + "," + c.B() + ")");
    }
}

public class B : A
{
    public new void Print(C c)
    {
        Console.WriteLine("B:C(" + c.A() + "," + c.B() + ")");
    }

    public void Print(I i)
    {
        Console.WriteLine("B:I(" + i.A() + ")");
    }
}

class Program
{
    public static void Main(string[] args)
    {
        A a = new A();
        B b = new B();
        C c = new C();
        a.Print(c);
        b.Print(c);
    }
}

however, if I change keyword 'new' to 'override' in class B like so:

    public override void Print(C c)

all of a sudden program starts to print:

A:C(A,B)
B:I(A)

Why?

Body:
Ok,  so

    public new void Print(C c)
    {
        Console.WriteLine("B:C(" + c.A() + "," + c.B() + ")");
    }

    public void Print(I i)
    {
        Console.WriteLine("B:I(" + i.A() + ")");
    }

This declares a new method for the print.  Now because B inherits from A, you are simly calling the new method twice.  When you overide the method, this then changes the method signature when you call for A, but when you call the B signature, then it has its own method signature.

I am not sure if I am explaining clear but good question.

using new:

A and B get the same implementation of the Print Method.

using override:

A has a different method signature to B as, you have not changed the method signature in B only in A.

using the new it basically ignores this:

    public void Print(I i)
    {
        Console.WriteLine("B:I(" + i.A() + ")");
    }


问:
C# serialize only values into a byte stream
Is there any possibility to automatically serialize properties of a class into a byte[] array or stream.

```<code>Stream stream = File.Open(@"C:/traiBin.bin", FileMode.Create);
BinaryFormatter bFormatter = new BinaryFormatter();
bFormatter.Serialize(stream, this.rcpt);
stream.Close();
</code>```

This example above serialized the whole class including namespaces, class name, variable names etc.
If there is no automated solution it will do it by hand.

Regards,
Mark

答:
I think you have to :

Or implement your own serialization mechanism ( can be not so hard based on your requirements), so in stream you will have kind of header that identifies the type saved and after type data stream, after another header and its type data stream again, and so on...

Or you can use something like this http://www.codeproject.com/KB/cs/generic_deep_cloning.aspx . Just an example of serialization, that author of article uses for deep cloning purposes.

Body:
Is there any possibility to automatically serialize properties of a class into a byte[] array or stream.

Stream stream = File.Open(@"C:/traiBin.bin", FileMode.Create);
BinaryFormatter bFormatter = new BinaryFormatter();
bFormatter.Serialize(stream, this.rcpt);
stream.Close();

This example above serialized the whole class including namespaces, class name, variable names etc.
If there is no automated solution it will do it by hand.

Regards,
Mark


问:
Apply a function that takes two vectors as input to two matrices across their corresponding columns (in R)
I have a function in R that takes two vectors and an integer like this:

```<code>MyFunction<-function(MyLoot, DungeonLoot, DungeonOrder)
{

  # Perfect Match
  PerfectMatch = MyLoot[1]==DungeonLoot[1]

  # Group Match
  GroupandClassMatch = (MyLoot[2]==DungeonLoot[2])&(MyLoot[3]>=DungeonLoot[3])

  # Order Match
  OrderMatch = MyLoot[5]==DungeonOrder

  # Order Match +1
  OrderMatchPlusOne = (OrderMatch)&(MyLoot[8]==1)

  # Final Score
  Score = PerfectMatch*1 + GroupandClassMatch*1 + OrderMatch*2 + OrderMatchPlusOne*1

  return(Score)
}
</code>```

Now I want to apply MyFunction to two matrices Matrix1 and Matrix2 across their rows so that I have a vector that looks something like:

```<code>c(MyFunction(Matrix1[1,],Matrix2[1,],12),MyFunction(Matrix1[2,],Matrix2[2,],12),...,MyFunction[Matrix1[n,],Matrix2[n,],12)
</code>```

What is the best (and most efficient) way of doing this? I could use a for loop but wondering if there is a better way e.g. using one of apply, sapply, mapply, lappy functions

答:
This achieved what I wanted - not sure if it is the most computationally efficient solution though.</p>
```<code>t(mapply(function(x,y) MyFunction(x,y,11), split(MyLoot, col(MyLoot)), split(DungeonLoot, col(DungeonLoot))))
</code>```

Body:
I have a function in R that takes two vectors and an integer like this:

MyFunction<-function(MyLoot, DungeonLoot, DungeonOrder)
{

  # Perfect Match
  PerfectMatch = MyLoot[1]==DungeonLoot[1]

  # Group Match
  GroupandClassMatch = (MyLoot[2]==DungeonLoot[2])&(MyLoot[3]>=DungeonLoot[3])

  # Order Match
  OrderMatch = MyLoot[5]==DungeonOrder

  # Order Match +1
  OrderMatchPlusOne = (OrderMatch)&(MyLoot[8]==1)

  # Final Score
  Score = PerfectMatch*1 + GroupandClassMatch*1 + OrderMatch*2 + OrderMatchPlusOne*1

  return(Score)
}

Now I want to apply MyFunction to two matrices Matrix1 and Matrix2 across their rows so that I have a vector that looks something like:

c(MyFunction(Matrix1[1,],Matrix2[1,],12),MyFunction(Matrix1[2,],Matrix2[2,],12),...,MyFunction[Matrix1[n,],Matrix2[n,],12)

What is the best (and most efficient) way of doing this? I could use a for loop but wondering if there is a better way e.g. using one of apply, sapply, mapply, lappy functions

Body:
This achieved what I wanted - not sure if it is the most computationally efficient solution though.

t(mapply(function(x,y) MyFunction(x,y,11), split(MyLoot, col(MyLoot)), split(DungeonLoot, col(DungeonLoot))))


问:
Mongodb: how to update the latest field
I am new to Mongodb. I have a collection of this form:

db.buckets.aggregate()

```<code>[
    {
        "_id": ObjectId("6202faa5eeaef7a5b1c974d6"),
        "bucket": "7835@0493",
        "ts": ISODate("2022-02-08T23:20:05.107Z"),
        "val": {"Wh1": 0, "Wh2": 0}
    },
    {
        "_id": ObjectId("6202faaeeeaef7a5b1c974d7"),
        "bucket": "7805@0498",
        "ts": ISODate("2022-02-08T23:20:14.988Z"),
        "val": {"Wh1": 0, "Wh2": 0}
    }
]
</code>```

......

I would like to update the fields Wh2 and Wh1 of the latest "bucket" : "7835@0493"

I tried the following :

```<code>db.buckets.findAndModify({query: {"bucket": "7835@2096"},sort: {ts:-1},update({"val": {"Wh1": 90,"Wh2": 50}})})
</code>```

and got:

2022-02-09T20:28:34.834+0900 E  QUERY    [js] uncaught exception: SyntaxError: missing variable name :
@(shell):1:99

any help is appreciated.

答:
From findAndModify docs, you miss out the update operator and also some syntax errors.

```<code>db.buckets.findAndModify({
    query: { "bucket": "7835@0493" },
    sort: { ts:-1 },
    update: {
        $set: {
            "val": {
                "Wh1": 90,
                "Wh2": 50
            }
        }
    }
})
</code>```

Title: Mongodb: how to update the latest field

Body:
I am new to Mongodb. I have a collection of this form:

db.buckets.aggregate()

[
    {
        "_id": ObjectId("6202faa5eeaef7a5b1c974d6"),
        "bucket": "7835@0493",
        "ts": ISODate("2022-02-08T23:20:05.107Z"),
        "val": {"Wh1": 0, "Wh2": 0}
    },
    {
        "_id": ObjectId("6202faaeeeaef7a5b1c974d7"),
        "bucket": "7805@0498",
        "ts": ISODate("2022-02-08T23:20:14.988Z"),
        "val": {"Wh1": 0, "Wh2": 0}
    }
]

......

I would like to update the fields Wh2 and Wh1 of the latest "bucket" : "7835@0493"

I tried the following :

db.buckets.findAndModify({query: {"bucket": "7835@2096"},sort: {ts:-1},update({"val": {"Wh1": 90,"Wh2": 50}})})

and got:

2022-02-09T20:28:34.834+0900 E  QUERY    [js] uncaught exception: SyntaxError: missing variable name :
@(shell):1:99

any help is appreciated.

Body:
From findAndModify docs, you miss out the update operator and also some syntax errors.

db.buckets.findAndModify({
    query: { "bucket": "7835@0493" },
    sort: { ts:-1 },
    update: {
        $set: {
            "val": {
                "Wh1": 90,
                "Wh2": 50
            }
        }
    }
})


问:
how to rename a key value in a linux file
I need to rename a word/field in main.dev.ts in a react project

the file is  under build/app/main.dev.ts

need to change like - ELECTRON_WEBPACK_APP_SNAME : abc to ELECTRON_WEBPACK_APP_SNAME :def

code is :-

```<code>}
process.env.ELECTRON_WEBPACK_APP_API_KEY = process.env.ELECTRON_WEBPACK_APP_API_KEY ? process.env.ELECTRON_WEBPACK_APP_API_KEY : 'cfghjdkw-123e-123e-6756346474-ufhdfg223';
process.env.ELECTRON_WEBPACK_APP_BRAND_NAME = process.env.ELECTRON_WEBPACK_APP_BRAND_NAME ? process.env.ELECTRON_WEBPACK_APP_BRAND_NAME : 'Abc';
process.env.ELECTRON_WEBPACK_APP_SNAME = process.env.ELECTRON_WEBPACK_APP_SNAME ? process.env.ELECTRON_WEBPACK_APP_SNAME : 'abc';
console.log("process.env.ELECTRON_WEBPACK_APP_SNAME", process.env.ELECTRON_WEBPACK_APP_SNAME);

</code>```

tried this but its not renaming

```<code>sed '/^ELECTRON_WEBPACK_APP_SNAME : abc /s/=.*$/= ELECTRON_WEBPACK_APP_SNAME : def/' main.dev.ts
</code>```

any help appreciated...!

答: sed 's/process.env.ELECTRON_WEBPACK_APP_SNAME : 'abc'/process.env.ELECTRON_WEBPACK_APP_SNAME : 'def'/g' main.dev.ts</p>

Body:
I need to rename a word/field in main.dev.ts in a react project

the file is  under build/app/main.dev.ts

need to change like - ELECTRON_WEBPACK_APP_SNAME : abc to ELECTRON_WEBPACK_APP_SNAME :def

code is :-

}
process.env.ELECTRON_WEBPACK_APP_API_KEY = process.env.ELECTRON_WEBPACK_APP_API_KEY ? process.env.ELECTRON_WEBPACK_APP_API_KEY : 'cfghjdkw-123e-123e-6756346474-ufhdfg223';
process.env.ELECTRON_WEBPACK_APP_BRAND_NAME = process.env.ELECTRON_WEBPACK_APP_BRAND_NAME ? process.env.ELECTRON_WEBPACK_APP_BRAND_NAME : 'Abc';
process.env.ELECTRON_WEBPACK_APP_SNAME = process.env.ELECTRON_WEBPACK_APP_SNAME ? process.env.ELECTRON_WEBPACK_APP_SNAME : 'abc';
console.log("process.env.ELECTRON_WEBPACK_APP_SNAME", process.env.ELECTRON_WEBPACK_APP_SNAME);

tried this but its not renaming

sed '/^ELECTRON_WEBPACK_APP_SNAME : abc /s/=.*$/= ELECTRON_WEBPACK_APP_SNAME : def/' main.dev.ts

any help appreciated...!


问:
Is there any way to append a string value to key of a hash in Redis?
Redis provided solution to append string value to a key.

APPEND mykey "Hello"

but not find any solution to append string value to a key of hash.

答:
There is RENAME command.

```<code>RENAME oldkey newkey
</code>```

To clarify, if you want to append World to an existing key Hello,

```<code>RENAME Hello HelloWorld
</code>```

Body:
There is RENAME command.

RENAME oldkey newkey

To clarify, if you want to append World to an existing key Hello,

RENAME Hello HelloWorld


答:
Try to use javascript to validate the email before posting it to your server-side code :)

Check this link: http://www.zparacha.com/validate-email-address-using-javascript-regular-expression/

Title: Form fields stability php

Body:
How can I make fields still in the form fields after submitting the form and return with invalid input data?

 <form action="" method="post">
             البريد الالكتروني
                <input type="text" name="emailAddress" class="textField"/>
                *
                <?php
                       if($emailValidator != CORRECT_VALUE)
                        echo $errorMessage[$emailValidator];?>

</form>

and here's where I check the input

 $emailValidator=checkInput($_POST['emailAddress'],INVALID_EMAIL_ADDRESS,'/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$/');

when user submit invalid email address, the validation result shows the error message to user. How can I make the invalid error email address still in the input?


问:
parameter to builtin must be a string constant or literal
I am trying to use __builtin_cpu_supports not with a literal, but with a string but it fails.

Code:

```<code>const char s[] = "cmov";
__builtin_cpu_supports(s);
const char *t = "cmov";
__builtin_cpu_supports(t);
</code>```

Result:

```<code>builtin_support.c:25:5: error: parameter to builtin must be a string constant or literal
   25 |     __builtin_cpu_supports(s);
      |     ^~~~~~~~~~~~~~~~~~~~~~
builtin_support.c:27:5: error: parameter to builtin must be a string constant or literal
   27 |     __builtin_cpu_supports(t);
      |     ^~~~~~~~~~~~~~~~~~~~~~
</code>```

Why?

答:
Ok for some reason and contrary to the error message the built-in function only wants a literal, not a string.

Using directly CPUID looks more convenient.

```<code>#include <cpuid.h>
unsigned int eax, ebx, ecx, edx;
__get_cpuid(0x01, &eax, &ebx, &ecx, &edx);
</code>```

Body:
I am trying to use __builtin_cpu_supports not with a literal, but with a string but it fails.

Code:

const char s[] = "cmov";
__builtin_cpu_supports(s);
const char *t = "cmov";
__builtin_cpu_supports(t);

Result:

builtin_support.c:25:5: error: parameter to builtin must be a string constant or literal
   25 |     __builtin_cpu_supports(s);
      |     ^~~~~~~~~~~~~~~~~~~~~~
builtin_support.c:27:5: error: parameter to builtin must be a string constant or literal
   27 |     __builtin_cpu_supports(t);
      |     ^~~~~~~~~~~~~~~~~~~~~~

Why?

Body:
Ok for some reason and contrary to the error message the built-in function only wants a literal, not a string.

Using directly CPUID looks more convenient.

#include <cpuid.h>
unsigned int eax, ebx, ecx, edx;
__get_cpuid(0x01, &eax, &ebx, &ecx, &edx);


问:
Error: Cannot install in Homebrew on ARM processor in Intel default prefix (/usr/local)
I use the latest Apple M1 chip processor. And I keep getting errors while application installation.

say.,

```<code>brew install openjdk@11
</code>```
```<code>Error: Cannot install in Homebrew on ARM processor in Intel default prefix (/usr/local)!
Please create a new installation in /opt/homebrew using one of the
"Alternative Installs" from:
  https://docs.brew.sh/Installation
You can migrate your previously installed formula list with:
  brew bundle dump
</code>```

Need help with exact steps to follow.

答:
Run this in the terminal it fixes the issue

eval "$(/opt/homebrew/bin/brew shellenv)"

Body:
I use the latest Apple M1 chip processor. And I keep getting errors while application installation.

say.,

brew install openjdk@11

Error: Cannot install in Homebrew on ARM processor in Intel default prefix (/usr/local)!
Please create a new installation in /opt/homebrew using one of the
"Alternative Installs" from:
  https://docs.brew.sh/Installation
You can migrate your previously installed formula list with:
  brew bundle dump

Need help with exact steps to follow.


问:
How to calculate the sum of numbers in deeply nested array of objects using JavaScript?
I just started learning JavaScript, and ran into such a problem, I have a nested array, I want to summarize the price value of these arrays and return the existing sum, I wonder which method is applicable for it, which does not hurt the performance, I need one example to understand the way to solve the problem. Thanks in advance

const initialData = [
      {
          title: 'm2212',
          data: [
              {
                  id: 98233181232,
                  variations:[{
                          warranty: '',
                          price: 120,
                          comment: '',
                      }]

              },
          ]
      },
      {
          title: 'm2',
          data: [
              {
                  id: 982812,
                  variations:[{
                          warranty: '',
                          price: 92,
                          comment: '',
                      }]

              },
               {
                  id: 92182812,
                  variations:[{
                          warranty: '',
                          price: 922,
                          comment: '',
                      }]

              },
          ]
      },
 ]

 //what i tried
 let sum = 0
 initialData.forEach((el)=>{
   el.data.forEach((el1)=>{
     sum = sum + el1.variations[0].price
    })
 })

 console.log(sum);```

答:
The simplest and performant approach would be something like this code:

```<code>  const sum = initialData.reduce((sum, item) => {
    const itemSum = item.data.reduce((dataSum, dataItem) => {
      const itemDataSum = dataItem.variations.reduce((variantsSum, variantItem) => {
        return variantsSum + variantItem.price;
      }, 0);

      return dataSum + itemDataSum;
    }, 0);
    return sum + itemSum;
  }, 0);
</code>```

  const initialData = [
    {
      title: "m2212",
      data: [
        {
          id: 98233181232,
          variations: [
            {
              warranty: "",
              price: 120,
              comment: ""
            }
          ]
        }
      ]
    },
    {
      title: "m2",
      data: [
        {
          id: 982812,
          variations: [
            {
              warranty: "",
              price: 92,
              comment: ""
            }
          ]
        },
        {
          id: 92182812,
          variations: [
            {
              warranty: "",
              price: 922,
              comment: ""
            }
          ]
        }
      ]
    }
  ];

  const sum = initialData.reduce((sum, item) => {
    const itemSum = item.data.reduce((dataSum, dataItem) => {
      const itemDataSum = dataItem.variations.reduce((variantsSum, variantItem) => {
        return variantsSum + variantItem.price;
      }, 0);

      return dataSum + itemDataSum;
    }, 0);
    return sum + itemSum;
  }, 0);

  console.log(sum);```

Body:
The simplest and performant approach would be something like this code:

  const sum = initialData.reduce((sum, item) => {
    const itemSum = item.data.reduce((dataSum, dataItem) => {
      const itemDataSum = dataItem.variations.reduce((variantsSum, variantItem) => {
        return variantsSum + variantItem.price;
      }, 0);

      return dataSum + itemDataSum;
    }, 0);
    return sum + itemSum;
  }, 0);

  const initialData = [
    {
      title: "m2212",
      data: [
        {
          id: 98233181232,
          variations: [
            {
              warranty: "",
              price: 120,
              comment: ""
            }
          ]
        }
      ]
    },
    {
      title: "m2",
      data: [
        {
          id: 982812,
          variations: [
            {
              warranty: "",
              price: 92,
              comment: ""
            }
          ]
        },
        {
          id: 92182812,
          variations: [
            {
              warranty: "",
              price: 922,
              comment: ""
            }
          ]
        }
      ]
    }
  ];

  const sum = initialData.reduce((sum, item) => {
    const itemSum = item.data.reduce((dataSum, dataItem) => {
      const itemDataSum = dataItem.variations.reduce((variantsSum, variantItem) => {
        return variantsSum + variantItem.price;
      }, 0);

      return dataSum + itemDataSum;
    }, 0);
    return sum + itemSum;
  }, 0);

  console.log(sum);


问:
Can't install node-sass@6 for node v16
This is my package.json after uninstalling sass  node-sass and sass-loader because I changed my node version from 14 to 16,

```<code>{
  "name": "our-awesome-project",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate",
    "static": "NUXTJS_DEPLOY_TARGET=static NUXTJS_SSR=true nuxt generate",
    "build-and-start": "NUXTJS_DEPLOY_TARGET=server NUXTJS_SSR=false nuxt build && NUXTJS_DEPLOY_TARGET=server NUXTJS_SSR=false nuxt start"
  },
  "husky": {
    "hooks": {
      "pre-commit": "cross-env PRE_COMMIT=true lint-staged -r"
    }
  },
  "dependencies": {
    "core-js": "^3.19.3",
    "nuxt": "^2.15.8",
    "nuxt-i18n": "^6.28.1",
    "nuxt-purgecss": "^1.0.0",
    "vue": "^2.6.14",
    "vue-server-renderer": "^2.6.14",
    "vue-template-compiler": "^2.6.14",
    "webpack": "^4.46"
  },
  "devDependencies": {
    "@nuxtjs/eslint-config": "^8.0.0",
    "@nuxtjs/google-fonts": "^1.3.0",
    "@nuxtjs/storybook": "^4.2.0",
    "@nuxtjs/style-resources": "^1.2.1",
    "@vue/cli-plugin-babel": "^4.5.15",
    "babel-eslint": "^10.1.0",
    "eslint": "^8.7.0",
    "husky": "^7.0.4",
    "nuxt-svg-loader": "^1.2.0",
    "postcss": "^8.4.5"
  }
}
</code>```

According to this I should install node-sass version 6.0

But I'm trying:
npm install --save-dev sass@1.49.0 node-sass@6.0.1 sass-loader@10.2.1

Also, read here to add --unsafe-perm so I tried:
npm install --save-dev --unsafe-perm sass@1.49.0 node-sass@6.0.1 sass-loader@10.2.1

But it keeps failing, being the first error always this one:

```<code>npm ERR! code 1
npm ERR! path /Users/toniweb/Proyectos/our-awesome-project/node_modules/node-sass
npm ERR! command failed
npm ERR! command sh -c node scripts/build.js
npm ERR! Building: /Users/user/.nvm/versions/node/v16.13.1/bin/node /Users/toniweb/Proyectos/our-awesome-project/node_modules/node-gyp/bin/node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=
</code>```

I tried removing node_modules package-lock.json and the same result

Of course, this is driving me nuts.. please tell me that anyone has an idea to try out

答:
We have a Nuxt 2.15.8 app running on Node 16, in which a couple of months ago we switched from node-sass to sass, as the former is deprecated.

I recall at the time it took some figuring out, but in the end we just needed to install some postcss parsers to get the Nuxt app fully working with sass & sass-loader.

Taking as the baseline the package.json in your post, try:

npm install --save-dev \
  sass@1.49.4 \
  sass-loader@10.2.1 \
  postcss-html@1.3.0 \
  postcss-scss@4.0.3
```

Title: Can't install node-sass@6 for node v16

Body:
This is my package.json after uninstalling sass  node-sass and sass-loader because I changed my node version from 14 to 16,

{
  "name": "our-awesome-project",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate",
    "static": "NUXTJS_DEPLOY_TARGET=static NUXTJS_SSR=true nuxt generate",
    "build-and-start": "NUXTJS_DEPLOY_TARGET=server NUXTJS_SSR=false nuxt build && NUXTJS_DEPLOY_TARGET=server NUXTJS_SSR=false nuxt start"
  },
  "husky": {
    "hooks": {
      "pre-commit": "cross-env PRE_COMMIT=true lint-staged -r"
    }
  },
  "dependencies": {
    "core-js": "^3.19.3",
    "nuxt": "^2.15.8",
    "nuxt-i18n": "^6.28.1",
    "nuxt-purgecss": "^1.0.0",
    "vue": "^2.6.14",
    "vue-server-renderer": "^2.6.14",
    "vue-template-compiler": "^2.6.14",
    "webpack": "^4.46"
  },
  "devDependencies": {
    "@nuxtjs/eslint-config": "^8.0.0",
    "@nuxtjs/google-fonts": "^1.3.0",
    "@nuxtjs/storybook": "^4.2.0",
    "@nuxtjs/style-resources": "^1.2.1",
    "@vue/cli-plugin-babel": "^4.5.15",
    "babel-eslint": "^10.1.0",
    "eslint": "^8.7.0",
    "husky": "^7.0.4",
    "nuxt-svg-loader": "^1.2.0",
    "postcss": "^8.4.5"
  }
}

According to this I should install node-sass version 6.0

But I'm trying:
npm install --save-dev sass@1.49.0 node-sass@6.0.1 sass-loader@10.2.1

Also, read here to add --unsafe-perm so I tried:
npm install --save-dev --unsafe-perm sass@1.49.0 node-sass@6.0.1 sass-loader@10.2.1

But it keeps failing, being the first error always this one:

npm ERR! code 1
npm ERR! path /Users/toniweb/Proyectos/our-awesome-project/node_modules/node-sass
npm ERR! command failed
npm ERR! command sh -c node scripts/build.js
npm ERR! Building: /Users/user/.nvm/versions/node/v16.13.1/bin/node /Users/toniweb/Proyectos/our-awesome-project/node_modules/node-gyp/bin/node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=

I tried removing node_modules package-lock.json and the same result

Of course, this is driving me nuts.. please tell me that anyone has an idea to try out


问:
How to provide Arabic Language support in Android Application
I have made an application in android but now I have to provide arabic language support. I have checked many of answers in stackoverflow but from any answer I didn't get correct answer. </p>

答:
In AndroidManifest.xml:
SupportRtL
this will enable alignments of images and text to right in Arabic and left in English

Create two string resource layouts (one English, one Arabic)
string Resource

Add the same string with the same name in the two layouts but change the value of the arabic string in the (ar\strings.xml)

Same goes to each drawable item
(Also for reference I'll add how you can create a resource that ar or RL)
creating arabic resourse

Also either in the base activity to set the base local language

        app = (MyApplication)getApplicationContext();

      lang = Actions.setLocal(this);using the function:
function


问:
Accessing chart properties (like chart title) via epplus in asp.net
I am trying to get title of an existing chart that is already present in my excel worksheet. i don't have ms office installed on server. So i am using EPPlus library. I am able to add new chart in worksheet but i want to retrieve chart title of an existing chart . Is there any way i can get it via epplus ? </p>

<p>i have tried the following the code : </p>

```<code>                    string file = @"c:\test.xlsm";
                    FileInfo exlName = new FileInfo(file);
                    using (ExcelPackage package = new ExcelPackage(exlName))
                    {
                        var logSheet = package.Workbook.Worksheets.SingleOrDefault(x => x.Name == "DEMO CHARTS");  //this worksheet contains chart in it
                        if (logSheet != null)
                        {
                            var chart = logSheet.Drawings["Chart 1"] as ExcelChart;
                            var title = chart.Title;
                        }
                    }
</code>```

答:
enumerate through the drawings collection on your worksheet - make sure the object is an excelchart (not a picture for example) - then query the innerText (or innerXml) to find your title.

```<code>            foreach(var drawing in worksheet.Drawings)
            {
                if (drawing is ExcelChart)
                {
                    if (((ExcelChart)drawing).ChartXml.InnerText.Contains("YOUR GRAPH TITLE"))
                    {
            //-- convert and use here...
            var chart = drawing as ExcelBarChart;
                    }
                }
            }
</code>```

Note: The answer below isn't perfect, as if your chart title is in the innertext for the drawing object (e.g. your chart title is "!") - it won't work, and in that case you will need to use the InnerXML property instead and search it using XDom..

Body:
I am trying to get title of an existing chart that is already present in my excel worksheet. i don't have ms office installed on server. So i am using EPPlus library. I am able to add new chart in worksheet but i want to retrieve chart title of an existing chart . Is there any way i can get it via epplus ?

i have tried the following the code :

                    string file = @"c:\test.xlsm";
                    FileInfo exlName = new FileInfo(file);
                    using (ExcelPackage package = new ExcelPackage(exlName))
                    {
                        var logSheet = package.Workbook.Worksheets.SingleOrDefault(x => x.Name == "DEMO CHARTS");  //this worksheet contains chart in it
                        if (logSheet != null)
                        {
                            var chart = logSheet.Drawings["Chart 1"] as ExcelChart;
                            var title = chart.Title;
                        }
                    }

Body:
enumerate through the drawings collection on your worksheet - make sure the object is an excelchart (not a picture for example) - then query the innerText (or innerXml) to find your title.

            foreach(var drawing in worksheet.Drawings)
            {
                if (drawing is ExcelChart)
                {
                    if (((ExcelChart)drawing).ChartXml.InnerText.Contains("YOUR GRAPH TITLE"))
                    {
            //-- convert and use here...
            var chart = drawing as ExcelBarChart;
                    }
                }
            }

Note: The answer below isn't perfect, as if your chart title is in the innertext for the drawing object (e.g. your chart title is "!") - it won't work, and in that case you will need to use the InnerXML property instead and search it using XDom..


问:
Hide Row if groupname included fixed Text angular
I have a table which show all names from json. But Some name should be hidden, if they include groupnam4.
For example:
How can I hide row "name2" in HTML, if group.name = groupname4.

My Json looks like:

```<code>{
   name: "name1"
   groups:
         [
           { id: "1",
             name: "groupname1"},
           { id: "2",
             name: "groupname2"},
         ]
 },

{
    name: "name2"
    groups:
        [
         { id: "1",
           name: "groupname1"},
         { id: "2",
           name: "groupname4"},
        ]
}
</code>```

答:
```<code><tr *ngFor="let item of groups">
  <td *ngIf="item.name != 'groupname4' ">{{ item.name }}</td>
</tr>
</code>```

write an ngIf condition and render when the name groupname4

Body:
I have a table which show all names from json. But Some name should be hidden, if they include groupnam4.
For example:
How can I hide row "name2" in HTML, if group.name = groupname4.

My Json looks like:

{
   name: "name1"
   groups:
         [
           { id: "1",
             name: "groupname1"},
           { id: "2",
             name: "groupname2"},
         ]
 },

{
    name: "name2"
    groups:
        [
         { id: "1",
           name: "groupname1"},
         { id: "2",
           name: "groupname4"},
        ]
}

Body:
<tr *ngFor="let item of groups">
  <td *ngIf="item.name != 'groupname4' ">{{ item.name }}</td>
</tr>

write an ngIf condition and render when the name groupname4


问:
docker-compose: (Re)Build Dockerfile from inside docker-compose file?
Had a hard time googling this question as most suggestions is how to do it through command line which I sadly do not have access to in this environment. Is it possible to do the equivalent of

```<code>docker-compose up --build --force-recreate
</code>```

From inside a docker-compose file?

答:
The environment you describe sounds similar to Kubernetes in a couple of ways, except that it's driven by a Docker Compose YAML file.  The strategies that work for Kubernetes will work here too.  In Compose there's no way to put "actions" in a YAML file, or flag that a service always needs to be rebuilt or recreated.  It sounds like the only thing it's possible to do in your environment is run docker-compose up -d.

The trick that I'd use here is to change the image: for a container whenever you have a change you need to deploy.  That means the image tag needs to be something unique; it could be a date stamp or source control ID.

version: '3.8'
services:
  myapp:
    image: registry.example.com/myapp:20220209
```
<p>Now when you have a change to your application, you (or your CI system) need to build a new copy of it, offline, and <code>docker push</code> it to a registry.  Then change this <code>image:</code> value, and push the updated file to the deployment system.  Compose will see that it's only running version 20220208 from yesterday and recreate that specific container.</p>
<p>If you have the ability to specify environment variables, you can use that in the Compose setup</p>
<pre class="lang-yaml prettyprint-override"><code>    image: registry.example.com/myapp:${MYAPP_TAG:-latest}
</code>```

to avoid having to physically modify the file.

Body:
Had a hard time googling this question as most suggestions is how to do it through command line which I sadly do not have access to in this environment. Is it possible to do the equivalent of

docker-compose up --build --force-recreate

From inside a docker-compose file?

Body:
The environment you describe sounds similar to Kubernetes in a couple of ways, except that it's driven by a Docker Compose YAML file.  The strategies that work for Kubernetes will work here too.  In Compose there's no way to put "actions" in a YAML file, or flag that a service always needs to be rebuilt or recreated.  It sounds like the only thing it's possible to do in your environment is run docker-compose up -d.

The trick that I'd use here is to change the image: for a container whenever you have a change you need to deploy.  That means the image tag needs to be something unique; it could be a date stamp or source control ID.

version: '3.8'
services:
  myapp:
    image: registry.example.com/myapp:20220209

Now when you have a change to your application, you (or your CI system) need to build a new copy of it, offline, and docker push it to a registry.  Then change this image: value, and push the updated file to the deployment system.  Compose will see that it's only running version 20220208 from yesterday and recreate that specific container.

If you have the ability to specify environment variables, you can use that in the Compose setup

    image: registry.example.com/myapp:${MYAPP_TAG:-latest}

to avoid having to physically modify the file.


问:
Discord.js: on('interactionCreate') not working but 'messageCreate' does work
I'm currently working on the commands of the bot and I can't seem to find the solution to my problem. When I run my

```<code>client.on('messageCreate', async interaction =>{
  // somethingHappens
})
</code>```

It works perfectly, but when I do

```<code>client.on('interactionCreate', async interaction =>{
  // nothingHappens
})
</code>```

This are my client Intents:

```<code>[
  Discord.Intents.FLAGS.GUILDS,
  Discord.Intents.FLAGS.GUILD_MESSAGES,
  Discord.Intents.FLAGS.DIRECT_MESSAGES
]
</code>```

Am I missing something?

答:
Maybe try this intent for me it worked.</p>
```<code>Discord.Intents.FLAGS.GUILD_INTEGRATIONS
</code>```

Body:
I'm currently working on the commands of the bot and I can't seem to find the solution to my problem. When I run my

client.on('messageCreate', async interaction =>{
  // somethingHappens
})

It works perfectly, but when I do

client.on('interactionCreate', async interaction =>{
  // nothingHappens
})

This are my client Intents:

[
  Discord.Intents.FLAGS.GUILDS,
  Discord.Intents.FLAGS.GUILD_MESSAGES,
  Discord.Intents.FLAGS.DIRECT_MESSAGES
]

Am I missing something?

Body:
Maybe try this intent for me it worked.

Discord.Intents.FLAGS.GUILD_INTEGRATIONS


问:
Create an object that has a ForeignKey with another object
Assume that I have two models:

class Category(models.Model):
    title = models.CharField(max_length=255)

class Product(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    title = models.CharField(max_length=255)
```
<p>What I wanna accomplish is creating a <code>Product</code> object.</p>
<p>Assume I'll receive <code>category_id</code> from the <code>POST</code> request</p>
<pre class="lang-py prettyprint-override"><code>>>> category = Category.objects.get(id=category_id)

>>> Product.objects.create(category=category, title='Send the category object')

>>> Product.objects.create(category_id=category_id, title='Send only category id')
</code>```

As you can see, there are two options, the first is to send category instance to create() method and the second is to send category_id, so my question is which approach is better for performance?

I know that I need to check if that category exists in the DB or not but this is not the case that I'm talking about in the question.

答:
If you have the primary key (category_id) there is no need to fetch the category first, you thus can use:

```<code>Product.objects.create(<strong>category_id=category_id</strong>, title='Send only category id')</code>```

which will thus only make one query: a query to create the Product, and thus will avoid querying for the category.

The two .create(…)s will make exactly the same query since Django will simply retrieve the .id of the category object, and make the query with that id.

I know that I need to check if that category exists in the DB or not but this is not the case that I'm talking about in the question.

No, if one would make a request with a category_id for which there is no record for the table behind the Category model, it will raise an IntegrityError: the database will normally ensure that ForeignKeys always point to valid items, so the Category.objects.get(id=category_id) is not necessary: if you are only fetching it to fetch the category, you can omit that.

Body:
Assume that I have two models:

class Category(models.Model):
    title = models.CharField(max_length=255)

class Product(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    title = models.CharField(max_length=255)

What I wanna accomplish is creating a Product object.

Assume I'll receive category_id from the POST request

>>> category = Category.objects.get(id=category_id)

>>> Product.objects.create(category=category, title='Send the category object')

>>> Product.objects.create(category_id=category_id, title='Send only category id')

As you can see, there are two options, the first is to send category instance to create() method and the second is to send category_id, so my question is which approach is better for performance?

I know that I need to check if that category exists in the DB or not but this is not the case that I'm talking about in the question.

Body:
If you have the primary key (category_id) there is no need to fetch the category first, you thus can use:

Product.objects.create(category_id=category_id, title='Send only category id')

which will thus only make one query: a query to create the Product, and thus will avoid querying for the category.

The two .create(…)s will make exactly the same query since Django will simply retrieve the .id of the category object, and make the query with that id.

I know that I need to check if that category exists in the DB or not but this is not the case that I'm talking about in the question.

No, if one would make a request with a category_id for which there is no record for the table behind the Category model, it will raise an IntegrityError: the database will normally ensure that ForeignKeys always point to valid items, so the Category.objects.get(id=category_id) is not necessary: if you are only fetching it to fetch the category, you can omit that.


问:
how do add a custom scoring script in painless
this language is not painless at all...
zero examples and the docs are lacking...

I am trying to build a custom distance function between embeddings, I have done it in python:

```<code>def my_norm(x,y):
    norm_embeddings = [sum(a * a) ** 0.5 for a in x]
    norm_target = sum(y * y) ** 0.5
    z = y-x
    norm_top = [sum(a * a) ** 0.5 for a in z]
    return norm_top / (norm_embeddings+norm_target)
</code>```

where x is a N*m array and y is m vector

here is what I got in painless, don't even know if this will work...

```<code>def normalized_euclidean_dist(def x, def y){
  def norm_embeddings= new ArrayList();
  def norm_target = Math.pow((y*y).sum(), 0.5);
  def z = y-x;
  def norm_top=new ArrayList();
  for (a in x){
    norm_embeddings.add(Math.pow((a*a).sum(), 0.5))
  }
  for (a in z){
    norm_top.add(Math.pow((a*a).sum(), 0.5))
  }
  return norm_top/(norm_embeddings+norm_target)
}
</code>```

how do I call this fucntion on the script?

答:
its hard to debug it without actual docs/index mapping, but this is the general way to call script sorting

```<code>GET some_index/_search
{
  "query": {
    "match_all": {}
  },
  "sort": {
    "_script": {
      "type": "number",
      "script": {
        "lang": "painless",
        "source": """
        float normalized_euclidean_dist(def x, def y){
          def norm_embeddings= new ArrayList();
          def norm_target = Math.pow((y*y).sum(), 0.5);
          def z = y-x;
          def norm_top=new ArrayList();
          for (a in x){
            norm_embeddings.add(Math.pow((a*a).sum(), 0.5));
          }
          for (a in z){
            norm_top.add(Math.pow((a*a).sum(), 0.5));
          }
          return norm_top/(norm_embeddings+norm_target);
        }

        return normalized_euclidean_dist(doc['x_field'], doc['y_field']);
        """
      },
      "order": "asc"
    }
  }
}
</code>```

Replace 'x_field' and 'y_field' with the actual field names, as far as I understand both of them are arrays, but if not, you need to add doc['x_field'].value

Now sorting scripts need to return a number as result, but I may miss something in your script but looks to me like its trying to divide an array buy a number / another array, which wouldn't work so there is work to do there as well

script sorting docs: https://www.elastic.co/guide/en/elasticsearch/reference/current/sort-search-results.html#script-based-sorting

Body:
this language is not painless at all...
zero examples and the docs are lacking...

I am trying to build a custom distance function between embeddings, I have done it in python:

def my_norm(x,y):
    norm_embeddings = [sum(a * a) ** 0.5 for a in x]
    norm_target = sum(y * y) ** 0.5
    z = y-x
    norm_top = [sum(a * a) ** 0.5 for a in z]
    return norm_top / (norm_embeddings+norm_target)

where x is a N*m array and y is m vector

here is what I got in painless, don't even know if this will work...

def normalized_euclidean_dist(def x, def y){
  def norm_embeddings= new ArrayList();
  def norm_target = Math.pow((y*y).sum(), 0.5);
  def z = y-x;
  def norm_top=new ArrayList();
  for (a in x){
    norm_embeddings.add(Math.pow((a*a).sum(), 0.5))
  }
  for (a in z){
    norm_top.add(Math.pow((a*a).sum(), 0.5))
  }
  return norm_top/(norm_embeddings+norm_target)
}

how do I call this fucntion on the script?

Body:
its hard to debug it without actual docs/index mapping, but this is the general way to call script sorting

GET some_index/_search
{
  "query": {
    "match_all": {}
  },
  "sort": {
    "_script": {
      "type": "number",
      "script": {
        "lang": "painless",
        "source": """
        float normalized_euclidean_dist(def x, def y){
          def norm_embeddings= new ArrayList();
          def norm_target = Math.pow((y*y).sum(), 0.5);
          def z = y-x;
          def norm_top=new ArrayList();
          for (a in x){
            norm_embeddings.add(Math.pow((a*a).sum(), 0.5));
          }
          for (a in z){
            norm_top.add(Math.pow((a*a).sum(), 0.5));
          }
          return norm_top/(norm_embeddings+norm_target);
        }

        return normalized_euclidean_dist(doc['x_field'], doc['y_field']);
        """
      },
      "order": "asc"
    }
  }
}

Replace 'x_field' and 'y_field' with the actual field names, as far as I understand both of them are arrays, but if not, you need to add doc['x_field'].value

Now sorting scripts need to return a number as result, but I may miss something in your script but looks to me like its trying to divide an array buy a number / another array, which wouldn't work so there is work to do there as well

script sorting docs: https://www.elastic.co/guide/en/elasticsearch/reference/current/sort-search-results.html#script-based-sorting