问:
In scala shapeless library, is it possible to write a generic arity function when the arity > 22 (presumably using one of shapeless macros)?
The following code is a typical demo of one of shapeless' use case:

```<code>
  def getHList[P <: Product, F, L <: HList](p: P)(implicit gen: Generic.Aux[P, L]): L = {
    gen.to(p)
  }

    val v = getHList(1, 2, 3, 4, 5, 6, 7, 8, 9)
</code>```

This gives the proper result, unfortunately, it relies on scala's tuple syntactic suger, and doesn't work when the number of argument > 22:

```<code>
    val v = getHList(1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0)

(this generates an error that looks this the follow)

[Error] /xxx/HListSuite.scala:41: 29 more arguments than can be applied to method getHList: (p: P)(implicit gen: shapeless.Generic.Aux[P,L])L
one error found

FAILURE: Build failed with an exception.

</code>```

I wonder if there is a macro or another scala feature I can use to break this limitation, any advice?

I'm using scala 2.12.8 but can upgrade to 2.13 at any time.

答:
If your goal is to generate an HList longer than 22 then there are plenty of ways

```<code>type _23 = Succ[_22]
val _23: _23 = new _23

1 :: 2 :: 3 :: 4 :: 5 :: 6 :: 7 :: 8 :: 9 :: 10 :: 11 :: 12 :: 13 :: 14 :: 15 :: 16 :: 17 :: 18 :: 19 :: 20 :: 21 :: 22 :: 23 :: HNil
import shapeless.syntax.std.traversable._
import shapeless.ops.hlist.Fill
(1 to 23).toHList[the.`Fill[_23, Int]`.Out]
(1 to 23).toSizedHList(_23)
implicitly[_1 *--* _23].apply //takes long
</code>```

Be careful, some of these calculations take long.

Also you can define Product23, Tuple23

```<code>getHList(Tuple23(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23))
</code>```

although syntax sugar just with brackets will not work. The name of case class isn't significant, it can be MyClass instead of Tuple23.

In Dotty there is TupleXXL.

If your goal is to write a method like getHList you can try to make it curried

```<code>//libraryDependencies += "com.github.dmytromitin" %% "auxify-macros" % "0.6", scalacOptions += "-Ymacro-annotations" (in 2.13)
import com.github.dmytromitin.auxify.macros.{aux, instance}

def curriedGetHList[N <: Nat] = new PartiallyAppliedCurriedGetHList[N]

class PartiallyAppliedCurriedGetHList[N <: Nat] {
  def apply[A](a: A)(implicit cghl: CurriedGetHList[N, A]): cghl.Out = cghl(a)
}

@aux @instance
trait CurriedGetHList[N <: Nat, A] {
  type Out
  def apply(a: A): Out
}
object CurriedGetHList {
  implicit def mkCurriedGetHList[N <: Nat, A]
  (implicit
   helper: CurriedGetHListHelper[N, A, A :: HNil]
  ): Aux[N, A, helper.Out] = instance(a => helper(a :: HNil))
}

@aux @instance
trait CurriedGetHListHelper[N <: Nat, A, L <: HList] {
  type Out
  def apply(acc: L): Out
}
object CurriedGetHListHelper {
  implicit def one[A, L <: HList]
  (implicit reverse: Reverse[L]): Aux[_1, A, L, reverse.Out] = instance(acc => reverse(acc))

  implicit def succ[N <: Nat, A, L <: HList]
  (implicit helper: Lazy[CurriedGetHListHelper[N, A, A :: L]]): Aux[Succ[N], A, L, A => helper.value.Out] =
    instance(acc => a => helper.value(a :: acc))
}

curriedGetHList[_10](1).apply(2)(3)(4)(5)(6)(7)(8)(9)(10)
</code>```

or

```<code>def curriedGetHList[N <: Nat] = new HListBuilder[N, HNil](HNil)

class HListBuilder[N <: Nat, L <: HList](l: L) {
  def apply[A](a: A)(implicit bhl: BuildHList[N, L, A]): bhl.Out = bhl(l, a)
}

@aux @instance
trait BuildHList[N <: Nat, L <: HList, A] {
  type Out
  def apply(l: L, a: A): Out
}
trait LowPriorityBuildHList {
  implicit def succ[N <: Nat, L <: HList, A]: BuildHList.Aux[Succ[N], L, A, HListBuilder[N, A :: L]] =
    BuildHList.instance((l, a) => new HListBuilder(a :: l))
}
object BuildHList extends LowPriorityBuildHList {
  implicit def one[L <: HList, A](implicit reverse: Reverse[A :: L]): Aux[_1, L, A, reverse.Out] =
    instance((l, a) => (a :: l).reverse)
}

curriedGetHList[_23](1).apply(2).apply(3).apply(4).apply(5).apply(6).apply(7).apply(8).apply(9).apply(10)
  .apply(11).apply(12).apply(13).apply(14).apply(15).apply(16).apply(17).apply(18).apply(19).apply(20)
  .apply(21).apply(22).apply(23)
</code>```

Or you can divide long tuple into tuple of tuples and use deep Generic (1 2 3 4).

One more option is to write a whitebox macro

```<code>import scala.language.experimental.macros
import scala.reflect.macros.whitebox

def getHList(xs: Any*): HList = macro getHListImpl
def getHListImpl(c: whitebox.Context)(xs: c.Tree*): c.Tree = {
  import c.universe._
  xs.foldRight[Tree](q"_root_.shapeless.HNil: _root_.shapeless.HNil")((h, t) => q"_root_.shapeless.::($h, $t)")
}

getHList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23)
</code>```

Since the macro is whitebox its return type will be proper, Int :: Int :: ... :: HNil.

Maybe the easiest is to use shapeless.ProductArgs

```<code>def getHList = new ProductArgs {
  def applyProduct[L <: HList](l: L): L = l
}

getHList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23)
</code>```

Actually ProductArgs are implemented in Shapeless via scala.Dynamic and whitebox macro.

Body:
The following code is a typical demo of one of shapeless' use case:

  def getHList[P <: Product, F, L <: HList](p: P)(implicit gen: Generic.Aux[P, L]): L = {
    gen.to(p)
  }

    val v = getHList(1, 2, 3, 4, 5, 6, 7, 8, 9)

This gives the proper result, unfortunately, it relies on scala's tuple syntactic suger, and doesn't work when the number of argument > 22:

    val v = getHList(1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0)

(this generates an error that looks this the follow)

[Error] /xxx/HListSuite.scala:41: 29 more arguments than can be applied to method getHList: (p: P)(implicit gen: shapeless.Generic.Aux[P,L])L
one error found

FAILURE: Build failed with an exception.

I wonder if there is a macro or another scala feature I can use to break this limitation, any advice?

I'm using scala 2.12.8 but can upgrade to 2.13 at any time.

Body:
If your goal is to generate an HList longer than 22 then there are plenty of ways

type _23 = Succ[_22]
val _23: _23 = new _23

1 :: 2 :: 3 :: 4 :: 5 :: 6 :: 7 :: 8 :: 9 :: 10 :: 11 :: 12 :: 13 :: 14 :: 15 :: 16 :: 17 :: 18 :: 19 :: 20 :: 21 :: 22 :: 23 :: HNil
import shapeless.syntax.std.traversable._
import shapeless.ops.hlist.Fill
(1 to 23).toHList[the.`Fill[_23, Int]`.Out]
(1 to 23).toSizedHList(_23)
implicitly[_1 *--* _23].apply //takes long

Be careful, some of these calculations take long.

Also you can define Product23, Tuple23

getHList(Tuple23(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23))

although syntax sugar just with brackets will not work. The name of case class isn't significant, it can be MyClass instead of Tuple23.

In Dotty there is TupleXXL.

If your goal is to write a method like getHList you can try to make it curried

//libraryDependencies += "com.github.dmytromitin" %% "auxify-macros" % "0.6", scalacOptions += "-Ymacro-annotations" (in 2.13)
import com.github.dmytromitin.auxify.macros.{aux, instance}

def curriedGetHList[N <: Nat] = new PartiallyAppliedCurriedGetHList[N]

class PartiallyAppliedCurriedGetHList[N <: Nat] {
  def apply[A](a: A)(implicit cghl: CurriedGetHList[N, A]): cghl.Out = cghl(a)
}

@aux @instance
trait CurriedGetHList[N <: Nat, A] {
  type Out
  def apply(a: A): Out
}
object CurriedGetHList {
  implicit def mkCurriedGetHList[N <: Nat, A]
  (implicit
   helper: CurriedGetHListHelper[N, A, A :: HNil]
  ): Aux[N, A, helper.Out] = instance(a => helper(a :: HNil))
}

@aux @instance
trait CurriedGetHListHelper[N <: Nat, A, L <: HList] {
  type Out
  def apply(acc: L): Out
}
object CurriedGetHListHelper {
  implicit def one[A, L <: HList]
  (implicit reverse: Reverse[L]): Aux[_1, A, L, reverse.Out] = instance(acc => reverse(acc))

  implicit def succ[N <: Nat, A, L <: HList]
  (implicit helper: Lazy[CurriedGetHListHelper[N, A, A :: L]]): Aux[Succ[N], A, L, A => helper.value.Out] =
    instance(acc => a => helper.value(a :: acc))
}

curriedGetHList[_10](1).apply(2)(3)(4)(5)(6)(7)(8)(9)(10)

or

def curriedGetHList[N <: Nat] = new HListBuilder[N, HNil](HNil)

class HListBuilder[N <: Nat, L <: HList](l: L) {
  def apply[A](a: A)(implicit bhl: BuildHList[N, L, A]): bhl.Out = bhl(l, a)
}

@aux @instance
trait BuildHList[N <: Nat, L <: HList, A] {
  type Out
  def apply(l: L, a: A): Out
}
trait LowPriorityBuildHList {
  implicit def succ[N <: Nat, L <: HList, A]: BuildHList.Aux[Succ[N], L, A, HListBuilder[N, A :: L]] =
    BuildHList.instance((l, a) => new HListBuilder(a :: l))
}
object BuildHList extends LowPriorityBuildHList {
  implicit def one[L <: HList, A](implicit reverse: Reverse[A :: L]): Aux[_1, L, A, reverse.Out] =
    instance((l, a) => (a :: l).reverse)
}

curriedGetHList[_23](1).apply(2).apply(3).apply(4).apply(5).apply(6).apply(7).apply(8).apply(9).apply(10)
  .apply(11).apply(12).apply(13).apply(14).apply(15).apply(16).apply(17).apply(18).apply(19).apply(20)
  .apply(21).apply(22).apply(23)

Or you can divide long tuple into tuple of tuples and use deep Generic (1 2 3 4).

One more option is to write a whitebox macro

import scala.language.experimental.macros
import scala.reflect.macros.whitebox

def getHList(xs: Any*): HList = macro getHListImpl
def getHListImpl(c: whitebox.Context)(xs: c.Tree*): c.Tree = {
  import c.universe._
  xs.foldRight[Tree](q"_root_.shapeless.HNil: _root_.shapeless.HNil")((h, t) => q"_root_.shapeless.::($h, $t)")
}

getHList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23)

Since the macro is whitebox its return type will be proper, Int :: Int :: ... :: HNil.

Maybe the easiest is to use shapeless.ProductArgs

def getHList = new ProductArgs {
  def applyProduct[L <: HList](l: L): L = l
}

getHList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23)

Actually ProductArgs are implemented in Shapeless via scala.Dynamic and whitebox macro.


来源: stackexchange

问:
How to avoid double printed statements with an if statement in a while loop
I'm new to stackoverflow and wanted to know why my statement keeps on being repeated twice when i introduce an if statement in my while loop @ "if done, type "back"". Secondly, can someone tell me why the ArrayList keeps an empty String at index 0 when i only add one item to the ArrayList? Thanks!

Here is the code:

package com.codewithrichard;

import java.util.ArrayList;
import java.util.Scanner;

public class Main {

```<code>public static void main(String[] args) {
 Scanner input = new Scanner(System.in);

 //global variables
  boolean appIsStillOn = true;

 ArrayList <String> shoppingList = new ArrayList<>();

 System.out.println("Welcome to your mobile shopping list" + "\n" + "Your options are");
 System.out.println("1) add item to list");
 System.out.println("2) display list and amount of items in it");
 System.out.println("3) quit!");

 while (appIsStillOn) {
     System.out.println("Option (1-4): ");
     int option1 = input.nextInt();
     if (option1 == 1) {
         while (true) {
             System.out.println("item (if done, type \"back\"): ");
             String itemAdded = input.nextLine().toLowerCase();
             if (!itemAdded.equals("back")) {
                 shoppingList.add(itemAdded);
             } else {
                 break;
             }
         }
     }
     else if (option1 ==2){
         System.out.println(shoppingList);
         System.out.println("size of shopping list: "  + shoppingList.size());
     }
     else {
         System.out.println("Can't wait for you to come back!");
         appIsStillOn = false;
     }

 }

}
</code>```

}

答:
The Scanner#nextInt() method (and many other next...() methods) does not consume the newLine character from the Scanner buffer which is produced when the ENTER key is hit. The Scanner#nextLine() method will consume it if encountered after a Scanner#nextInt() method therefore giving the impression that the prompt for input was skipped over.

Also Consider this...

What is to happen if the User accidentally types in an alpha character instead of a menu choice digit? That's right, your application will crash due to a InputMismatchException.

You should always carry out some form of validation for User input and if that validation fails, allow the User to make a proper entry. This obviously promotes a more trouble free environment when using your application. Using your current model, here is an example of this:

```<code>java.util.Scanner input = new java.util.Scanner(System.in);

//global variables
boolean appIsStillOn = true;
ArrayList<String> shoppingList = new ArrayList<>();

System.out.println("Welcome to your mobile shopping list.");

while (appIsStillOn) {
    int option1 = 0;
    while (option1 < 1 || option1 > 3) {
        System.out.println();
        System.out.println("Your Shopping List options are:");
        System.out.println("  1) Add item to list.");
        System.out.println("  2) Display list and amount of items in it.");
        System.out.println("  3) Quit!");
        System.out.print("Choice (1-3): --> ");
        try{
            option1 = input.nextInt();
            if (option1 < 1 || option1 > 3) {
                throw new java.util.InputMismatchException();
            }
            /* Consume the enter key hit (newline char) in case
               a Scanner#nextLine() prompt is next so that it
               doesn't get consumed by that method.   */
            input.nextLine();
        }
        catch (java.util.InputMismatchException ex) {
            System.err.println("Invalid menu choice supplied! Try again...");
            /* Consume the enter key hit (newline char) in case
               a Scanner#nextLine() prompt is next so that it
               doesn't get consumed by that method. It is also
               required here in case an exception has bypassed
               the above 'input.nextLine()' call.*/
            input.nextLine(); // Consume the enter key hit (newline char)
        }
    }

    if (option1 == 1) {
        while (true) {
            System.out.println();
            System.out.println("Enter the item to add (when done, enter \"back\"): ");
            System.out.print("Item: --> ");
            String itemToAdd = input.nextLine();
            if (itemToAdd.trim().equals("")) {
                System.err.println("Invalid Item String! You must supply something!");
                continue;
            }
            else if (itemToAdd.equalsIgnoreCase("back")) {
                break;
            }
            shoppingList.add(itemToAdd);
        }
    }
    else if (option1 == 2) {
        System.out.println();
        System.out.println(shoppingList);
        System.out.println("Number of Items in shopping list: " + shoppingList.size());
    }
    else {
        System.out.println();
        System.out.println("Bye-Bye - Can't wait for you to come back!");
        appIsStillOn = false;
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new to stackoverflow and wanted to know why my statement keeps on being repeated twice when i introduce an if statement in my while loop @ "if done, type "back"". Secondly, can someone tell me why the ArrayList keeps an empty String at index 0 when i only add one item to the ArrayList? Thanks!

Here is the code:

package com.codewithrichard;

import java.util.ArrayList;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {
 Scanner input = new Scanner(System.in);

 //global variables
  boolean appIsStillOn = true;

 ArrayList <String> shoppingList = new ArrayList<>();

 System.out.println("Welcome to your mobile shopping list" + "\n" + "Your options are");
 System.out.println("1) add item to list");
 System.out.println("2) display list and amount of items in it");
 System.out.println("3) quit!");

 while (appIsStillOn) {
     System.out.println("Option (1-4): ");
     int option1 = input.nextInt();
     if (option1 == 1) {
         while (true) {
             System.out.println("item (if done, type \"back\"): ");
             String itemAdded = input.nextLine().toLowerCase();
             if (!itemAdded.equals("back")) {
                 shoppingList.add(itemAdded);
             } else {
                 break;
             }
         }
     }
     else if (option1 ==2){
         System.out.println(shoppingList);
         System.out.println("size of shopping list: "  + shoppingList.size());
     }
     else {
         System.out.println("Can't wait for you to come back!");
         appIsStillOn = false;
     }

 }

}

}

Body:
The Scanner#nextInt() method (and many other next...() methods) does not consume the newLine character from the Scanner buffer which is produced when the ENTER key is hit. The Scanner#nextLine() method will consume it if encountered after a Scanner#nextInt() method therefore giving the impression that the prompt for input was skipped over.

Also Consider this...

What is to happen if the User accidentally types in an alpha character instead of a menu choice digit? That's right, your application will crash due to a InputMismatchException.

You should always carry out some form of validation for User input and if that validation fails, allow the User to make a proper entry. This obviously promotes a more trouble free environment when using your application. Using your current model, here is an example of this:

java.util.Scanner input = new java.util.Scanner(System.in);

//global variables
boolean appIsStillOn = true;
ArrayList<String> shoppingList = new ArrayList<>();

System.out.println("Welcome to your mobile shopping list.");

while (appIsStillOn) {
    int option1 = 0;
    while (option1 < 1 || option1 > 3) {
        System.out.println();
        System.out.println("Your Shopping List options are:");
        System.out.println("  1) Add item to list.");
        System.out.println("  2) Display list and amount of items in it.");
        System.out.println("  3) Quit!");
        System.out.print("Choice (1-3): --> ");
        try{
            option1 = input.nextInt();
            if (option1 < 1 || option1 > 3) {
                throw new java.util.InputMismatchException();
            }
            /* Consume the enter key hit (newline char) in case
               a Scanner#nextLine() prompt is next so that it
               doesn't get consumed by that method.   */
            input.nextLine();
        }
        catch (java.util.InputMismatchException ex) {
            System.err.println("Invalid menu choice supplied! Try again...");
            /* Consume the enter key hit (newline char) in case
               a Scanner#nextLine() prompt is next so that it
               doesn't get consumed by that method. It is also
               required here in case an exception has bypassed
               the above 'input.nextLine()' call.*/
            input.nextLine(); // Consume the enter key hit (newline char)
        }
    }

    if (option1 == 1) {
        while (true) {
            System.out.println();
            System.out.println("Enter the item to add (when done, enter \"back\"): ");
            System.out.print("Item: --> ");
            String itemToAdd = input.nextLine();
            if (itemToAdd.trim().equals("")) {
                System.err.println("Invalid Item String! You must supply something!");
                continue;
            }
            else if (itemToAdd.equalsIgnoreCase("back")) {
                break;
            }
            shoppingList.add(itemToAdd);
        }
    }
    else if (option1 == 2) {
        System.out.println();
        System.out.println(shoppingList);
        System.out.println("Number of Items in shopping list: " + shoppingList.size());
    }
    else {
        System.out.println();
        System.out.println("Bye-Bye - Can't wait for you to come back!");
        appIsStillOn = false;
    }
}


问:
How can I find the current DNS server?
I'm using Delphi and need to get the current Windows DNS server IP address so I can do a lookup. What function should I call to find it? The only solution I have right now does an ipconfig/all to get it, which is horrible.</p>

答: See GetNetowrkParams method (Platform SDK: IP Helper)

ContentLicense: CC BY-SA 2.5

Title: How can I find the current DNS server?

LastEditorDisplayName: Nick Berardi

OwnerDisplayName: Mladen Jankovic


问:
Could a truly random number be generated using pings to pseudo-randomly selected IP addresses?
The question posed came about during a 2nd Year Comp Science lecture while discussing the impossibility of generating numbers in a deterministic computational device.

This was the only suggestion which didn't depend on non-commodity-class hardware.

Subsequently nobody would put their reputation on the line to argue definitively for or against it.

Anyone care to make a stand for or against.  If so, how about a mention as to a possible implementation?

答:
Randomness is not a binary property -- it's a value between 0 and 1 that describes how difficult it is to predict the next value in a stream.

Asking "how random can my values be if I base them on pings?" is actually asking "how random are pings?". You can estimate that by gathering a large enough set of data (1 mln pings for example) and mapping their distribution curve and behavior in time. If the distribution is flat and the behavior is difficult to predict, the data seems more random. The more bumpy distribution or predictable behavior suggest lower randomness.

You should also consider the sample resolution. I could imagine the results being rounded in some way to a milisecond, so with pings you could have integer values between 0 and 500. That's not a lot of resolution.

On the practical side, I would recommend against it, since pings can be predicted and manipulated, further reducing their randomness.

Generally, I suggest against "rolling your own" randomness generators, encryption methods and hashing algorithms. As fun as it seems, it's mostly a lot of very intimidating math.

As to how to build a really good entropy generator -- I think that's probably going to have to be a sealed box that outputs some sort of result of interactions on atomic or sub-atomic level. I mean, if you're using a source of entropy that the enemy can easily read too, he only needs to find out your algorythm. Any form of connection is a possible attack vector, so you should place the source of entropy as close to the service that consumes it as possible.

OwnerDisplayName: Ande Turner

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: nemo

OwnerDisplayName: Pies

LastEditorDisplayName: Pies


问:
How to subtract two identical dataframes in pandas
I have got two identical dataframes in pandas/python (a and b) only values are different:

a:

```<code>date       a1 a2 a3
01.01.2020 2  2  2
02.01.2020 3  3  3
03.01.2020 4  4  4
</code>```

b:

```<code>date       a1 a2 a3
01.01.2020 1  1  1
01.01.2020 2  2  2
01.01.2020 3  3  3
</code>```

I need a - b and expect to see result c:

```<code>date       a1 a2 a3
01.01.2020 1  1  1
01.01.2020 1  1  1
01.01.2020 1  1  1
</code>```

a - b does not work and I cannot figure out how. Would you please help me? Thanks!

答:
You can set_index:

```<code>new_df = (a.set_index('date') - b.set_index('date')).reset_index()
</code>```

However, that only works if your dates are identical between the two dataframes and different within each.

In the other case (as shown in your sample data) you can do:

```<code>c = b.copy()
c.iloc[:,1:] = a.iloc[:, 1:] - b.iloc[:,1:]
</code>```

Body:
I have got two identical dataframes in pandas/python (a and b) only values are different:

a:

date       a1 a2 a3
01.01.2020 2  2  2
02.01.2020 3  3  3
03.01.2020 4  4  4

b:

date       a1 a2 a3
01.01.2020 1  1  1
01.01.2020 2  2  2
01.01.2020 3  3  3

I need a - b and expect to see result c:

date       a1 a2 a3
01.01.2020 1  1  1
01.01.2020 1  1  1
01.01.2020 1  1  1

a - b does not work and I cannot figure out how. Would you please help me? Thanks!

Body:
You can set_index:

new_df = (a.set_index('date') - b.set_index('date')).reset_index()

However, that only works if your dates are identical between the two dataframes and different within each.

In the other case (as shown in your sample data) you can do:

c = b.copy()
c.iloc[:,1:] = a.iloc[:, 1:] - b.iloc[:,1:]


问:
EF Core - Include related entities using a generic method
previously, back in EF Frameowrk days, the following method sufficed when needing the related entities to an entity.

```<code>private IQueryable<T> EntitySet(params Expression<Func<T, object>>[] includes)
    {
        var set = Context.Set<T>().Where(x => !x.IsDeleted);
        if (includes != null)
        {
            foreach (var include in includes)
            {
                set = set.Include(include);
            }
        }
        return set;
    }
</code>```

I'd call this method with something like EntitySet(x => x.People, x => x.People.Meetings). However, ever since moving to EF core, I can no longer get the related data because I need to explicitly use Include(x.People).ThenInclude(p.Meegings).

Is what I'm trying to do even possible in EF core? Or were there so many changes in gather related data so that the above method is no longer applicable?

答:
It almost seems like you are attempting to add a filter to many queries of the same DbSet. Have you looked at Query Filters before in EF Core? It seems very similar to what you are trying to do. If you need to have a query should get all records instead of just active records, there is an option to ignore query filters at a by query basis.

https://learn.microsoft.com/en-us/ef/core/querying/filters

Edit:
If you are looking to dynamically specify your includes still. You can do so with Strings in EF Core the same as was done in EF. However, the ability to use a lambda to access child objects may have gotten lost in conversion. https://entityframeworkcore.com/knowledge-base/38083198/add-include-expressions-dynamically

Body:
previously, back in EF Frameowrk days, the following method sufficed when needing the related entities to an entity.

private IQueryable<T> EntitySet(params Expression<Func<T, object>>[] includes)
    {
        var set = Context.Set<T>().Where(x => !x.IsDeleted);
        if (includes != null)
        {
            foreach (var include in includes)
            {
                set = set.Include(include);
            }
        }
        return set;
    }

I'd call this method with something like EntitySet(x => x.People, x => x.People.Meetings). However, ever since moving to EF core, I can no longer get the related data because I need to explicitly use Include(x.People).ThenInclude(p.Meegings).

Is what I'm trying to do even possible in EF core? Or were there so many changes in gather related data so that the above method is no longer applicable?


问:
SQL SELECT with bad data
If a column has bad data such as:

```<code> 45612345698
 (456)123-7452
 125-145-9856
</code>```

Without fixing the data. Is it possible to have a sql query of 1251459856 which then would return the 3rd item in the column?

答:
If your data is worse than just "-",")" and "(" you could go for a more generic solution and strip on any non-numeric character with the following</p>

```<code>WITH sample_data_tab (str) AS
(
SELECT '45612345698' FROM DUAL UNION
SELECT '(456)123-7452' FROM DUAL UNION
SELECT '125-145-9856' FROM DUAL UNION
SELECT '989 145 9856' FROM DUAL
)
SELECT regexp_replace(str, '[^0-9]', '') FROM sample_data_tab
</code>```

Title: SQL SELECT with bad data

Body:
If a column has bad data such as:

 45612345698
 (456)123-7452
 125-145-9856

Without fixing the data. Is it possible to have a sql query of 1251459856 which then would return the 3rd item in the column?

Body:
If your data is worse than just "-",")" and "(" you could go for a more generic solution and strip on any non-numeric character with the following

WITH sample_data_tab (str) AS
(
SELECT '45612345698' FROM DUAL UNION
SELECT '(456)123-7452' FROM DUAL UNION
SELECT '125-145-9856' FROM DUAL UNION
SELECT '989 145 9856' FROM DUAL
)
SELECT regexp_replace(str, '[^0-9]', '') FROM sample_data_tab


问:
Secure and authorize GET request request from nginx/nchan to auth server
I am new to Nginx and nchan.
I have a typical use-case of pub-sub model based on Nginx/nchan where there are multiple subscribers and a single publisher. Subscribers subscribe to Nchan server via a websocket wss API call.
I want to allow only authorized nodes to be allowed to subscribe to Nchan. I know that there is proxy_pass in Nginx where I can rely on an external auth server to send 2xx to authorize a request, but there is a problem:

The GET request itself from Nginx/nchan to my auth server needs to be authenticated/authorized so that not everyone is allowed to call the auth request. Or take it like this: I cannot expose an open API on my auth server because of security concerns.

The subscribe requests can have an Auth token, which can be validated by auth server. Is there a way in Nginx by which I can parse the request received as subscribe request and pass it to auth server?

答:
You can use a lua script and use something like this

```<code>location ~ "^/subscribe" {
    access_by_lua_block {
      //check headers/cookie for authorization token
      //validate token
    }

    nchan_subscriber;
}
</code>```

To rely on an external authorization service. You can use lua to proxy the request

```<code>location ~ "^/sub" {
    access_by_lua_block {
      local res = ngx.location.capture(location, options)
      if res.status == ngx.HTTP_OK then
        return
      end

      if res.status == ngx.HTTP_UNAUTHORIZED then
          ngx.exit(ngx.HTTP_UNAUTHORIZED)
          return
      end
    }

    nchan_subscriber;
}
</code>```

Body:
You can use a lua script and use something like this

location ~ "^/subscribe" {
    access_by_lua_block {
      //check headers/cookie for authorization token
      //validate token
    }

    nchan_subscriber;
}

To rely on an external authorization service. You can use lua to proxy the request

location ~ "^/sub" {
    access_by_lua_block {
      local res = ngx.location.capture(location, options)
      if res.status == ngx.HTTP_OK then
        return
      end

      if res.status == ngx.HTTP_UNAUTHORIZED then
          ngx.exit(ngx.HTTP_UNAUTHORIZED)
          return
      end
    }

    nchan_subscriber;
}


问:
Xampp Access violation at address 005ABEFFE
I have an issue with my XAMPP Control Pannel.

Each time I run my XAMPP Control Pannel, it shuts down, with these errors :

This is what the application error window show me :

```<code>  Exception EAccessViolation in module xampp-control.exe at 001ABEFFE.
  Access violation at address 005ABEFFE in module 'xampp-controle.exe'.
  Read of address 00000042.
</code>```

And this is the details of the crash :

```<code>  Problem signature:
  Problem Event Name:   APPCRASH
  Application Name: xampp-control.exe
  Application Version:  3.1.0.0
  Application Timestamp:    505b977e
  Fault Module Name:    xampp-control.exe
  Fault Module Version: 3.1.0.0
  Fault Module Timestamp:   505b977e
  Exception Code:   c0000005
  Exception Offset: 001abefe
  OS Version:   6.3.9600.2.0.0.272.7
  Locale ID:    1036
  Additional Information 1: 85f1
  Additional Information 2: 85f130a438e7576b1a9e31c22e4b9f42
  Additional Information 3: 5349
  Additional Information 4: 53499a809c3ee8ed8ef93e12b24b146b

  Read our privacy statement online:
  http://go.microsoft.com/fwlink/?linkid=280262

  If the online privacy statement is not available, please read our privacy statement offline:
  C:\Windows\system32\en-US\erofflps.txt
</code>```

Can you explain me how to fix it please ?

答:
First, your user must have administrator permission.

Second, install Xampp outside of "program files", preferably install in C:\xampp (It usually comes with this by default).

Third, after installation (Before running Xampp), go to the C:\xampp directory, look for xampp-control.exe, right click on it, go to "properties" go to the "compatibility" tab and then check the "run as administrator" option.

Body:
I have an issue with my XAMPP Control Pannel.

Each time I run my XAMPP Control Pannel, it shuts down, with these errors :

This is what the application error window show me :

  Exception EAccessViolation in module xampp-control.exe at 001ABEFFE.
  Access violation at address 005ABEFFE in module 'xampp-controle.exe'.
  Read of address 00000042.

And this is the details of the crash :

  Problem signature:
  Problem Event Name:   APPCRASH
  Application Name: xampp-control.exe
  Application Version:  3.1.0.0
  Application Timestamp:    505b977e
  Fault Module Name:    xampp-control.exe
  Fault Module Version: 3.1.0.0
  Fault Module Timestamp:   505b977e
  Exception Code:   c0000005
  Exception Offset: 001abefe
  OS Version:   6.3.9600.2.0.0.272.7
  Locale ID:    1036
  Additional Information 1: 85f1
  Additional Information 2: 85f130a438e7576b1a9e31c22e4b9f42
  Additional Information 3: 5349
  Additional Information 4: 53499a809c3ee8ed8ef93e12b24b146b

  Read our privacy statement online:
  http://go.microsoft.com/fwlink/?linkid=280262

  If the online privacy statement is not available, please read our privacy statement offline:
  C:\Windows\system32\en-US\erofflps.txt

Can you explain me how to fix it please ?


问:
How to read the WsdlService typeprovider into a local F# class and present as a non-blocking Task for C#
I am (extremely) new to F#. I am attempting to download information from a local database to a client application.

On the client side, I am  using the WsdlService typeprovider to access the WCF functions. How is the downloaded class read into a client side F# type?

```<code>type Wsdl1 = WsdlService<"http://iiii:xxxx/ServiceHost.svc">   // works correctly.

// My New type -- C# compatible.
type MyVisit = {
        lastname : string
        firstname : string
        birthdate : DateTime
        appointment_time : DateTime
        service_time : DateTime
        posting_time : DateTime
        chart_number : int
    }
</code>```

The below works correctly, but returns the visit type as a WSDL type. How do I convert the WSDL type returned by the context to the C# compatible type "Visit" above? The WSDL type has the same field names as "Visit".

```<code>let GetScheduleAsync (tableDate : DateTime) =
    async {
        return! context.GetOfficeScheduleAsync(tableDate) |> Async.AwaitTask
    }
    |> Async.StartAsTask
</code>```

I'm thinking some form of " |> Seq.map" is needed, but I can't seem to get it right. The goal here is to provide a non-blocking service available as a Task to the C# code.

Any help is most appreciated.

Update:
This seems to work, is it correct?

```<code>let GetScheduleAsync (tableDate : DateTime) =
async {
let! data = context.GetOfficeScheduleAsync(tableDate) |> Async.AwaitTask
                                return data |> Seq.map(fun q -> {
                                    MyVisit.lastname = q.lastname
                                    firstname = q.firstname
                                    birthdate = q.birthdate
                                    appointment_time = q.appointment_time
                                    service_time = q.service_time
                                    posting_time = q.posting_time
                                    chart_number = q.chart_number
                                    })
                            }
      |> Async.StartAsTask
</code>```

答:
As an answer to my question,

This seems to work correctly:

```<code>let GetScheduleAsync (tableDate : DateTime) =
async {
    let! data = context.GetOfficeScheduleAsync(tableDate) |> Async.AwaitTask
    return data |> Seq.map(fun q -> {
        MyVisit.lastname = q.lastname
        firstname = q.firstname
        birthdate = q.birthdate
        appointment_time = q.appointment_time
        service_time = q.service_time
        posting_time = q.posting_time
        chart_number = q.chart_number
        })
        }
      |> Async.StartAsTask
</code>```

Thanks to all who helped. I believe it is correct.

Body:
I am (extremely) new to F#. I am attempting to download information from a local database to a client application.

On the client side, I am  using the WsdlService typeprovider to access the WCF functions. How is the downloaded class read into a client side F# type?

type Wsdl1 = WsdlService<"http://iiii:xxxx/ServiceHost.svc">   // works correctly.

// My New type -- C# compatible.
type MyVisit = {
        lastname : string
        firstname : string
        birthdate : DateTime
        appointment_time : DateTime
        service_time : DateTime
        posting_time : DateTime
        chart_number : int
    }

The below works correctly, but returns the visit type as a WSDL type. How do I convert the WSDL type returned by the context to the C# compatible type "Visit" above? The WSDL type has the same field names as "Visit".

let GetScheduleAsync (tableDate : DateTime) =
    async {
        return! context.GetOfficeScheduleAsync(tableDate) |> Async.AwaitTask
    }
    |> Async.StartAsTask

I'm thinking some form of " |> Seq.map" is needed, but I can't seem to get it right. The goal here is to provide a non-blocking service available as a Task to the C# code.

Any help is most appreciated.

Update:
This seems to work, is it correct?

let GetScheduleAsync (tableDate : DateTime) =
async {
let! data = context.GetOfficeScheduleAsync(tableDate) |> Async.AwaitTask
                                return data |> Seq.map(fun q -> {
                                    MyVisit.lastname = q.lastname
                                    firstname = q.firstname
                                    birthdate = q.birthdate
                                    appointment_time = q.appointment_time
                                    service_time = q.service_time
                                    posting_time = q.posting_time
                                    chart_number = q.chart_number
                                    })
                            }
      |> Async.StartAsTask

Body:
As an answer to my question,

This seems to work correctly:

let GetScheduleAsync (tableDate : DateTime) =
async {
    let! data = context.GetOfficeScheduleAsync(tableDate) |> Async.AwaitTask
    return data |> Seq.map(fun q -> {
        MyVisit.lastname = q.lastname
        firstname = q.firstname
        birthdate = q.birthdate
        appointment_time = q.appointment_time
        service_time = q.service_time
        posting_time = q.posting_time
        chart_number = q.chart_number
        })
        }
      |> Async.StartAsTask

Thanks to all who helped. I believe it is correct.


问:
Calculate distance between two latitude-longitude points? (Haversine formula)
How do I calculate the distance between two points specified by latitude and longitude?

For clarification, I'd like the distance in kilometers; the points use the WGS84 system and I'd like to understand the relative accuracies of the approaches available.

答:
The functions needed for an accurate calculation of distance between lat-long points are complex, and the pitfalls are many. I would not recomend haversine or other spherical solutions due to the big inaccuracies (the earth is not a perfect sphere). The vincenty formula is better, but will in some cases throw errors, even when coded correctly.

Instead of coding the functions yourself I suggest using geopy which have implemented the very accurate geographiclib for distance calculations (paper from author).

```<code>#pip install geopy
from geopy.distance import geodesic
NY = [40.71278,-74.00594]
Beijing = [39.90421,116.40739]
print("WGS84: ",geodesic(NY, Beijing).km) #WGS84 is Standard
print("Intl24: ",geodesic(NY, Beijing, ellipsoid='Intl 1924').km) #geopy includes different ellipsoids
print("Custom ellipsoid: ",geodesic(NY, Beijing, ellipsoid=(6377., 6356., 1 / 297.)).km) #custom ellipsoid

#supported ellipsoids:
#model             major (km)   minor (km)     flattening
#'WGS-84':        (6378.137,    6356.7523142,  1 / 298.257223563)
#'GRS-80':        (6378.137,    6356.7523141,  1 / 298.257222101)
#'Airy (1830)':   (6377.563396, 6356.256909,   1 / 299.3249646)
#'Intl 1924':     (6378.388,    6356.911946,   1 / 297.0)
#'Clarke (1880)': (6378.249145, 6356.51486955, 1 / 293.465)
#'GRS-67':        (6378.1600,   6356.774719,   1 / 298.25)
</code>```

The only drawback with this library is that it doesn't support vectorized calculations.
For vectorized calculations you can use the new geovectorslib.

```<code>#pip install geovectorslib
from geovectorslib import inverse
print(inverse(lats1,lons1,lats2,lons2)['s12'])
</code>```

lats and lons are numpy arrays. Geovectorslib is very accurate and extremly fast! I haven't found a solution for changing ellipsoids though. The WGS84 ellipsoid is used as standard, which is the best choice for most uses.

OwnerDisplayName: Robin M

Body:
The functions needed for an accurate calculation of distance between lat-long points are complex, and the pitfalls are many. I would not recomend haversine or other spherical solutions due to the big inaccuracies (the earth is not a perfect sphere). The vincenty formula is better, but will in some cases throw errors, even when coded correctly.

Instead of coding the functions yourself I suggest using geopy which have implemented the very accurate geographiclib for distance calculations (paper from author).

#pip install geopy
from geopy.distance import geodesic
NY = [40.71278,-74.00594]
Beijing = [39.90421,116.40739]
print("WGS84: ",geodesic(NY, Beijing).km) #WGS84 is Standard
print("Intl24: ",geodesic(NY, Beijing, ellipsoid='Intl 1924').km) #geopy includes different ellipsoids
print("Custom ellipsoid: ",geodesic(NY, Beijing, ellipsoid=(6377., 6356., 1 / 297.)).km) #custom ellipsoid

#supported ellipsoids:
#model             major (km)   minor (km)     flattening
#'WGS-84':        (6378.137,    6356.7523142,  1 / 298.257223563)
#'GRS-80':        (6378.137,    6356.7523141,  1 / 298.257222101)
#'Airy (1830)':   (6377.563396, 6356.256909,   1 / 299.3249646)
#'Intl 1924':     (6378.388,    6356.911946,   1 / 297.0)
#'Clarke (1880)': (6378.249145, 6356.51486955, 1 / 293.465)
#'GRS-67':        (6378.1600,   6356.774719,   1 / 298.25)

The only drawback with this library is that it doesn't support vectorized calculations.
For vectorized calculations you can use the new geovectorslib.

#pip install geovectorslib
from geovectorslib import inverse
print(inverse(lats1,lons1,lats2,lons2)['s12'])

lats and lons are numpy arrays. Geovectorslib is very accurate and extremly fast! I haven't found a solution for changing ellipsoids though. The WGS84 ellipsoid is used as standard, which is the best choice for most uses.


问:
How to use `gcloud config` to build an image based on `gcr.io/google.com/cloudsdktool/cloud-sdk`
I am trying to build an image based on gcr.io/google.com/cloudsdktool/cloud-sdk:alpine, with some configuration I already know on build time. After some testing with gcloud config set on my local system, I transposed these commands into my Dockerfile. Although the sequence of commands yields the expected final gcloud configuration on my computer, the behaviour I found on the docker image was different and no change was persisted after the RUN commands.

I didn't expect this behaviour. What should explain this?

I used the following Dockerfile to assess the issue during troubleshoot:

```<code>FROM gcr.io/google.com/cloudsdktool/cloud-sdk:alpine AS runner
  RUN ["gcloud", "config", "list"]
  RUN ["gcloud", "config", "set", "compute/region", "europe-west1"]
  RUN ["gcloud", "config", "list"]
  ENTRYPOINT [ "bash" ]
</code>```

One can see that step 2/5 and step 4/5 yield the same output, even though the step 3/4 should change the current gcloud configuration for compute/region.

$ docker build --no-cache .
Sending build context to Docker daemon  2.048kB
Step 1/5 : FROM gcr.io/google.com/cloudsdktool/cloud-sdk:alpine AS runner
 ---> e3ce7ea1a190
Step 2/5 : RUN ["gcloud", "config", "list"]
 ---> Running in b8fb806b04aa
[component_manager]
disable_update_check = true
[core]
disable_usage_reporting = true
[metrics]
environment = github_docker_image

Your active configuration is: [default]
Removing intermediate container b8fb806b04aa
 ---> bc8321e71e60
Step 3/5 : RUN ["gcloud", "config", "set", "compute/region", "europe-west1"]
 ---> Running in cfbcb80b1a31
Updated property [compute/region].
Removing intermediate container cfbcb80b1a31
 ---> db76ee7c5e60
Step 4/5 : RUN ["gcloud", "config", "list"]
 ---> Running in d90c64fcf0b0
[component_manager]
disable_update_check = true
[core]
disable_usage_reporting = true
[metrics]
environment = github_docker_image

Your active configuration is: [default]
Removing intermediate container d90c64fcf0b0
 ---> a593aa61055e
Step 5/5 : ENTRYPOINT [ "bash" ]
 ---> Running in acb4d360754c
Removing intermediate container acb4d360754c
 ---> edab55257026
Successfully built edab55257026
```

cloud-builders
https://github.com/GoogleCloudPlatform/cloud-builders/tree/master/gcloud

答:
gcloud config is persisted in /root/.config/gcloud/configurations/config_default

BUT /root/.config and /root/.kube are VOLUMEs and can't be changed:

```<code>VOLUME ["/root/.config", "/root/.kube"]
</code>```

https://github.com/GoogleCloudPlatform/cloud-sdk-docker/blob/8764ec3c23860b35e9a7883c74ca2b4a6b45d866/Dockerfile#L42

"If any build steps change the data within the volume after it has been declared, those changes will be discarded."

see: https://docs.docker.com/engine/reference/builder/#volume

Body:
I am trying to build an image based on gcr.io/google.com/cloudsdktool/cloud-sdk:alpine, with some configuration I already know on build time. After some testing with gcloud config set on my local system, I transposed these commands into my Dockerfile. Although the sequence of commands yields the expected final gcloud configuration on my computer, the behaviour I found on the docker image was different and no change was persisted after the RUN commands.

I didn't expect this behaviour. What should explain this?

I used the following Dockerfile to assess the issue during troubleshoot:

FROM gcr.io/google.com/cloudsdktool/cloud-sdk:alpine AS runner
  RUN ["gcloud", "config", "list"]
  RUN ["gcloud", "config", "set", "compute/region", "europe-west1"]
  RUN ["gcloud", "config", "list"]
  ENTRYPOINT [ "bash" ]

One can see that step 2/5 and step 4/5 yield the same output, even though the step 3/4 should change the current gcloud configuration for compute/region.

$ docker build --no-cache .
Sending build context to Docker daemon  2.048kB
Step 1/5 : FROM gcr.io/google.com/cloudsdktool/cloud-sdk:alpine AS runner
 ---> e3ce7ea1a190
Step 2/5 : RUN ["gcloud", "config", "list"]
 ---> Running in b8fb806b04aa
[component_manager]
disable_update_check = true
[core]
disable_usage_reporting = true
[metrics]
environment = github_docker_image

Your active configuration is: [default]
Removing intermediate container b8fb806b04aa
 ---> bc8321e71e60
Step 3/5 : RUN ["gcloud", "config", "set", "compute/region", "europe-west1"]
 ---> Running in cfbcb80b1a31
Updated property [compute/region].
Removing intermediate container cfbcb80b1a31
 ---> db76ee7c5e60
Step 4/5 : RUN ["gcloud", "config", "list"]
 ---> Running in d90c64fcf0b0
[component_manager]
disable_update_check = true
[core]
disable_usage_reporting = true
[metrics]
environment = github_docker_image

Your active configuration is: [default]
Removing intermediate container d90c64fcf0b0
 ---> a593aa61055e
Step 5/5 : ENTRYPOINT [ "bash" ]
 ---> Running in acb4d360754c
Removing intermediate container acb4d360754c
 ---> edab55257026
Successfully built edab55257026

cloud-builders
https://github.com/GoogleCloudPlatform/cloud-builders/tree/master/gcloud

Body:
gcloud config is persisted in /root/.config/gcloud/configurations/config_default

BUT /root/.config and /root/.kube are VOLUMEs and can't be changed:

VOLUME ["/root/.config", "/root/.kube"]

https://github.com/GoogleCloudPlatform/cloud-sdk-docker/blob/8764ec3c23860b35e9a7883c74ca2b4a6b45d866/Dockerfile#L42

"If any build steps change the data within the volume after it has been declared, those changes will be discarded."

see: https://docs.docker.com/engine/reference/builder/#volume


问:
What is the airflow in sequential_executor logs
I am new to apache airflow and would like to ask simple question related to scheduler. When I am trying to run my DAG I am getting error as -
Persmission Error [13]: Permission Denied 'airflow'

When I check the above loggs, sequential_executor printed INFO message as
sequential_executer.py 45  INFO Executing Command: ['airflow', 'run', 'test','report_list' .... ]

Could you please let me know why I am getting this error?

答: I have added airflow library path and its resolved</p>


问:
How to verify user token before the dom is loaded?
I want to verify the user token (that stored in local storage) before the DOM is loaded, so the user will see immediately the correct DOM. window.onload and document.onreadystatechange triggers too late for that.
(this is a react app)

what is the appropriate event?

thanks!

答:
You could add a script tag in the head

  The body gets parsed

```

Body:
You could add a script tag in the head

<head>
  <!-- meta, css, ... -->

  <script>
    //This gets executed before
  </script>
</head>

<body>
  The body gets parsed
</body>


答:
Create a state variable canShow initially set to false, now in the useEffect callback function verify the token and according to the verification toggle canShow.
And in the return function render the dom only if canShow is true. </p>

<p>P.S. You can do the same using class based component but react encourages developers to use functional components as much as possible. </p>

Title: How to verify user token before the dom is loaded?

Body:
I want to verify the user token (that stored in local storage) before the DOM is loaded, so the user will see immediately the correct DOM. window.onload and document.onreadystatechange triggers too late for that.
(this is a react app)

what is the appropriate event?

thanks!

Body:
Create a state variable canShow initially set to false, now in the useEffect callback function verify the token and according to the verification toggle canShow.
And in the return function render the dom only if canShow is true.

P.S. You can do the same using class based component but react encourages developers to use functional components as much as possible.


问:
How to split select query rows based on the comma separated values in the columns in oracle plsql
I wrote 2 queries Union. i'm getting results as comma separted in two of the columns. And the output is displayed as 2 records.

How to split them into 4 records as below expected results?

```<code>select emp_id,dept_name,location from department where dept_id = 1
union
select emp_id,dept_name,location from sales_dept where dept_id = 1;
</code>```

Output:

```<code>emp_id ----- dept_name------  location

r1-----------Retail,IT-----   US, UK
k2-----------Sales,Chemical-  NZ, SA
j3-----------Biotech(Chemistry,Tech)-   JA
</code>```

I need the expected output as  below:

```<code>emp_id ----- dept_name-----location
r1-----------Retail--------US
r1-----------IT----------- UK
k2-----------Sales---------NZ
k2-----------Chemical------SA
j3---------Biotech(Chemistry,Tech)--JA
</code>```

The last record of whereever dept_name is "Biotech(Chemistry,Tech)" should be displayed as single record and not to be split. Please let me know how to do it.

The query given by Jim is working fine except in this scenario when dept_name is Biotech(Chemistry,Tech) as the requirement is given now.

答:
Please use below query,</p>

```<code>select emp_id, dept_name, location from
(select distinct emp_id, trim(regexp_substr(dept_name,'[^,]+', 1, level) ) dept_name,
trim(regexp_substr(location,'[^,]+', 1, level) ) location, level
from pivot_comma
connect by regexp_substr(dept_name, '[^,]+', 1, level) is not null
order by emp_id, level);
</code>```

Body:
I wrote 2 queries Union. i'm getting results as comma separted in two of the columns. And the output is displayed as 2 records.

How to split them into 4 records as below expected results?

select emp_id,dept_name,location from department where dept_id = 1
union
select emp_id,dept_name,location from sales_dept where dept_id = 1;

Output:

emp_id ----- dept_name------  location

r1-----------Retail,IT-----   US, UK
k2-----------Sales,Chemical-  NZ, SA
j3-----------Biotech(Chemistry,Tech)-   JA

I need the expected output as  below:

emp_id ----- dept_name-----location
r1-----------Retail--------US
r1-----------IT----------- UK
k2-----------Sales---------NZ
k2-----------Chemical------SA
j3---------Biotech(Chemistry,Tech)--JA

The last record of whereever dept_name is "Biotech(Chemistry,Tech)" should be displayed as single record and not to be split. Please let me know how to do it.

The query given by Jim is working fine except in this scenario when dept_name is Biotech(Chemistry,Tech) as the requirement is given now.

Body:
Please use below query,

select emp_id, dept_name, location from
(select distinct emp_id, trim(regexp_substr(dept_name,'[^,]+', 1, level) ) dept_name,
trim(regexp_substr(location,'[^,]+', 1, level) ) location, level
from pivot_comma
connect by regexp_substr(dept_name, '[^,]+', 1, level) is not null
order by emp_id, level);


问:
SCSS ampersand and multiple parent selectors
I have just converted all of the style of my current project from Less to SCSS and I have a complex SCSS selector made of multiple selectors separated by commas that is now compiled completely differently.

I have background classes for my sections and I want to remove the top padding of a section with the same bg class as the previous one.

```<code>.bg{
    &--1, &--2, &--3, &--4,
    &--5, &--6, &--purple,
    &--pink, &--cyan{
        &.section + &.section{
            & > .padd{
                padding-top: 0;
            }
        }
    }
}
</code>```

I don't have the Less output anymore, but the ampersands in &.section + &.section should be only representing one of the parent selectors(e.g. .bg--1.section + .bg--1.section) but it is now representing every possible case (e.g. .bg--1.section + .bg--1.section, .bg--1.section + .bg--2.section, etc.) which is now applying to every section instead of only on repeated background sections and creating an endless css selector (15,798 characters, holy cow).

I know that the Less ampersand parent selector is not interpreted the same way as SCSS but I need to know how I could achieve the result I had in Less.

答:
I have managed to find an easy fix for this problem.

There is a @each loop in SCSS. Having all the color variables' names in a single list variable for an @each loop gave the exact same results as Less would normally do by default.
This is what the SCSS looks like now:

```<code>$colors: 1, 2, 3, 4, 5, 6, purple, pink, cyan;

@each $color in $colors {
    &--#{$color}{
        &.section + &.section{
            & > .padd{
                padding-top: 0;
            }
        }
    }
}
</code>```

Body:
I have just converted all of the style of my current project from Less to SCSS and I have a complex SCSS selector made of multiple selectors separated by commas that is now compiled completely differently.

I have background classes for my sections and I want to remove the top padding of a section with the same bg class as the previous one.

.bg{
    &--1, &--2, &--3, &--4,
    &--5, &--6, &--purple,
    &--pink, &--cyan{
        &.section + &.section{
            & > .padd{
                padding-top: 0;
            }
        }
    }
}

I don't have the Less output anymore, but the ampersands in &.section + &.section should be only representing one of the parent selectors(e.g. .bg--1.section + .bg--1.section) but it is now representing every possible case (e.g. .bg--1.section + .bg--1.section, .bg--1.section + .bg--2.section, etc.) which is now applying to every section instead of only on repeated background sections and creating an endless css selector (15,798 characters, holy cow).

I know that the Less ampersand parent selector is not interpreted the same way as SCSS but I need to know how I could achieve the result I had in Less.

Body:
I have managed to find an easy fix for this problem.

There is a @each loop in SCSS. Having all the color variables' names in a single list variable for an @each loop gave the exact same results as Less would normally do by default.
This is what the SCSS looks like now:

$colors: 1, 2, 3, 4, 5, 6, purple, pink, cyan;

@each $color in $colors {
    &--#{$color}{
        &.section + &.section{
            & > .padd{
                padding-top: 0;
            }
        }
    }
}


问:
Docker: run script : ERROR: Unable to lock database: Permission denied
Hello I'm trying to run a script to just start my yarn dev after my postgres is connected:

```<code>until psql -c '\l'; do
  echo >&2 "$(date +%Y%m%dt%H%M%S) Postgres is unavailable - sleeping"
  sleep 1
done
echo >&2 "$(date +%Y%m%dt%H%M%S) Postgres is up - executing command"

exec ${@}
</code>```

docker file:

```<code>    #building code
    FROM node:lts-alpine

    RUN mkdir -p /home/node/api && chown -R node:node /home/node/api

    WORKDIR /home/node/api

    COPY ormconfig.json .env package.json yarn.* ./

    USER node

    RUN yarn

    COPY --chown=node:node . .

    RUN apk add --no-cache openssl

    COPY wait-pg.sh ./
    RUN chmod +x /wait-pg.sh
    ENTRYPOINT ["/wait-pg.sh"]

    EXPOSE 4000

    CMD ["yarn", "dev"]
</code>```

docker compose:

```<code>version: '3.7'
services:
  db-pg:
    image: postgres:12
    container_name: db-pg
    ports:
      - '${DB_PORT}:5432'
    environment:
      ALLOW_EMPTY_PASSWORD: 'no'
      POSTGRES_USER: ${DB_USER}
      POSTGRES_PASSWORD: ${DB_PASS}
      POSTGRES_DB: ${DB_NAME}
    volumes:
      - ci-postgres-data:/data

  ci-api:
    build: .
    container_name: ci-api
    volumes:
      - .:/home/node/api
      - /home/node/api/node_modules
    ports:
      - '${SERVER_PORT}:${SERVER_PORT}'
    depends_on:
      - db-pg
    command: ['./wait-pg.sh', 'yarn', 'dev']
    logging:
      driver: 'json-file'
      options:
        max-size: '10m'
        max-file: '5'

volumes:
  ci-postgres-data:
</code>```

and  get this error:

---> Running in c5add5098b70 ERROR: Unable to lock database:
  Permission denied ERROR: Failed to open apk database: Permission
  denied ERROR: Service 'ci-api' failed to build: The command '/bin/sh
  -c apk add --no-cache openssl' returned a non-zero code: 99

答:
You are getting the error because the node user you are trying to use does not have permissions to run the command.
Move the user definition to after the commands,  something like this:</p>

```<code>  #building code
    FROM node:lts-alpine

    RUN mkdir -p /home/node/api && chown -R node:node /home/node/api
    WORKDIR /home/node/api
    COPY ormconfig.json .env package.json yarn.* ./

    RUN yarn
    COPY --chown=node:node . .
    RUN apk add --no-cache openssl
    COPY wait-pg.sh .
    RUN chmod +x ./wait-pg.sh

    USER node

    ENTRYPOINT ["./wait-pg.sh"]
    EXPOSE 4000
    CMD ["yarn", "dev"]
</code>```

Body:
Hello I'm trying to run a script to just start my yarn dev after my postgres is connected:

until psql -c '\l'; do
  echo >&2 "$(date +%Y%m%dt%H%M%S) Postgres is unavailable - sleeping"
  sleep 1
done
echo >&2 "$(date +%Y%m%dt%H%M%S) Postgres is up - executing command"

exec ${@}

docker file:

    #building code
    FROM node:lts-alpine

    RUN mkdir -p /home/node/api && chown -R node:node /home/node/api

    WORKDIR /home/node/api

    COPY ormconfig.json .env package.json yarn.* ./

    USER node

    RUN yarn

    COPY --chown=node:node . .

    RUN apk add --no-cache openssl

    COPY wait-pg.sh ./
    RUN chmod +x /wait-pg.sh
    ENTRYPOINT ["/wait-pg.sh"]

    EXPOSE 4000

    CMD ["yarn", "dev"]

docker compose:

version: '3.7'
services:
  db-pg:
    image: postgres:12
    container_name: db-pg
    ports:
      - '${DB_PORT}:5432'
    environment:
      ALLOW_EMPTY_PASSWORD: 'no'
      POSTGRES_USER: ${DB_USER}
      POSTGRES_PASSWORD: ${DB_PASS}
      POSTGRES_DB: ${DB_NAME}
    volumes:
      - ci-postgres-data:/data

  ci-api:
    build: .
    container_name: ci-api
    volumes:
      - .:/home/node/api
      - /home/node/api/node_modules
    ports:
      - '${SERVER_PORT}:${SERVER_PORT}'
    depends_on:
      - db-pg
    command: ['./wait-pg.sh', 'yarn', 'dev']
    logging:
      driver: 'json-file'
      options:
        max-size: '10m'
        max-file: '5'

volumes:
  ci-postgres-data:

and  get this error:

---> Running in c5add5098b70 ERROR: Unable to lock database:
  Permission denied ERROR: Failed to open apk database: Permission
  denied ERROR: Service 'ci-api' failed to build: The command '/bin/sh
  -c apk add --no-cache openssl' returned a non-zero code: 99

Body:
You are getting the error because the node user you are trying to use does not have permissions to run the command.
Move the user definition to after the commands,  something like this:

  #building code
    FROM node:lts-alpine

    RUN mkdir -p /home/node/api && chown -R node:node /home/node/api
    WORKDIR /home/node/api
    COPY ormconfig.json .env package.json yarn.* ./

    RUN yarn
    COPY --chown=node:node . .
    RUN apk add --no-cache openssl
    COPY wait-pg.sh .
    RUN chmod +x ./wait-pg.sh

    USER node

    ENTRYPOINT ["./wait-pg.sh"]
    EXPOSE 4000
    CMD ["yarn", "dev"]


问:
Dask multiple clients
Is it possible to have multiple clients in dask? For instance, can I have multiple threads running with one client per thread, so that when one thread blocks, the others can continue? In this case, each client would have separate task graphs that don't depend on each other.

As a followup question, if this is possible, then how can I specify where to run a specific task? When I do dd.read_csv, then call compute, how do I know which client and its associated scheduler / workers is executing this?

答:
Is it possible to have multiple clients in dask

yes, this is possible, you could, for instance, be running computations on one cluster and other computations on another, simultaneously

can I have multiple threads running with one client per thread

It is not clients that run your work, but workers, so I'm not sure what you are asking.

when one thread blocks, the others can continue

Clients are largely async, and there are few operations that should block, and it's up to you when you call them.

when call compute, how do I know which client and its associated scheduler / workers is executing this

thing.compute() will use the default client, which will be the most recently-created one. The function dask.distributed.get_client() would fetch the right one for you.

To pick which to use, you can use either of these:

```<code>fut = client.compute(thing)
fut.result() or client.gather(fut)

with client:
    thing.compute()
</code>```

Title: Dask multiple clients

Body:
Is it possible to have multiple clients in dask

yes, this is possible, you could, for instance, be running computations on one cluster and other computations on another, simultaneously

can I have multiple threads running with one client per thread

It is not clients that run your work, but workers, so I'm not sure what you are asking.

when one thread blocks, the others can continue

Clients are largely async, and there are few operations that should block, and it's up to you when you call them.

when call compute, how do I know which client and its associated scheduler / workers is executing this

thing.compute() will use the default client, which will be the most recently-created one. The function dask.distributed.get_client() would fetch the right one for you.

To pick which to use, you can use either of these:

fut = client.compute(thing)
fut.result() or client.gather(fut)

with client:
    thing.compute()


问:
Recursive depth function on an array
I have an array of objects like this input, and I want to nest some objects inside another objects (based if their parentId is the parents' forumId),

I got the function working but up to 1 depth, how can I get it working for n depth? Any idea or optimizations are appreciated!

EDIT: After pointing out, the input isn't necessarily ordered.

const input = [
  {
    forumId: 1,
    parentId: null,
    forumName: "Main",
    forumDescription: "",
    forumLocked: false,
    forumDisplay: true,
  },
  {
    forumId: 2,
    parentId: 1,
    forumName: "Announcements",
    forumDescription: "Announcements & Projects posted here",
    forumLocked: false,
    forumDisplay: true,
  },
  {
    forumId: 3,
    parentId: 1,
    forumName: "General",
    forumDescription: "General forum, talk whatever you want here",
    forumLocked: false,
    forumDisplay: true,
  },
  {
    forumId: 4,
    parentId: 3,
    forumName: "Introduction",
    forumDescription: "A warming introduction for newcomers here",
    forumLocked: false,
    forumDisplay: true,
  },
];

function processInput(forumInput) {
  const topLevelForums = forumInput.filter(function (forum) {
    return forum.parentId === null;
  });

  let output = topLevelForums;

  forumInput.forEach(function (forum) {
    if (forum.parentId !== null) {
      const forumParentId = forum.parentId;
      output.forEach(function (parentForum, idx) {
        if (parentForum.forumId === forumParentId) {
          if (!output[idx].hasOwnProperty("subForums")) {
            output[idx].subForums = [];
          }
          parentForum.subForums.push(forum);
        }
      });
    }
  });

  return output;
}
```

<p>This is the <strong>expected output</strong>:</p>

```[
  {
    forumId: 1,
    parentId: null,
    forumName: "Main",
    forumDescription: "",
    forumLocked: false,
    forumDisplay: true,
    subForums: [
      {
        forumId: 2,
        parentId: 1,
        forumName: "Announcements",
        forumDescription: "Announcements & Projects posted here",
        forumLocked: false,
        forumDisplay: true,
      },
      {
        forumId: 3,
        parentId: 1,
        forumName: "General",
        forumDescription: "General forum, talk whatever you want here",
        forumLocked: false,
        forumDisplay: true,
        subForums: [
          {
            forumId: 4,
            parentId: 3,
            forumName: "Introduction",
            forumDescription: "A warming introduction for newcomers here",
            forumLocked: false,
            forumDisplay: true,
          },
        ],
      },
    ],
  },
]
```

<p>This is the <strong>current output</strong>:</p>

```[
  {
    forumDescription: "",
    forumDisplay: true,
    forumId: 1,
    forumLocked: false,
    forumName: "Main",
    parentId: null,
    subForums: [
      {
        forumDescription: "Announcements & Projects posted here",
        forumDisplay: true,
        forumId: 2,
        forumLocked: false,
        forumName: "Announcements",
        parentId: 1,
      },
      {
        forumDescription: "General forum, talk whatever you want here",
        forumDisplay: true,
        forumId: 3,
        forumLocked: false,
        forumName: "General",
        parentId: 1,
      },
    ],
  },
]
```

答:
As some other answers, I would use a Map to key nodes by their forumId, and then populate the children inside the corresponding values:

let input = [{ forumId: 3, parentId: 1, forumName: "General", forumDescription: "General forum, talk whatever you want here", forumLocked: false, forumDisplay: true }, { forumId: 2, parentId: 1, forumName: "Announcements", forumDescription: "Announcements & Projects posted here", forumLocked: false, forumDisplay: true }, { forumId: 4, parentId: 3, forumName: "Introduction", forumDescription: "A warming introduction for newcomers here", forumLocked: false, forumDisplay: true }, { forumId: 1, parentId: null, forumName: "Main", forumDescription: "", forumLocked: false, forumDisplay: true }];

let root = {};
let map = new Map(input.map(o => [o.forumId, ({...o})]))
map.forEach(o => (p => p.subForms = (p.subForms || []).concat(o))(map.get(o.parentId) || root));
let result = root.subForms;

console.log(result);```

Title: Recursive depth function on an array

Body:
I have an array of objects like this input, and I want to nest some objects inside another objects (based if their parentId is the parents' forumId),

I got the function working but up to 1 depth, how can I get it working for n depth? Any idea or optimizations are appreciated!

EDIT: After pointing out, the input isn't necessarily ordered.

const input = [
  {
    forumId: 1,
    parentId: null,
    forumName: "Main",
    forumDescription: "",
    forumLocked: false,
    forumDisplay: true,
  },
  {
    forumId: 2,
    parentId: 1,
    forumName: "Announcements",
    forumDescription: "Announcements & Projects posted here",
    forumLocked: false,
    forumDisplay: true,
  },
  {
    forumId: 3,
    parentId: 1,
    forumName: "General",
    forumDescription: "General forum, talk whatever you want here",
    forumLocked: false,
    forumDisplay: true,
  },
  {
    forumId: 4,
    parentId: 3,
    forumName: "Introduction",
    forumDescription: "A warming introduction for newcomers here",
    forumLocked: false,
    forumDisplay: true,
  },
];

function processInput(forumInput) {
  const topLevelForums = forumInput.filter(function (forum) {
    return forum.parentId === null;
  });

  let output = topLevelForums;

  forumInput.forEach(function (forum) {
    if (forum.parentId !== null) {
      const forumParentId = forum.parentId;
      output.forEach(function (parentForum, idx) {
        if (parentForum.forumId === forumParentId) {
          if (!output[idx].hasOwnProperty("subForums")) {
            output[idx].subForums = [];
          }
          parentForum.subForums.push(forum);
        }
      });
    }
  });

  return output;
}

This is the expected output:

[
  {
    forumId: 1,
    parentId: null,
    forumName: "Main",
    forumDescription: "",
    forumLocked: false,
    forumDisplay: true,
    subForums: [
      {
        forumId: 2,
        parentId: 1,
        forumName: "Announcements",
        forumDescription: "Announcements & Projects posted here",
        forumLocked: false,
        forumDisplay: true,
      },
      {
        forumId: 3,
        parentId: 1,
        forumName: "General",
        forumDescription: "General forum, talk whatever you want here",
        forumLocked: false,
        forumDisplay: true,
        subForums: [
          {
            forumId: 4,
            parentId: 3,
            forumName: "Introduction",
            forumDescription: "A warming introduction for newcomers here",
            forumLocked: false,
            forumDisplay: true,
          },
        ],
      },
    ],
  },
]

This is the current output:

[
  {
    forumDescription: "",
    forumDisplay: true,
    forumId: 1,
    forumLocked: false,
    forumName: "Main",
    parentId: null,
    subForums: [
      {
        forumDescription: "Announcements & Projects posted here",
        forumDisplay: true,
        forumId: 2,
        forumLocked: false,
        forumName: "Announcements",
        parentId: 1,
      },
      {
        forumDescription: "General forum, talk whatever you want here",
        forumDisplay: true,
        forumId: 3,
        forumLocked: false,
        forumName: "General",
        parentId: 1,
      },
    ],
  },
]


答:
You can try using the lifecycle method - componentDidMount in your App.js ( the starting react file ). Put your logic in this lifecycle method. For example -

```<code>async componentDidMount() {
    await this.setState({
      user:localStorage.getItem("user")
    })
}
</code>```

And then use this state in your render function to update your DOM accordingly.

Body:
You can try using the lifecycle method - componentDidMount in your App.js ( the starting react file ). Put your logic in this lifecycle method. For example -

async componentDidMount() {
    await this.setState({
      user:localStorage.getItem("user")
    })
}

And then use this state in your render function to update your DOM accordingly.


问:
How to deploy an app with multiple Docker containers to AWS Elastic Beanstalk?
I have a Django application whose docker image's Dockerfile is as follows:

```<code>FROM python:3.7

ENV PYTHONUNBUFFERED 1

RUN mkdir /code
WORKDIR /code
COPY requirements.txt /code/

RUN pip3 install -r requirements.txt
COPY . /code/

ENV PORT=8000
EXPOSE 8000
</code>```

Then, I have a docker-compose.yml file for defining other container images and dependencies for my Django application as follows:

```<code>version: '3'

services:
  web: &django_app
    build: .
    command: python3 manage.py runserver 0.0.0.0:8000
    ports:
      - "80:8000"
    depends_on:
      - rabbitmq
  rabbitmq:
    image: rabbitmq:latest
  celery_worker:
    <<: *django_app
    command: celery -A DJingApp worker --loglevel=info
    ports: []
    depends_on:
      - rabbitmq
</code>```

As you can see above, I've got to have 3 containers(web, rabbitmq, and celery_worker) running at any point in time for my Django app to work.

So, how do I deploy this project's Docker images to AWS Elastic Beanstalk and run them out there? Are there any changes that I will have to make to my Dockerfile or docker-compose.yml? If yes, what are they?

答:
It's quite challenging to deploy a multi-container app to Elastic Beanstalk. You need a Dockerrun.aws.json version 2 configuration file which is an Elastic Beanstalk–specific JSON file that describes how to deploy a set of Docker containers as an Elastic Beanstalk application.

If you don't know how to create the configuration file I suggest reviewing the official page.

And also you can use container transform utility to transform your docker-compose file to a Dockerrun.aws.json configuration file which I find very helpful. You may need to make some changes in the autogenerated file.

And also to customize your environment you need to use .ebextensions. Such as defining your Django settings path, WSGI path, web server configurations, executing Django management commands before deployment and so.

For detailed logs, I suggest using environment logs under:

Elastic Beanstalk - Environments - 'your-environment-name' - Logs

Note: I suggest using eb deploy for successful deployment since you need to deploy your source code in .zip file format.

Body:
I have a Django application whose docker image's Dockerfile is as follows:

FROM python:3.7

ENV PYTHONUNBUFFERED 1

RUN mkdir /code
WORKDIR /code
COPY requirements.txt /code/

RUN pip3 install -r requirements.txt
COPY . /code/

ENV PORT=8000
EXPOSE 8000

Then, I have a docker-compose.yml file for defining other container images and dependencies for my Django application as follows:

version: '3'

services:
  web: &django_app
    build: .
    command: python3 manage.py runserver 0.0.0.0:8000
    ports:
      - "80:8000"
    depends_on:
      - rabbitmq
  rabbitmq:
    image: rabbitmq:latest
  celery_worker:
    <<: *django_app
    command: celery -A DJingApp worker --loglevel=info
    ports: []
    depends_on:
      - rabbitmq

As you can see above, I've got to have 3 containers(web, rabbitmq, and celery_worker) running at any point in time for my Django app to work.

So, how do I deploy this project's Docker images to AWS Elastic Beanstalk and run them out there? Are there any changes that I will have to make to my Dockerfile or docker-compose.yml? If yes, what are they?


问:
onPress not working on Animatable component
Is anything jumping out as wrong here? I am trying to have an onPress behavior on my Animatable component so when i drag it around with a gesture it will move, but if i click it it will fire that onPress behavior ...

It's currently a TouchableOpacity because that is what another stackoverflow answer suggested, yet when I use the createAnimatedComponent function with a TouchableOpacity I lose the ability to actually move it with gestures.

Any ideas?

```<code>return (
      <AnimatedTouchable
        style={[
          styles.card,
          this.state.active ? { zIndex: 2 } : { zIndex: 1 },
          {
            transform: [
              { translateX: this._animatedValue.x },
              { translateY: this._animatedValue.y },
              { rotate: interpolatedRotation },
              { scaleX: this.scale },
              { scaleY: this.scale }
            ]
          }
        ]}
        onPress={this.sayHi}
        {...this._panResponder.panHandlers}
      >
        <Text style={styles.cardNumber}>{this.props.id}</Text>
      </AnimatedTouchable>
    );
</code>```

const AnimatedTouchable = Animated.createAnimatedComponent(TouchableOpacity);

With this current setup it only fires the onPress function, but non of my gesture animations go through.

答:
You can wrap your component with an AnimatableView and use a ref in order to execute the animation, example:

```<code>import React, { useRef } from 'react'
import {
  View as AnimatableView,
  initializeRegistryWithDefinitions
} from 'react-native-animatable'
import { throttle } from 'lodash'
import { ANIMATIONS } from '../animations'

export default function (WrappedComponent) {
  return ({ onPress, delay = 800, duration = 1000, animation = ANIMATIONS.ZOOM_IN_OUT, ...rest }) => {
    const compEl = useRef(null)
    const onPressAnimatedDelayed = throttle((event) => {
      onPress && onPress(event)
      compEl.current.animate(animation, duration)
    }, delay, { 'trailing': false })

    return (
      <AnimatableView ref={compEl}>
        <WrappedComponent
          onPress={onPressAnimatedDelayed}
          {...rest}
        />
      </AnimatableView>
    )
  }
}
</code>```

Check the example running from Expo: https://snack.expo.io/@jdnichollsc/animatable

Regards

Body:
Is anything jumping out as wrong here? I am trying to have an onPress behavior on my Animatable component so when i drag it around with a gesture it will move, but if i click it it will fire that onPress behavior ...

It's currently a TouchableOpacity because that is what another stackoverflow answer suggested, yet when I use the createAnimatedComponent function with a TouchableOpacity I lose the ability to actually move it with gestures.

Any ideas?

return (
      <AnimatedTouchable
        style={[
          styles.card,
          this.state.active ? { zIndex: 2 } : { zIndex: 1 },
          {
            transform: [
              { translateX: this._animatedValue.x },
              { translateY: this._animatedValue.y },
              { rotate: interpolatedRotation },
              { scaleX: this.scale },
              { scaleY: this.scale }
            ]
          }
        ]}
        onPress={this.sayHi}
        {...this._panResponder.panHandlers}
      >
        <Text style={styles.cardNumber}>{this.props.id}</Text>
      </AnimatedTouchable>
    );

const AnimatedTouchable = Animated.createAnimatedComponent(TouchableOpacity);

With this current setup it only fires the onPress function, but non of my gesture animations go through.

Body:
You can wrap your component with an AnimatableView and use a ref in order to execute the animation, example:

import React, { useRef } from 'react'
import {
  View as AnimatableView,
  initializeRegistryWithDefinitions
} from 'react-native-animatable'
import { throttle } from 'lodash'
import { ANIMATIONS } from '../animations'

export default function (WrappedComponent) {
  return ({ onPress, delay = 800, duration = 1000, animation = ANIMATIONS.ZOOM_IN_OUT, ...rest }) => {
    const compEl = useRef(null)
    const onPressAnimatedDelayed = throttle((event) => {
      onPress && onPress(event)
      compEl.current.animate(animation, duration)
    }, delay, { 'trailing': false })

    return (
      <AnimatableView ref={compEl}>
        <WrappedComponent
          onPress={onPressAnimatedDelayed}
          {...rest}
        />
      </AnimatableView>
    )
  }
}

Check the example running from Expo: https://snack.expo.io/@jdnichollsc/animatable

Regards


问:
Jmeter delay between threads
I am using JMeter for performance testing. I am using csv file and there are 8 lines of data. I want to execute 3 threads in parallel at a time.
1,2,3 - execute in parallel
1 minute time delay
then 4,5,6 - parallel
1 minute time delay
then
7,8 - parallel execution

I am using JSR223 timer. I used the below code:

```<code>if(ctx.getThreadNum()%3==0) {
   sleep(60000);
</code>```

}

Here its sleeping at thread 3 and 6 but not as I mentioned above. Could someone please provide a idea on this?

答:
Maybe it would be easier to switch to Parallel Controller like:

Parallel Controller

1

2

3

Flow Control Action for delay

Parallel Controller

4

5

6

Flow Control Action for delay

Parallel Controller

7

8

The similar behaviour can be achieved using Synchronizing Timer if you cannot or unwilling to use the Parallel Controller

Title: Jmeter delay between threads

Body:
I am using JMeter for performance testing. I am using csv file and there are 8 lines of data. I want to execute 3 threads in parallel at a time.
1,2,3 - execute in parallel
1 minute time delay
then 4,5,6 - parallel
1 minute time delay
then
7,8 - parallel execution

I am using JSR223 timer. I used the below code:

if(ctx.getThreadNum()%3==0) {
   sleep(60000);

}

Here its sleeping at thread 3 and 6 but not as I mentioned above. Could someone please provide a idea on this?


问:
Woocommerce form has no action?
I'm looking at the code in form-edit-address.php and I am very confused. I need to know what function is called when the 'Save address' button is clicked. However I can't find anything that links this button to a function. Am I missing something here?

```<code><form method="post">

    <h3><?php echo apply_filters( 'woocommerce_my_account_edit_address_title', $page_title, $load_address ); ?></h3><?php // @codingStandardsIgnoreLine ?>

    <div class="woocommerce-address-fields">
        <?php do_action( "woocommerce_before_edit_address_form_{$load_address}" ); ?>

        <div class="woocommerce-address-fields__field-wrapper">
            <?php
            foreach ( $address as $key => $field ) {
                woocommerce_form_field( $key, $field, wc_get_post_data_by_key( $key, $field['value'] ) );
            }
            ?>
        </div>

        <?php do_action( "woocommerce_after_edit_address_form_{$load_address}" ); ?>

        <p>
            <button type="submit" class="button" name="save_address" value="<?php esc_attr_e( 'Save address', 'woocommerce' ); ?>"><?php esc_html_e( 'Save address', 'woocommerce' ); ?></button>
            <?php wp_nonce_field( 'woocommerce-edit_address', 'woocommerce-edit-address-nonce' ); ?>
            <input type="hidden" name="action" value="edit_address" />
        </p>
    </div>

</form>
</code>```

What tells the program what to do when the button is clicked?

答: If there is no explicit action, the currently active URL is used (standard HTML). So if you're on /foo, the POST request will be sent to /foo - in this probably directly to form-edit-address.php.

Title: Woocommerce form has no action?

Body:
I'm looking at the code in form-edit-address.php and I am very confused. I need to know what function is called when the 'Save address' button is clicked. However I can't find anything that links this button to a function. Am I missing something here?

<form method="post">

<?php echo apply_filters( 'woocommerce_my_account_edit_address_title', $page_title, $load_address ); ?>
<?php // @codingStandardsIgnoreLine ?>

        <?php do_action( "woocommerce_before_edit_address_form_{$load_address}" ); ?>

            <?php
            foreach ( $address as $key => $field ) {
                woocommerce_form_field( $key, $field, wc_get_post_data_by_key( $key, $field['value'] ) );
            }
            ?>

        <?php do_action( "woocommerce_after_edit_address_form_{$load_address}" ); ?>

            <button type="submit" class="button" name="save_address" value="<?php esc_attr_e( 'Save address', 'woocommerce' ); ?>"><?php esc_html_e( 'Save address', 'woocommerce' ); ?></button>
            <?php wp_nonce_field( 'woocommerce-edit_address', 'woocommerce-edit-address-nonce' ); ?>
            <input type="hidden" name="action" value="edit_address" />

</form>

What tells the program what to do when the button is clicked?


问:
How to subtract two identical dataframes in pandas
I have got two identical dataframes in pandas/python (a and b) only values are different:

a:

```<code>date       a1 a2 a3
01.01.2020 2  2  2
02.01.2020 3  3  3
03.01.2020 4  4  4
</code>```

b:

```<code>date       a1 a2 a3
01.01.2020 1  1  1
01.01.2020 2  2  2
01.01.2020 3  3  3
</code>```

I need a - b and expect to see result c:

```<code>date       a1 a2 a3
01.01.2020 1  1  1
01.01.2020 1  1  1
01.01.2020 1  1  1
</code>```

a - b does not work and I cannot figure out how. Would you please help me? Thanks!

答: Try using df1.subtract(df2). Simple and elegant.

Body:
I have got two identical dataframes in pandas/python (a and b) only values are different:

a:

date       a1 a2 a3
01.01.2020 2  2  2
02.01.2020 3  3  3
03.01.2020 4  4  4

b:

date       a1 a2 a3
01.01.2020 1  1  1
01.01.2020 2  2  2
01.01.2020 3  3  3

I need a - b and expect to see result c:

date       a1 a2 a3
01.01.2020 1  1  1
01.01.2020 1  1  1
01.01.2020 1  1  1

a - b does not work and I cannot figure out how. Would you please help me? Thanks!


问:
how to set radio button text(caption) to center
**VB.NET 2010 , ASPNET *******

Hi,

Is there a way to set the radio button text to center,
I want to show it on the top of radiobutton hole..thanks

答:
The text and the radio button are separate, so you can style them any way you like. Example:

HTML:

```<code><label class="CenteredRadio">
  <span>Click me</span>
  <input type="radio" name="group" value="yes" />
</label>
</code>```

CSS:

```<code>.CenteredRadio { width: 300px; }
.CenteredRadio span { display: block; text-align: center; }
.CenteredRadio input { display: block; text-align: center; }
</code>```

If you are using a RadioButton control, set it's text to an empty string, and you can use your own text.

Body:
The text and the radio button are separate, so you can style them any way you like. Example:

HTML:

<label class="CenteredRadio">
  <span>Click me</span>
  <input type="radio" name="group" value="yes" />
</label>

CSS:

.CenteredRadio { width: 300px; }
.CenteredRadio span { display: block; text-align: center; }
.CenteredRadio input { display: block; text-align: center; }

If you are using a RadioButton control, set it's text to an empty string, and you can use your own text.


问:
How do I change model coefficients to compare a model in the literature?
I'd like to compare the coefficients from my own replication of a statistical model in the literature with the coefficients in the literature. I thougth I could just duplicate my model, and then plug in the coefficients from the literature and print both. But I'm getting this error:

Error in if (coef.var[i] == .global.coefficient.variables[j]) { :
  argument is of length zero

What is the easiest way to do this?

```<code>##fake data
var1<-rnorm(100)
var2<-rnorm(100)
df<-data.frame(var1, var2)
#My own model
model1<-lm(var1~var2, data=df)

#Duplicate my own model
model2<-model1
#Try to change the coefficients to match what appears in the literature
model2$coefficients<-c(5, 10)
#Try to report
library(stargazer)
stargazer(model1, model2,type="html")
</code>```

答:
This works:</p>

```<code>var1<-rnorm(100)
var2<-rnorm(100)
df<-data.frame(var1, var2)

model1<-lm(var1~var2, data=df)

model2<-model1

model2$coefficients[[1]] <- 5
model2$coefficients[[2]] <- 10

library(stargazer)
stargazer(model1, model2,type="html")
</code>```

Body:
I'd like to compare the coefficients from my own replication of a statistical model in the literature with the coefficients in the literature. I thougth I could just duplicate my model, and then plug in the coefficients from the literature and print both. But I'm getting this error:

Error in if (coef.var[i] == .global.coefficient.variables[j]) { :
  argument is of length zero

What is the easiest way to do this?

##fake data
var1<-rnorm(100)
var2<-rnorm(100)
df<-data.frame(var1, var2)
#My own model
model1<-lm(var1~var2, data=df)

#Duplicate my own model
model2<-model1
#Try to change the coefficients to match what appears in the literature
model2$coefficients<-c(5, 10)
#Try to report
library(stargazer)
stargazer(model1, model2,type="html")

Body:
This works:

var1<-rnorm(100)
var2<-rnorm(100)
df<-data.frame(var1, var2)

model1<-lm(var1~var2, data=df)

model2<-model1

model2$coefficients[[1]] <- 5
model2$coefficients[[2]] <- 10

library(stargazer)
stargazer(model1, model2,type="html")


问:
Extracting first line from a file if condition matches in a block
I have the below file and I need to capture all the hostnames in a single file separated by "," which have Failed: 0 in them

file.txt:

```<code>host1:
   name: sudo something
   name: something
   succeeded: 34
   Failed: 0
host2:
   name: something 123
   succeeded: 12
   Failed: 3
host3:
   name: something 1234
   succeeded: 12
   Failed: 13
host4:
   name: something 1234
   succeeded: 12
   Failed: 0
</code>```

So, the output should be host1, host4. I have tried the below code:

```<code>awk -F ':' '/:/{host=$1; getline; if($1 !~ /Failed:0/) NR==1{print host}}' file.txt > output.txt
</code>```

Can anyone, advice how to go about it, please? I would prefer to do it in one line command as I need to pass it via Jenkins pipeline.

========================Update===============================

Using grep - V Name: my input file looks as below:

host1:

Summary for host1

Succeeded: 36 (changed=10)

Failed:     0

host4:

Summary for host4

Succeeded: 36 (changed=10)

Failed:     0

Now, how can I just filter for Failed:  0 cases and get the hostnames?

答:
Your YAML with the good indentation:

```<code>host1:
   name: sudo something
   name: something
   succeeded: 34
   Failed: 0
host2:
   name: something 123
   succeeded: 12
   Failed: 3
host3:
   name: something 1234
   succeeded: 12
   Failed: 13
host4:
   name: something 1234
   succeeded: 12
   Failed: 13
</code>```

Now with perl, we can properly parse the YAML :

```<code>#!/usr/bin/env perl

my $conf_file = "conf.yaml";

use strict; use warnings;
use YAML::AppConfig;

my $conf = YAML::AppConfig->new(file => $conf_file) or die;

foreach my $host (keys %{$conf->{config}}) {
    print $host if $conf->{config}->{$host}->{"Failed"} == 0;
}
</code>```

Output

```<code>host1
host4
</code>```

This is the hosts with Failed 0

Body:
I have the below file and I need to capture all the hostnames in a single file separated by "," which have Failed: 0 in them

file.txt:

host1:
   name: sudo something
   name: something
   succeeded: 34
   Failed: 0
host2:
   name: something 123
   succeeded: 12
   Failed: 3
host3:
   name: something 1234
   succeeded: 12
   Failed: 13
host4:
   name: something 1234
   succeeded: 12
   Failed: 0

So, the output should be host1, host4. I have tried the below code:

awk -F ':' '/:/{host=$1; getline; if($1 !~ /Failed:0/) NR==1{print host}}' file.txt > output.txt

Can anyone, advice how to go about it, please? I would prefer to do it in one line command as I need to pass it via Jenkins pipeline.

========================Update===============================

Using grep - V Name: my input file looks as below:

host1:

Summary for host1

Succeeded: 36 (changed=10)

Failed:     0

host4:

Summary for host4

Succeeded: 36 (changed=10)

Failed:     0

Now, how can I just filter for Failed:  0 cases and get the hostnames?

Body:
Your YAML with the good indentation:

host1:
   name: sudo something
   name: something
   succeeded: 34
   Failed: 0
host2:
   name: something 123
   succeeded: 12
   Failed: 3
host3:
   name: something 1234
   succeeded: 12
   Failed: 13
host4:
   name: something 1234
   succeeded: 12
   Failed: 13

Now with perl, we can properly parse the YAML :

#!/usr/bin/env perl

my $conf_file = "conf.yaml";

use strict; use warnings;
use YAML::AppConfig;

my $conf = YAML::AppConfig->new(file => $conf_file) or die;

foreach my $host (keys %{$conf->{config}}) {
    print $host if $conf->{config}->{$host}->{"Failed"} == 0;
}

Output

host1
host4

This is the hosts with Failed 0