问:
Execute BeforeEach Hook before Before Hook in Mocha
I want to create a beforeEach Hook that is executed before a before Hook.

Basically I want the following behaviour:

```<code>beforeEach(() => {
  console.log('beforeEach')
})

describe('tests', () => {
  before(() => {
    console.log('before')
  })

  it('test 1', () => {
    console.log('it')
  })
})
</code>```

And I get:

```<code>before
beforeEach
it
</code>```

But the output I want is:

```<code>beforeEach
before
it
</code>```

What would be the correct structure to get the desired behaviour?

Workaround

Currently I found a workaround using two nested beforeEach:

```<code>beforeEach(() => {
  console.log('beforeEach1')
})

describe('tests', () => {
  beforeEach(() => {
    console.log('beforeEach2')
  })

  it('test 1', () => {
    console.log('it')
  })
})
</code>```

Which output is:

```<code>beforeEach1
beforeEach2
it
</code>```

答:
You could use a describe() that has a beforeEach() and a describe() inside of it.

Something like this

```<code>describe ('A blah component', () =>
{
  beforeEach(() => {
    console.log('beforeEach')
  })

   describe(`tests`, () => {
     before(() => {
       console.log('before')
     })

     it('test 1, () => {
       console.log('it')
     })
   })
}
</code>```

Body:
I want to create a beforeEach Hook that is executed before a before Hook.

Basically I want the following behaviour:

beforeEach(() => {
  console.log('beforeEach')
})

describe('tests', () => {
  before(() => {
    console.log('before')
  })

  it('test 1', () => {
    console.log('it')
  })
})

And I get:

before
beforeEach
it

But the output I want is:

beforeEach
before
it

What would be the correct structure to get the desired behaviour?

Workaround

Currently I found a workaround using two nested beforeEach:

beforeEach(() => {
  console.log('beforeEach1')
})

describe('tests', () => {
  beforeEach(() => {
    console.log('beforeEach2')
  })

  it('test 1', () => {
    console.log('it')
  })
})

Which output is:

beforeEach1
beforeEach2
it

Body:
You could use a describe() that has a beforeEach() and a describe() inside of it.

Something like this

describe ('A blah component', () =>
{
  beforeEach(() => {
    console.log('beforeEach')
  })

   describe(`tests`, () => {
     before(() => {
       console.log('before')
     })

     it('test 1, () => {
       console.log('it')
     })
   })
}


来源: stackexchange

问:
How to handle when a factorial gets too big for int in C++?
I have this recursive function for finding factorial, but I don't know how to modify it to throw an error when the factorial gets too big for int.

If my function was iterative, I could just put in an if-statement, checking if the factorial was 0 or less each time through, thereby finding where the overflow occurred, but this doesn't seem feasible for the recursive definition.

```<code>int factorial(int x)
{
    if (x < 0) error("Can't take factorial of a negative number.");
    else if (x == 0) return 1;
    else return x * factorial(x - 1);
}
</code>```

If for example, I call the function with 50, it will return 0. I would like to throw an error message in cases like this. Could anyone straighten me out on this?

答:
The factorial function is a static function whose output will always be the same, given the same input. Therefore, we can know in advance whether a given input will overflow or not.

```<code>int32_t factorial(int32_t val) {
    if(val > 12)
        throw std::runtime_error("Input too large for Factorial function (val must be less than 13)");
    if(val < 0)
        throw std::runtime_error("Input must be non-negative");
    if(val == 0)
        return 1;
    return factorial(val-1) * val;
}

int64_t factorial(int64_t val) {
    if(val > 20)
        throw std::runtime_error("Input too large for Factorial function (val must be less than 21)");
    if(val < 0)
        throw std::runtime_error("Input must be non-negative");
    if(val == 0)
        return 1;
    return factorial(val-1) * val;
}
</code>```

If you'd like to instead detect integer overflow dynamically, you'll need to review rigorous methods for detecting possible overflow.

ContentLicense: CC BY-SA 4.0

Body:
I have this recursive function for finding factorial, but I don't know how to modify it to throw an error when the factorial gets too big for int.

If my function was iterative, I could just put in an if-statement, checking if the factorial was 0 or less each time through, thereby finding where the overflow occurred, but this doesn't seem feasible for the recursive definition.

int factorial(int x)
{
    if (x < 0) error("Can't take factorial of a negative number.");
    else if (x == 0) return 1;
    else return x * factorial(x - 1);
}

If for example, I call the function with 50, it will return 0. I would like to throw an error message in cases like this. Could anyone straighten me out on this?

Body:
The factorial function is a static function whose output will always be the same, given the same input. Therefore, we can know in advance whether a given input will overflow or not.

int32_t factorial(int32_t val) {
    if(val > 12)
        throw std::runtime_error("Input too large for Factorial function (val must be less than 13)");
    if(val < 0)
        throw std::runtime_error("Input must be non-negative");
    if(val == 0)
        return 1;
    return factorial(val-1) * val;
}

int64_t factorial(int64_t val) {
    if(val > 20)
        throw std::runtime_error("Input too large for Factorial function (val must be less than 21)");
    if(val < 0)
        throw std::runtime_error("Input must be non-negative");
    if(val == 0)
        return 1;
    return factorial(val-1) * val;
}

If you'd like to instead detect integer overflow dynamically, you'll need to review rigorous methods for detecting possible overflow.


问:
How to write a column name with dot (".") in the SELECT clause?
I'm trying to write a column name using "." with no success

sample:

```<code>SELECT PrmTable.Value = MAX(Value)
FROM TempTable
</code>```

or

```<code>SELECT MAX(Value) AS PrmTable.Value
FROM TempTable
</code>```

Any idea ?

答:
```<code>SELECT [PrmTable.Value] = MAX(Value)

FROM TempTable

or

SELECT MAX(Value) AS [PrmTable.Value]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to write a column name using "." with no success

sample:

SELECT PrmTable.Value = MAX(Value)
FROM TempTable

or

SELECT MAX(Value) AS PrmTable.Value
FROM TempTable

Any idea ?


问:
Automation Anywhere Excel Loop
Does anyone know of an easy way to start an excel loop in Automation Anywhere at a row other than 1? (or two by using contains header option). I would like to start a loop at row 5 but everything I have tried thus far does not work.

Thanks in advance.

答:
You can use the command - Go to Cell under Excel commands as explained below.

If you want to start from 5th row and 'A' column then before starting the excel loop:

Open spreadsheet

Select Go to Cell Command under excel commands

Select Specific Cell radio button

Provide the value of the Specific Cell as'A5'(which denotes  5th row and 'A' column)

Reference:

How to write data to excel file in a loop starting from a specific cell

Title: Automation Anywhere Excel Loop


问:
How can I get an element from linked list with given index in java?
I'm learning about link-list in Java. and I'm want to write a method to give the value of node based on given index

I write a function, but it does not pass some of testcases, and I dont know why?. what is wrong with my logic?

//waypoint.java

```<code>public class Waypoint {
    int x  ;
    int y  ;
    public int getX()
    {
        return this.x;
    }
    public int getY()
    {
        return this.y;
    }
    public void setXY(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
</code>```

// TourElement.java

```<code>public class TourElement {
 private Waypoint points;
 private TourElement next;
  public void setWaypoint( Waypoint points)
 {
   this.points = points;
 }
  public void setTourElement(TourElement next)
  {
      this.next = next;
  }
 Waypoint getWaypoint()
 {
     return this.points;
 }

 TourElement getNext()
 {
     return this.next;
 }

int getNoOfWaypoints()//  return the number of waypoints in the list
{
    int count = 1;
    TourElement current = getNext();
    while(current.next != null)
    {
        count++;
        current = current.next;
        System.out.println(count);
    }
    return count;
}
</code>```

// here is method I'm strucking with:

```<code>Waypoint getWaypointAt(int index)
{
   int totalElement = getNoOfWaypoints();
   int count = 0;
   TourElement current = getNext();
   if(index < totalElement && index >= 0)
   {
       while (current.next != null)
      {
        if(count == index)
          {
              return getWaypoint();
          }
         count++;
          current = current.next;
         }

       }
   return null;
}
</code>```

//the testcase:
//case 1: pass

```<code>public void test0GetWaypointAt_First() {
        TourElement elem = createElementList(new int[][] {{0, 0}, {1, 1}, {2, 2}});
        Waypoint expected = createWaypoint(0, 0);
        assertArrayEquals(expected.toArray(), elem.getWaypointAt(0).toArray());
    }
</code>```

//case 2 and case 3: failed

```<code>public void test0GetWaypointAt_Snd() {
        TourElement elem = createElementList(new int[][] {{0, 0}, {1, 1}, {2, 2}});
        Waypoint expected = createWaypoint(1, 1);
        assertArrayEquals(expected.toArray(), elem.getWaypointAt(1).toArray());
    }

    @Test
    public void test0GetWaypointAt_Last() {
        TourElement elem = createElementList(new int[][] {{0, 0}, {1, 1}, {2, 2}});
        Waypoint expected = createWaypoint(2, 2);
        assertArrayEquals(expected.toArray(), elem.getWaypointAt(2).toArray());
    }
</code>```

I dont know the reason. Please help me. Thank you so much in advance

答:
Structure you've build with list seems ok, about your method getWaypointAt I see at least two problems:

First problem

   TourElement current = getNext();
```

<p><code>getNext()</code> is already the next element in your list, so you're skipping the first element all the time. It should be </p>

<pre class="lang-java prettyprint-override"><code>   TourElement current = this;
</code>```

Second problem

    return getWaypoint();
```

<p>It returns waypoint from the head all the time. Should be</p>

<pre class="lang-java prettyprint-override"><code>    return current.getWaypoint();
</code>```

Seems like your first test should fail as well. I don't see the way you build elements in createElementList, it could be a reason why it pass.

Body:
I'm learning about link-list in Java. and I'm want to write a method to give the value of node based on given index

I write a function, but it does not pass some of testcases, and I dont know why?. what is wrong with my logic?

//waypoint.java

public class Waypoint {
    int x  ;
    int y  ;
    public int getX()
    {
        return this.x;
    }
    public int getY()
    {
        return this.y;
    }
    public void setXY(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

// TourElement.java

public class TourElement {
 private Waypoint points;
 private TourElement next;
  public void setWaypoint( Waypoint points)
 {
   this.points = points;
 }
  public void setTourElement(TourElement next)
  {
      this.next = next;
  }
 Waypoint getWaypoint()
 {
     return this.points;
 }

 TourElement getNext()
 {
     return this.next;
 }

int getNoOfWaypoints()//  return the number of waypoints in the list
{
    int count = 1;
    TourElement current = getNext();
    while(current.next != null)
    {
        count++;
        current = current.next;
        System.out.println(count);
    }
    return count;
}

// here is method I'm strucking with:

Waypoint getWaypointAt(int index)
{
   int totalElement = getNoOfWaypoints();
   int count = 0;
   TourElement current = getNext();
   if(index < totalElement && index >= 0)
   {
       while (current.next != null)
      {
        if(count == index)
          {
              return getWaypoint();
          }
         count++;
          current = current.next;
         }

       }
   return null;
}

//the testcase:
//case 1: pass

public void test0GetWaypointAt_First() {
        TourElement elem = createElementList(new int[][] {{0, 0}, {1, 1}, {2, 2}});
        Waypoint expected = createWaypoint(0, 0);
        assertArrayEquals(expected.toArray(), elem.getWaypointAt(0).toArray());
    }

//case 2 and case 3: failed

public void test0GetWaypointAt_Snd() {
        TourElement elem = createElementList(new int[][] {{0, 0}, {1, 1}, {2, 2}});
        Waypoint expected = createWaypoint(1, 1);
        assertArrayEquals(expected.toArray(), elem.getWaypointAt(1).toArray());
    }

    @Test
    public void test0GetWaypointAt_Last() {
        TourElement elem = createElementList(new int[][] {{0, 0}, {1, 1}, {2, 2}});
        Waypoint expected = createWaypoint(2, 2);
        assertArrayEquals(expected.toArray(), elem.getWaypointAt(2).toArray());
    }

I dont know the reason. Please help me. Thank you so much in advance

Body:
Structure you've build with list seems ok, about your method getWaypointAt I see at least two problems:

First problem

   TourElement current = getNext();

getNext() is already the next element in your list, so you're skipping the first element all the time. It should be

   TourElement current = this;

Second problem

    return getWaypoint();

It returns waypoint from the head all the time. Should be

    return current.getWaypoint();

Seems like your first test should fail as well. I don't see the way you build elements in createElementList, it could be a reason why it pass.


问:
How do I add parallel computation to this example?
I have an algorithm for synchronous calculation of a certain integral on a given segment. I want to use the Control.Parallel library, or rather par :: a -> b -> b to add parallel computing to this algorithm.
How can I do this?

```<code>integrate :: (Double -> Double) -> Double -> Double -> Double
integrate f a b =
  let
    step     = (b - a) / 1000
    segments = [a + x * step | x <- [0..999]]
    area x   = step * (f x + f (x + step)) / 2
  in sum $ map area segments
</code>```

答:
From the looks of it you are trying to approximate an integral of a function f on the region from b to a using trapezoidal rule. You are right in trying to parallelize the code, but there are a couple of issues with the attempt:

First of all, you need a work stealing scheduler in order to get any benefit, since par is unlikely to give you a speedup

Secondly, the way it is implemented each intermediate point f(x) is computed twice, except for the border points f(a) and f(b)

Few moths ago I needed this functionality, so I added it the the massiv library: trapezoidRule, which conveninetly solves both of the above problems and avoids usage of lists.

Here is an out of the box solution, but it will not automatically parallelize the computation, since there is only one element of the array is being computed (it was designed to estimate integrals over many regions)

integrate' :: (Double -> Double) -> Double -> Double -> Double
integrate' f a b = trapezoidRule Seq P (\scale x -> f (scale x)) a d (Sz1 1) n ! 0
  where
    n = 1000
    d = b - a
```

<p>As a sanity check:</p>

```λ> integrate (\x -> x * x) 10 20 -- implementation from the question
2333.3335
λ> integrate' (\x -> x * x) 10 20
2333.3335
```

<p>Here is a solution that will do the automatic parallelization and will avoid redundant evaluation:</p>

```integrateA :: Int -> (Double -> Double) -> Double -> Double -> Double
integrateA n f a b =
  let step = (b - a) / fromIntegral n
      sz = size segments - 1
      segments = computeAs P $ A.map f (enumFromStepN Par a step (Sz (n + 1)))
      area y0 y1 = step * (y0 + y1) / 2
      areas = A.zipWith area (extract' 0 sz segments) (extract' 1 sz segments)
   in A.sum areas
```

<p>Because of list fusion, in case of your solution using lists, there will be no allocation, as such, for simple cases it will be very fast. In the above solution there is gonna be an array of size <code>n+1</code> allocated in order to promote sharing and avoid double function evaluation. There will also be extra cost encountered due to scheduling, since forking off threads does not come for free. But in the end for really expensive functions and very large <code>n</code> it is possible to get factor of ~x3 speed up on a quad core processor. </p>

<p>Below are some benchmarks of integrating gaussian function with <code>n = 100000</code>:</p>

```benchmarking Gaussian1D/list
time                 3.657 ms   (3.623 ms .. 3.687 ms)
                     0.999 R²   (0.998 R² .. 1.000 R²)
mean                 3.627 ms   (3.604 ms .. 3.658 ms)
std dev              80.50 μs   (63.62 μs .. 115.4 μs)

benchmarking Gaussian1D/array Seq
time                 3.408 ms   (3.304 ms .. 3.523 ms)
                     0.987 R²   (0.979 R² .. 0.994 R²)
mean                 3.670 ms   (3.578 ms .. 3.839 ms)
std dev              408.0 μs   (293.8 μs .. 627.6 μs)
variance introduced by outliers: 69% (severely inflated)

benchmarking Gaussian1D/array Par
time                 1.340 ms   (1.286 ms .. 1.393 ms)
                     0.980 R²   (0.967 R² .. 0.989 R²)
mean                 1.393 ms   (1.328 ms .. 1.485 ms)
std dev              263.3 μs   (160.1 μs .. 385.6 μs)
variance introduced by outliers: 90% (severely inflated)
```

<p>Side note suggestion. Switching to Simpson's rule will give you a better approximation. Implementation is available in <code>massiv</code> ;)</p>

<p><strong>Edit</strong></p>

<p>This is such a fun problem, that I decided to see what would it take to implement it without any array allocations. Here is what I came up with:</p>

<pre class="lang-hs prettyprint-override"><code>integrateS :: Int -> (Double -> Double) -> Double -> Double -> Double
integrateS n f a b =
  let step = (b - a) / fromIntegral n
      segments = A.map f (enumFromStepN Seq (a + step) step (Sz n))
      area y0 y1 = step * (y0 + y1) / 2
      sumWith (acc, y0) y1 =
        let acc' = acc + area y0 y1
         in acc' `seq` (acc', y1)
   in fst $ A.foldlS sumWith (0, f a) segments
</code>```

Above approach runs in constant memory, since the few arrays that do get created aren't real arrays backed by memory, but instead are delayed arrays. With a bit of trickery around fold accumulator we can share the results, thus avoiding double function evaluation. This results in astonishing speed up:

```<code>benchmarking Gaussian1D/array Seq no-alloc
time                 1.788 ms   (1.777 ms .. 1.799 ms)
                     1.000 R²   (0.999 R² .. 1.000 R²)
mean                 1.787 ms   (1.781 ms .. 1.795 ms)
std dev              23.85 μs   (17.19 μs .. 31.96 μs)
</code>```

The downside to the above approach is that it is not easily parallelizable, but not impossible. Embrace yourself, here is a monstrosity that can run on 8 capabilities (hardcoded and in my case 4 cores with hyperthreading):

```<code>-- | Will not produce correct results if `n` is not divisible by 8
integrateN8 :: Int -> (Double -> Double) -> Double -> Double -> Double
integrateN8 n f a b =
  let k = 8
      n' = n `div` k
      step = (b - a) / fromIntegral n
      segments =
        makeArrayR D (ParN (fromIntegral k)) (Sz1 k) $ \i ->
          let start = a + step * fromIntegral n' * fromIntegral i + step
           in (f start, A.map f (enumFromStepN Seq (start + step) step (Sz (n' - 1))))
      area y0 y1 = step * (y0 + y1) / 2
      sumWith (acc, y0) y1 =
        let acc' = acc + area y0 y1
         in acc' `seq` (acc', y1)
      partialResults =
        computeAs U $ A.map (\(y0, arr) -> (y0, A.foldlS sumWith (0, y0) arr)) segments
      combine (acc, y0) (y1, (acci, yn)) =
        let acc' = acc + acci + area y0 y1
         in acc' `seq` (acc', yn)
   in fst $ foldlS combine (0, f a) partialResults
</code>```

The only real array allocated is for keeping partialResults which has a total of 16 Double elements. Speed improvement is not as drastic, but nevertheless it is there:

```<code>benchmarking Gaussian1D/array Par no-alloc
time                 960.1 μs   (914.3 μs .. 1.020 ms)
                     0.968 R²   (0.944 R² .. 0.990 R²)
mean                 931.8 μs   (900.8 μs .. 976.3 μs)
std dev              129.2 μs   (84.20 μs .. 198.8 μs)
variance introduced by outliers: 84% (severely inflated)
</code>```

Body:
I have an algorithm for synchronous calculation of a certain integral on a given segment. I want to use the Control.Parallel library, or rather par :: a -> b -> b to add parallel computing to this algorithm.
How can I do this?

integrate :: (Double -> Double) -> Double -> Double -> Double
integrate f a b =
  let
    step     = (b - a) / 1000
    segments = [a + x * step | x <- [0..999]]
    area x   = step * (f x + f (x + step)) / 2
  in sum $ map area segments

Body:
From the looks of it you are trying to approximate an integral of a function f on the region from b to a using trapezoidal rule. You are right in trying to parallelize the code, but there are a couple of issues with the attempt:

First of all, you need a work stealing scheduler in order to get any benefit, since par is unlikely to give you a speedup

Secondly, the way it is implemented each intermediate point f(x) is computed twice, except for the border points f(a) and f(b)

Few moths ago I needed this functionality, so I added it the the massiv library: trapezoidRule, which conveninetly solves both of the above problems and avoids usage of lists.

Here is an out of the box solution, but it will not automatically parallelize the computation, since there is only one element of the array is being computed (it was designed to estimate integrals over many regions)

integrate' :: (Double -> Double) -> Double -> Double -> Double
integrate' f a b = trapezoidRule Seq P (\scale x -> f (scale x)) a d (Sz1 1) n ! 0
  where
    n = 1000
    d = b - a

As a sanity check:

λ> integrate (\x -> x * x) 10 20 -- implementation from the question
2333.3335
λ> integrate' (\x -> x * x) 10 20
2333.3335

Here is a solution that will do the automatic parallelization and will avoid redundant evaluation:

integrateA :: Int -> (Double -> Double) -> Double -> Double -> Double
integrateA n f a b =
  let step = (b - a) / fromIntegral n
      sz = size segments - 1
      segments = computeAs P $ A.map f (enumFromStepN Par a step (Sz (n + 1)))
      area y0 y1 = step * (y0 + y1) / 2
      areas = A.zipWith area (extract' 0 sz segments) (extract' 1 sz segments)
   in A.sum areas

Because of list fusion, in case of your solution using lists, there will be no allocation, as such, for simple cases it will be very fast. In the above solution there is gonna be an array of size n+1 allocated in order to promote sharing and avoid double function evaluation. There will also be extra cost encountered due to scheduling, since forking off threads does not come for free. But in the end for really expensive functions and very large n it is possible to get factor of ~x3 speed up on a quad core processor.

Below are some benchmarks of integrating gaussian function with n = 100000:

benchmarking Gaussian1D/list
time                 3.657 ms   (3.623 ms .. 3.687 ms)
                     0.999 R²   (0.998 R² .. 1.000 R²)
mean                 3.627 ms   (3.604 ms .. 3.658 ms)
std dev              80.50 μs   (63.62 μs .. 115.4 μs)

benchmarking Gaussian1D/array Seq
time                 3.408 ms   (3.304 ms .. 3.523 ms)
                     0.987 R²   (0.979 R² .. 0.994 R²)
mean                 3.670 ms   (3.578 ms .. 3.839 ms)
std dev              408.0 μs   (293.8 μs .. 627.6 μs)
variance introduced by outliers: 69% (severely inflated)

benchmarking Gaussian1D/array Par
time                 1.340 ms   (1.286 ms .. 1.393 ms)
                     0.980 R²   (0.967 R² .. 0.989 R²)
mean                 1.393 ms   (1.328 ms .. 1.485 ms)
std dev              263.3 μs   (160.1 μs .. 385.6 μs)
variance introduced by outliers: 90% (severely inflated)

Side note suggestion. Switching to Simpson's rule will give you a better approximation. Implementation is available in massiv ;)

Edit

This is such a fun problem, that I decided to see what would it take to implement it without any array allocations. Here is what I came up with:

integrateS :: Int -> (Double -> Double) -> Double -> Double -> Double
integrateS n f a b =
  let step = (b - a) / fromIntegral n
      segments = A.map f (enumFromStepN Seq (a + step) step (Sz n))
      area y0 y1 = step * (y0 + y1) / 2
      sumWith (acc, y0) y1 =
        let acc' = acc + area y0 y1
         in acc' `seq` (acc', y1)
   in fst $ A.foldlS sumWith (0, f a) segments

Above approach runs in constant memory, since the few arrays that do get created aren't real arrays backed by memory, but instead are delayed arrays. With a bit of trickery around fold accumulator we can share the results, thus avoiding double function evaluation. This results in astonishing speed up:

benchmarking Gaussian1D/array Seq no-alloc
time                 1.788 ms   (1.777 ms .. 1.799 ms)
                     1.000 R²   (0.999 R² .. 1.000 R²)
mean                 1.787 ms   (1.781 ms .. 1.795 ms)
std dev              23.85 μs   (17.19 μs .. 31.96 μs)

The downside to the above approach is that it is not easily parallelizable, but not impossible. Embrace yourself, here is a monstrosity that can run on 8 capabilities (hardcoded and in my case 4 cores with hyperthreading):

-- | Will not produce correct results if `n` is not divisible by 8
integrateN8 :: Int -> (Double -> Double) -> Double -> Double -> Double
integrateN8 n f a b =
  let k = 8
      n' = n `div` k
      step = (b - a) / fromIntegral n
      segments =
        makeArrayR D (ParN (fromIntegral k)) (Sz1 k) $ \i ->
          let start = a + step * fromIntegral n' * fromIntegral i + step
           in (f start, A.map f (enumFromStepN Seq (start + step) step (Sz (n' - 1))))
      area y0 y1 = step * (y0 + y1) / 2
      sumWith (acc, y0) y1 =
        let acc' = acc + area y0 y1
         in acc' `seq` (acc', y1)
      partialResults =
        computeAs U $ A.map (\(y0, arr) -> (y0, A.foldlS sumWith (0, y0) arr)) segments
      combine (acc, y0) (y1, (acci, yn)) =
        let acc' = acc + acci + area y0 y1
         in acc' `seq` (acc', yn)
   in fst $ foldlS combine (0, f a) partialResults

The only real array allocated is for keeping partialResults which has a total of 16 Double elements. Speed improvement is not as drastic, but nevertheless it is there:

benchmarking Gaussian1D/array Par no-alloc
time                 960.1 μs   (914.3 μs .. 1.020 ms)
                     0.968 R²   (0.944 R² .. 0.990 R²)
mean                 931.8 μs   (900.8 μs .. 976.3 μs)
std dev              129.2 μs   (84.20 μs .. 198.8 μs)
variance introduced by outliers: 84% (severely inflated)


问:
Converting a list to a "two or more objects" argument in R
I have to call a function in R that takes "2 or more objects" as an input, so the function definition is:

function(..., all = TRUE, <other named parameters>)

where ... is defined as 2 or more objects

The issue is I have is that my objects are in a list, and I am working with a different number of objects according to what I want to do. So if my list has 3 elements for example I would have to do:

function(list[[1]], list [[2]], list[[3]])

How can I do that generically, regardless of the number of element in my list ?

答:
You can use do.call, as that takes a list of arguments and applies them on function. Eg for rbind :

```<code>X <- list(A=1:3,B=4:6,C=7:9)
do.call(rbind,X)

  [,1] [,2] [,3]
A    1    2    3
B    4    5    6
C    7    8    9
</code>```

Mind you, if you need extra arguments, you should add them to the list as well. See eg :

```<code>X <- list(A=list(A1=1:2,A2=3:4),B=list(B1=5:6,B2=7:8))

do.call(c,X)      # Returns a list
do.call(c,X,recursive=TRUE)  # Gives an error
do.call(c,c(X,list(recursive=TRUE)))

A.A11 A.A12 A.A21 A.A22 B.B11 B.B12 B.B21 B.B22
    1     2     3     4     5     6     7     8
</code>```

Body:
You can use do.call, as that takes a list of arguments and applies them on function. Eg for rbind :

X <- list(A=1:3,B=4:6,C=7:9)
do.call(rbind,X)

  [,1] [,2] [,3]
A    1    2    3
B    4    5    6
C    7    8    9

Mind you, if you need extra arguments, you should add them to the list as well. See eg :

X <- list(A=list(A1=1:2,A2=3:4),B=list(B1=5:6,B2=7:8))

do.call(c,X)      # Returns a list
do.call(c,X,recursive=TRUE)  # Gives an error
do.call(c,c(X,list(recursive=TRUE)))

A.A11 A.A12 A.A21 A.A22 B.B11 B.B12 B.B21 B.B22
    1     2     3     4     5     6     7     8


问:
Deploy Azure Function dynamically enabled/disabled using ARM template
I have a class library, timer-based Azure Function that is deployed using an ARM template.  Everything works fine except I would like a slightly different behavior based on the target environment. When deploying to a test environment I would like the function to be initially disabled but in production it should always be enabled. Is this possible?

My current workaround is to have an app setting that tells the function to immediately exit when set to a specific value. However, this seems like a poor solution, especially since the timer-triggered function is executed quite frequently. To solve this I manually disables the function using the following switch in the Azure portal:

Is there perhaps possible to specify the desired state of this switch from the ARM template?

答:
Expanding on Joy's answer, which worked like a charm!

For the benefit of others, the "name" property above is composed like so:

```<code>AzureWebJobs.<YouFunctionName>.Disabled
</code>```

where <YouFunctionName> is specified in your template.json here:

```<code>{
    "resources": [
        "name": "<YourFunctionName>",
        "type": "functions",
         "properties": {
              "config": {
                   "bindings": [
                       {
                      ...
                        }
                    ]
                }
           }
       ]
}
</code>```

Body:
Expanding on Joy's answer, which worked like a charm!

For the benefit of others, the "name" property above is composed like so:

AzureWebJobs.<YouFunctionName>.Disabled

where <YouFunctionName> is specified in your template.json here:

{
    "resources": [
        "name": "<YourFunctionName>",
        "type": "functions",
         "properties": {
              "config": {
                   "bindings": [
                       {
                      ...
                        }
                    ]
                }
           }
       ]
}


问:
Python: Best way to add to sys.path relative to the current running script
I have a directory full of scripts (let's say project/bin). I also have a library located in project/lib and want the scripts to automatically load it. This is what I normally use at the top of each script:

```<code>#!/usr/bin/python
from os.path import dirname, realpath, sep, pardir
import sys
sys.path.append(dirname(realpath(__file__)) + sep + pardir + sep + "lib")

# ... now the real code
import mylib
</code>```

This is kind of cumbersome, ugly, and has to be pasted at the beginning of every file. Is there a better way to do this?

Really what I'm hoping for is something as smooth as this:

```<code>#!/usr/bin/python
import sys.path
from os.path import pardir, sep
sys.path.append_relative(pardir + sep + "lib")

import mylib
</code>```

Or even better, something that wouldn't break when my editor (or someone else who has commit access) decides to reorder the imports as part of its clean-up process:

```<code>#!/usr/bin/python --relpath_append ../lib
import mylib
</code>```

That wouldn't port directly to non-posix platforms, but it would keep things clean.

答:
You can run the script with python -m from the relevant root dir. And pass the  "modules path" as argument.

Example: $ python -m module.sub_module.main  # Notice there is no '.py' at the end.

Another example:

```<code>$ tree  # Given this file structure
.
├── bar
│   ├── __init__.py
│   └── mod.py
└── foo
    ├── __init__.py
    └── main.py

$ cat foo/main.py
from bar.mod import print1
print1()

$ cat bar/mod.py
def print1():
    print('In bar/mod.py')

$ python foo/main.py  # This gives an error
Traceback (most recent call last):
  File "foo/main.py", line 1, in <module>
    from bar.mod import print1
ImportError: No module named bar.mod

$ python -m foo.main  # But this succeeds
In bar/mod.py
</code>```

Body:
I have a directory full of scripts (let's say project/bin). I also have a library located in project/lib and want the scripts to automatically load it. This is what I normally use at the top of each script:

#!/usr/bin/python
from os.path import dirname, realpath, sep, pardir
import sys
sys.path.append(dirname(realpath(__file__)) + sep + pardir + sep + "lib")

# ... now the real code
import mylib

This is kind of cumbersome, ugly, and has to be pasted at the beginning of every file. Is there a better way to do this?

Really what I'm hoping for is something as smooth as this:

#!/usr/bin/python
import sys.path
from os.path import pardir, sep
sys.path.append_relative(pardir + sep + "lib")

import mylib

Or even better, something that wouldn't break when my editor (or someone else who has commit access) decides to reorder the imports as part of its clean-up process:

#!/usr/bin/python --relpath_append ../lib
import mylib

That wouldn't port directly to non-posix platforms, but it would keep things clean.

Body:
You can run the script with python -m from the relevant root dir. And pass the  "modules path" as argument.

Example: $ python -m module.sub_module.main  # Notice there is no '.py' at the end.

Another example:

$ tree  # Given this file structure
.
├── bar
│   ├── __init__.py
│   └── mod.py
└── foo
    ├── __init__.py
    └── main.py

$ cat foo/main.py
from bar.mod import print1
print1()

$ cat bar/mod.py
def print1():
    print('In bar/mod.py')

$ python foo/main.py  # This gives an error
Traceback (most recent call last):
  File "foo/main.py", line 1, in <module>
    from bar.mod import print1
ImportError: No module named bar.mod

$ python -m foo.main  # But this succeeds
In bar/mod.py


问:
Guice injector in JUnit tests
Using Guice, is it a good practice to get a new injector in each JUnit test class, as each test class should be independant?</p>

答:
I think using DI will make unit test code more simple, I always Use DI for unit test and also for integration test.

Without DI everything feels hard to code. Either using Guice Inject or Spring Autowired. like my test code bellow:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/application-context.xml")
public class When_inexists_user_disabled {
    @Autowired
    IRegistrationService registrationService;

    private int userId;

    @Before
    public void setUp() {
        Logger.getRootLogger().setLevel(Level.INFO);
        Logger.getLogger("org.springframework").setLevel(Level.WARN);
        BasicConfigurator.configure();

        userId = 999;
    }

    @Test(expected=UserNotFoundException.class)
    public void user_should_have_disabled() throws UserNotFoundException {
        registrationService.disable(userId);
    }

}
</code>```

Title: Guice injector in JUnit tests

Body:
I think using DI will make unit test code more simple, I always Use DI for unit test and also for integration test.

Without DI everything feels hard to code. Either using Guice Inject or Spring Autowired. like my test code bellow:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/application-context.xml")
public class When_inexists_user_disabled {
    @Autowired
    IRegistrationService registrationService;

    private int userId;

    @Before
    public void setUp() {
        Logger.getRootLogger().setLevel(Level.INFO);
        Logger.getLogger("org.springframework").setLevel(Level.WARN);
        BasicConfigurator.configure();

        userId = 999;
    }

    @Test(expected=UserNotFoundException.class)
    public void user_should_have_disabled() throws UserNotFoundException {
        registrationService.disable(userId);
    }

}


问:
Passport.js Google strategy is not working with the React application
I am using passport.js google strategy for user authentication.
I am using OAUTH2.

When I launch my server and hit API through browser, it launches google signin page.
But when I hit API from react front-end, it never launches the googles signin page.

Please find below server code,

```<code>const bodyParser = require('body-parser');
const express = require('express');
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
const app = express();
const cors = require('cors');

app.use(passport.initialize());
app.use(passport.session());
app.use(cors());

app.use((req, res, next) => {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader(
        "Access-Control-Allow-Methods",
        "GET, POST, OPTIONS, PUT, PATCH, DELETE"
    );
    res.setHeader(
        "Access-Control-Allow-Headers",
        "X-Requested-With,content-type"
    );
    res.setHeader("Access-Control-Allow-Credentials", true);
    next();
});

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

passport.use('google', new GoogleStrategy({
    clientID: "clientID", -- my client id
    clientSecret: "clientSecret", -- my clientsecret
    callbackURL: "callbackURL" -- url
},
    function (accessToken, refreshToken, profile, done) {
        // User.findOrCreate({ googleId: profile.id }, function (err, user) {
        //  console.log(err,user);
        //   return done(err, user);
        // });
        console.log(profile);
        return done(err, user);
    }
));

app.get('/googleauth',
    passport.authenticate('google', { scope: ['https://www.googleapis.com/auth/plus.login'] }));

passport.serializeUser(function (user, done) {
    done(null, user);
})

passport.deserializeUser(function (user, done) {
    done(null, user);
})

app.listen(4000, () => {
    console.log("REST server started on port 4000");
});
</code>```

Axios call from react code,

```<code>  handleJGoogleLogin(e) {
    e.preventDefault();
    var current = this;
    axios.get('http://localhost:4000/googleauth')
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
  }
</code>```

I am stuck here, looking for some help.

Thanks in advance

答:
A few things under your passport.use add in another parameter

```<code>   passport.use('google', new GoogleStrategy({
      clientID: "clientID", -- my client id
      clientSecret: "clientSecret", -- my clientsecret
      callbackURL: "callbackURL" -- url
      proxy: true
     },

   change:
          const GoogleStrategy = require('passport-google-
    auth').OAuth2Strategy;
     to:
         const GoogleStrategy = require('passport-google-oauth20').Strategy;

      add in a second scope of profile
        app.get('/googleauth',
               passport.authenticate('google', { scope:
               ['https://www.googleapis.com/auth/plus.login','profile'] }));
</code>```

Can you post your react code?

Body:
I am using passport.js google strategy for user authentication.
I am using OAUTH2.

When I launch my server and hit API through browser, it launches google signin page.
But when I hit API from react front-end, it never launches the googles signin page.

Please find below server code,

const bodyParser = require('body-parser');
const express = require('express');
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
const app = express();
const cors = require('cors');

app.use(passport.initialize());
app.use(passport.session());
app.use(cors());

app.use((req, res, next) => {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader(
        "Access-Control-Allow-Methods",
        "GET, POST, OPTIONS, PUT, PATCH, DELETE"
    );
    res.setHeader(
        "Access-Control-Allow-Headers",
        "X-Requested-With,content-type"
    );
    res.setHeader("Access-Control-Allow-Credentials", true);
    next();
});

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

passport.use('google', new GoogleStrategy({
    clientID: "clientID", -- my client id
    clientSecret: "clientSecret", -- my clientsecret
    callbackURL: "callbackURL" -- url
},
    function (accessToken, refreshToken, profile, done) {
        // User.findOrCreate({ googleId: profile.id }, function (err, user) {
        //  console.log(err,user);
        //   return done(err, user);
        // });
        console.log(profile);
        return done(err, user);
    }
));

app.get('/googleauth',
    passport.authenticate('google', { scope: ['https://www.googleapis.com/auth/plus.login'] }));

passport.serializeUser(function (user, done) {
    done(null, user);
})

passport.deserializeUser(function (user, done) {
    done(null, user);
})

app.listen(4000, () => {
    console.log("REST server started on port 4000");
});

Axios call from react code,

  handleJGoogleLogin(e) {
    e.preventDefault();
    var current = this;
    axios.get('http://localhost:4000/googleauth')
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
  }

I am stuck here, looking for some help.

Thanks in advance

Body:
A few things under your passport.use add in another parameter

   passport.use('google', new GoogleStrategy({
      clientID: "clientID", -- my client id
      clientSecret: "clientSecret", -- my clientsecret
      callbackURL: "callbackURL" -- url
      proxy: true
     },

   change:
          const GoogleStrategy = require('passport-google-
    auth').OAuth2Strategy;
     to:
         const GoogleStrategy = require('passport-google-oauth20').Strategy;

      add in a second scope of profile
        app.get('/googleauth',
               passport.authenticate('google', { scope:
               ['https://www.googleapis.com/auth/plus.login','profile'] }));

Can you post your react code?


问:
Monitoring Services And Characteristics on React-Native
I have two questions for you about my code :)

I'm creating an android to connect to ble device. I'm using ble-plx library.

```<code>import React, {Component} from 'react';
import { Platform, View, Text } from 'react-native';
import { BleManager } from 'react-native-ble-plx';

export default class Main extends Component {
  constructor() {
    super();
    this.manager = new BleManager()
    this.state = {info: "", values: {}}
    this.deviceprefix = "Device";
    this.devicesuffix_dx = "DX";
    this.sensors = {
      "0000f0fd-0001-0008-0000-0805f9b34fb0" : "Acc+Gyr+Mg",
      "0000f0f4-0000-1000-8000-00805f9b34fb" : "Pressure"
    }

    }

  serviceUUID() {
      return "0000f0f0-0000-1000-8000-00805f9b34fb"
    }

  notifyUUID(num) {
      return num
    }

  model_dx (model) {
      return this.deviceprefix + model + this.devicesuffix_dx
    }

  info(message) {
      this.setState({info: message})
    }

  error(message) {
      this.setState({info: "ERROR: " + message})
    }

  updateValue(key, value) {
      this.setState({values: {...this.state.values, [key]: value}})
    }

  componentWillMount(){
    const subscription = this.manager.onStateChange((state) => {
      if (state === 'PoweredOn') {
        this.scanAndConnect();
        subscription.remove();
      }
    }, true);
  }
  async requestPermission() {
    try {
      const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);

      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        this.setState({permissionStatus:'granted'});
      }else if(granted === PermissionsAndroid.RESULTS.DENIED) {
        this.setState({permissionStatus:'denied'});
      }else{

      }
    } catch (err) {
      console.error(err)
    }
  }

    scanAndConnect(){
      this.manager.startDeviceScan(null, null, (error, device) => {
        if (error) {

          return
        }

        let model = '0030';
        if (device.name == this.model_dx(model)  ) {
          this.manager.stopDeviceScan();
          device.connect()
            .then((device) => {
              this.info("Discovering services and characteristics ")
              return device.discoverAllServicesAndCharacteristics()
            })
           .then((device) => {
             this.info("SetupNotification")
             return this.setupNotifications(device)
           })
            .catch((error) => {
              this.error(error.message)
            });
        }

      });
    }

    async setupNotifications(device) {
        for (const id in this.sensors) {

          const service = this.serviceUUID(id)
          const characteristicN = this.notifyUUID(id)

          device.monitorCharacteristicForService(service, characteristicN, (error, characteristic) => {
            if (error) {
              this.error(error.message)
              return
            }
            this.updateValue(characteristic.uuid, characteristic.value)
          })
        }
      }

    render() {
       return (
         <View>
           <Text>{this.state.info}</Text>
           {Object.keys(this.sensors).map((key) => {
          return <Text key={key}>
                   {this.sensors[key] + ": " + (this.state.values[this.notifyUUID(key)] || "-")}
                 </Text>
        })}
         </View>
       )
     }

}
</code>```

I have two question for you:

1) The monitoring give me values like:

For example in the case of "Pressure" the value: "ZABIAGYAZwBoAA=="
I should receive a number not string, I have tried to convert Text into Binary and then Binary to Decimal. How can I do, in your opinion in the app?

2)
I print the values using:

```<code><Text>{this.state.info}</Text>
               {Object.keys(this.sensors).map((key) => {
              return <Text key={key}>
                       {this.sensors[key] + ": " + (this.state.values[this.notifyUUID(key)] || "-")}
                     </Text>
</code>```

But If I wanted to access the "pressure" value directly, how could I do it? To be clear if I wanted to, for example, passing the value that remembers me pressure on another page?
Thank you all for the support!

答:
install this library:

npm install --save base-64

import it in your Main class:

import base64 from 'base-64'

then in your updateValue method:

```<code>updateValue(key, value) {
    const readebleData = base64.decode(value);

    this.setState({values: {...this.state.values, [key]: readebleData}})
}
</code>```

If you want to pass the readableData to another class you should use library like react-redux or passing the variable during the transition to the new class, for example using react-native-router-flux:

Actions.pageKey({ data: readebleData })

Body:
I have two questions for you about my code :)

I'm creating an android to connect to ble device. I'm using ble-plx library.

import React, {Component} from 'react';
import { Platform, View, Text } from 'react-native';
import { BleManager } from 'react-native-ble-plx';

export default class Main extends Component {
  constructor() {
    super();
    this.manager = new BleManager()
    this.state = {info: "", values: {}}
    this.deviceprefix = "Device";
    this.devicesuffix_dx = "DX";
    this.sensors = {
      "0000f0fd-0001-0008-0000-0805f9b34fb0" : "Acc+Gyr+Mg",
      "0000f0f4-0000-1000-8000-00805f9b34fb" : "Pressure"
    }

    }

  serviceUUID() {
      return "0000f0f0-0000-1000-8000-00805f9b34fb"
    }

  notifyUUID(num) {
      return num
    }

  model_dx (model) {
      return this.deviceprefix + model + this.devicesuffix_dx
    }

  info(message) {
      this.setState({info: message})
    }

  error(message) {
      this.setState({info: "ERROR: " + message})
    }

  updateValue(key, value) {
      this.setState({values: {...this.state.values, [key]: value}})
    }

  componentWillMount(){
    const subscription = this.manager.onStateChange((state) => {
      if (state === 'PoweredOn') {
        this.scanAndConnect();
        subscription.remove();
      }
    }, true);
  }
  async requestPermission() {
    try {
      const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);

      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        this.setState({permissionStatus:'granted'});
      }else if(granted === PermissionsAndroid.RESULTS.DENIED) {
        this.setState({permissionStatus:'denied'});
      }else{

      }
    } catch (err) {
      console.error(err)
    }
  }

    scanAndConnect(){
      this.manager.startDeviceScan(null, null, (error, device) => {
        if (error) {

          return
        }

        let model = '0030';
        if (device.name == this.model_dx(model)  ) {
          this.manager.stopDeviceScan();
          device.connect()
            .then((device) => {
              this.info("Discovering services and characteristics ")
              return device.discoverAllServicesAndCharacteristics()
            })
           .then((device) => {
             this.info("SetupNotification")
             return this.setupNotifications(device)
           })
            .catch((error) => {
              this.error(error.message)
            });
        }

      });
    }

    async setupNotifications(device) {
        for (const id in this.sensors) {

          const service = this.serviceUUID(id)
          const characteristicN = this.notifyUUID(id)

          device.monitorCharacteristicForService(service, characteristicN, (error, characteristic) => {
            if (error) {
              this.error(error.message)
              return
            }
            this.updateValue(characteristic.uuid, characteristic.value)
          })
        }
      }

    render() {
       return (
         <View>
           <Text>{this.state.info}</Text>
           {Object.keys(this.sensors).map((key) => {
          return <Text key={key}>
                   {this.sensors[key] + ": " + (this.state.values[this.notifyUUID(key)] || "-")}
                 </Text>
        })}
         </View>
       )
     }

}

I have two question for you:

1) The monitoring give me values like:

For example in the case of "Pressure" the value: "ZABIAGYAZwBoAA=="
I should receive a number not string, I have tried to convert Text into Binary and then Binary to Decimal. How can I do, in your opinion in the app?

2)
I print the values using:

<Text>{this.state.info}</Text>
               {Object.keys(this.sensors).map((key) => {
              return <Text key={key}>
                       {this.sensors[key] + ": " + (this.state.values[this.notifyUUID(key)] || "-")}
                     </Text>

But If I wanted to access the "pressure" value directly, how could I do it? To be clear if I wanted to, for example, passing the value that remembers me pressure on another page?
Thank you all for the support!

Body:
install this library:

npm install --save base-64

import it in your Main class:

import base64 from 'base-64'

then in your updateValue method:

updateValue(key, value) {
    const readebleData = base64.decode(value);

    this.setState({values: {...this.state.values, [key]: readebleData}})
}

If you want to pass the readableData to another class you should use library like react-redux or passing the variable during the transition to the new class, for example using react-native-router-flux:

Actions.pageKey({ data: readebleData })


问:
socket connecting in main but not inside a function
i am trying to create a socket, connect method is working fine (i.e returning 0 if called from the main function) but not working fine(i.e return a non zero value) if called from some function other than main why? thanks in advance</p>

```<code>#include<iostream>
#include<stdlib.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>//the new file.
#include<unistd.h>//for using the sleep function.
#include<string.h>
using namespace std;
//char request1[]="GET /index.html HTTP/1.1\r\n\r\n";
void T_occupy(char* request,int n,struct sockaddr_in* server_address,int time_slot){
    int my_socket;
    while(1){
            my_socket=socket(AF_INET,SOCK_STREAM,0);
            int connection_status=connect(my_socket,(struct sockaddr*)&server_address,sizeof(server_address));
            if(connection_status){
                    cout<<"error in establising the connection \n";
                    return;
            }
            int i;
            for(i=0;i<n;i++){
                    char temp=request[i];
                    send(my_socket,&temp,sizeof(temp),0);
                    sleep(time_slot);
            }
            close(my_socket);
    }

}
int main(int argc,char* argv[]){
    //first we will do thigns with only one thread.
    char* address;
    char* msg="GET   /Iamabouttoendyourstorybyhackingyouandyouwillnotbeabletoserveanyone.html HTTP/1.1\r\n\r\n";
    address=argv[1];
    struct sockaddr_in server_address;
    server_address.sin_family=AF_INET;
    server_address.sin_port=htons(80);
    inet_aton(address,(struct in_addr*)&server_address.sin_addr.s_addr);
    T_occupy(msg,strlen(msg),&server_address,7);
    return 0;
}
</code>```

答:
You're passing &server_address, which has type struct sockaddr_in ** to connect which is expecting a struct sockaddr_in * casted to a struct sockaddr *.  You're also passing sizeof(server_address) which is the size of the pointer, not the size of the struct.

Remove the unneeded & in the second parameter and add * to the last:

```<code>int connection_status=connect(my_socket,(struct sockaddr*)server_address,sizeof(*server_address));
</code>```

Body:
i am trying to create a socket, connect method is working fine (i.e returning 0 if called from the main function) but not working fine(i.e return a non zero value) if called from some function other than main why? thanks in advance

#include<iostream>
#include<stdlib.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>//the new file.
#include<unistd.h>//for using the sleep function.
#include<string.h>
using namespace std;
//char request1[]="GET /index.html HTTP/1.1\r\n\r\n";
void T_occupy(char* request,int n,struct sockaddr_in* server_address,int time_slot){
    int my_socket;
    while(1){
            my_socket=socket(AF_INET,SOCK_STREAM,0);
            int connection_status=connect(my_socket,(struct sockaddr*)&server_address,sizeof(server_address));
            if(connection_status){
                    cout<<"error in establising the connection \n";
                    return;
            }
            int i;
            for(i=0;i<n;i++){
                    char temp=request[i];
                    send(my_socket,&temp,sizeof(temp),0);
                    sleep(time_slot);
            }
            close(my_socket);
    }

}
int main(int argc,char* argv[]){
    //first we will do thigns with only one thread.
    char* address;
    char* msg="GET   /Iamabouttoendyourstorybyhackingyouandyouwillnotbeabletoserveanyone.html HTTP/1.1\r\n\r\n";
    address=argv[1];
    struct sockaddr_in server_address;
    server_address.sin_family=AF_INET;
    server_address.sin_port=htons(80);
    inet_aton(address,(struct in_addr*)&server_address.sin_addr.s_addr);
    T_occupy(msg,strlen(msg),&server_address,7);
    return 0;
}

Body:
You're passing &server_address, which has type struct sockaddr_in ** to connect which is expecting a struct sockaddr_in * casted to a struct sockaddr *.  You're also passing sizeof(server_address) which is the size of the pointer, not the size of the struct.

Remove the unneeded & in the second parameter and add * to the last:

int connection_status=connect(my_socket,(struct sockaddr*)server_address,sizeof(*server_address));


问:
I can't restore the original image from a Base30 text jSignature representation
I am trying to implement the jSignature library in my application but I can't make it work, the actual problem is trying to recreate the original image from the base30 text. In order to do it I draw something in their demo, take the base30 text and paste it in my app but the generated image has almost nothing to do with the original one. The code of my sample app is this:

```<code>    private void BtnConvertToSVG_Click(object sender, EventArgs e)
    {
        convertFromBase30();
    }

    private void convertFromBase30()
    {
        try
        {
            jSignature.Tools.Base30Converter Base30 = new jSignature.Tools.Base30Converter();
            String base30Text = tbBase30Text.Text.ToString();
            int[][][] arrBase30 = Base30.Base30ToNative(base30Text);
            String strSVG = jSignature.Tools.SVGConverter.ToSVG(arrBase30);
            tbSVG.Text = strSVG;
            MemoryStream s = new MemoryStream(Encoding.ASCII.GetBytes(strSVG));
            SvgDocument mySVG = SvgDocument.Open<SvgDocument>(s, null);
            var tempStream = new System.IO.MemoryStream();
            mySVG.Draw().Save(tempStream, System.Drawing.Imaging.ImageFormat.Png);
            System.Drawing.Image img = System.Drawing.Image.FromStream(tempStream);
            pbImage.Image = img;
        }
        catch (Exception ex)
        {
            MessageBox.Show(String.Format("{0}", ex.Message));
        }
    }
</code>```

It is a Windows Forms application with two TextBox:

tbBase30Text: Here I introduce the base30 text

tbSVG: Where the app writes the SVG image code

A Button (btnConvertToSVG) and a PictureBox where I print the generated image. It makes use of the libraries included in the jSignature project

If I draw an SO image in their demo it gives me the next result

Pasting the base30 code in my application gives me the next result:

I don't understand why but the only common thing between both signatures are the number of lines.

There are some forks of this library, the brinley's one (last updated) and the willowsystems's are which I tried with no success.

答:
I finally solved it thanks to another SO question talking about the same problem. The error was in the library to convert to SVG included in the jSignature project.

All the String.Format ignore the Culture when converting the String adding errors to the final result, you can fix it by adding CultureInfo.InvariantCulture to all of them at the beginning

```<code>String.Format(CultureInfo.InvariantCulture, ...)
</code>```

Body:
I am trying to implement the jSignature library in my application but I can't make it work, the actual problem is trying to recreate the original image from the base30 text. In order to do it I draw something in their demo, take the base30 text and paste it in my app but the generated image has almost nothing to do with the original one. The code of my sample app is this:

    private void BtnConvertToSVG_Click(object sender, EventArgs e)
    {
        convertFromBase30();
    }

    private void convertFromBase30()
    {
        try
        {
            jSignature.Tools.Base30Converter Base30 = new jSignature.Tools.Base30Converter();
            String base30Text = tbBase30Text.Text.ToString();
            int[][][] arrBase30 = Base30.Base30ToNative(base30Text);
            String strSVG = jSignature.Tools.SVGConverter.ToSVG(arrBase30);
            tbSVG.Text = strSVG;
            MemoryStream s = new MemoryStream(Encoding.ASCII.GetBytes(strSVG));
            SvgDocument mySVG = SvgDocument.Open<SvgDocument>(s, null);
            var tempStream = new System.IO.MemoryStream();
            mySVG.Draw().Save(tempStream, System.Drawing.Imaging.ImageFormat.Png);
            System.Drawing.Image img = System.Drawing.Image.FromStream(tempStream);
            pbImage.Image = img;
        }
        catch (Exception ex)
        {
            MessageBox.Show(String.Format("{0}", ex.Message));
        }
    }

It is a Windows Forms application with two TextBox:

tbBase30Text: Here I introduce the base30 text

tbSVG: Where the app writes the SVG image code

A Button (btnConvertToSVG) and a PictureBox where I print the generated image. It makes use of the libraries included in the jSignature project

If I draw an SO image in their demo it gives me the next result

Pasting the base30 code in my application gives me the next result:

I don't understand why but the only common thing between both signatures are the number of lines.

There are some forks of this library, the brinley's one (last updated) and the willowsystems's are which I tried with no success.

Body:
I finally solved it thanks to another SO question talking about the same problem. The error was in the library to convert to SVG included in the jSignature project.

All the String.Format ignore the Culture when converting the String adding errors to the final result, you can fix it by adding CultureInfo.InvariantCulture to all of them at the beginning

String.Format(CultureInfo.InvariantCulture, ...)


问:
Restore deleted git file that had some changes
I made some changed to a file and by mistake deleted that file. I have not yet committed those changes. I want to undelete that file but keep the changes that I made. How do I do that using git?</p>

答:
Using git, unfortunately you can't, since the changes were never commited.

The alternative you could hope for is to check, if any, the local history of changes in the editor you happen to work with.


问:
Calculation in C
I would like to make a simple calculation in C.
Nverthless, there might be a problem in my code with the "resultat"...
Was trying to do the exemple given in OpenClassroom, at the following link : https://openclassrooms.com/fr/courses/19980-apprenez-a-programmer-en-c/14337-une-bete-de-calcul

Here is my code in Repl.
I think the teacher didn't put everything for it to work properly, so I've tried to modificate it by puting the two first lines : https://repl.it/@LunaShivaya/SuburbanThornyDebugmonitor

Thanks in advance for your ideas :)
Sakura.

答:
You need to declare it inside a main function.

```<code>#include <stdio.h>

int main()
{
  int resultat = 0;

  resultat = 5 + 3;

  printf("5 + 3 =  %d", resultat);

  return 0;
}
</code>```

Libraries are used to load pre-defined variables and functions. In this case, you are using printf, which is pre-defined in the library stdio.h.

Title: Calculation in C

Body:
You need to declare it inside a main function.

#include <stdio.h>

int main()
{
  int resultat = 0;

  resultat = 5 + 3;

  printf("5 + 3 =  %d", resultat);

  return 0;
}

Libraries are used to load pre-defined variables and functions. In this case, you are using printf, which is pre-defined in the library stdio.h.


问:
How to automate disparate technology process in Azure
I have a weekly process that I wish to automate in Azure. The overall process consists of about 5 distinct sub-processes. Total execution time is approximately 8  hours. The sub-process technologies include:

A third party data loader program that runs on a Windows VM in Azure. This program is able to send an email upon completion. This process then needs to trigger...

T-SQL scripts running on a Windows VM in Azure which upon completion needs to trigger...

SSIS jobs running on a Windows VM in Azure which upon completion needs to trigger...

A c# application that runs on a Windows VM in Azure which upon completion needs to trigger...

Python code running on a linux VM in Azure.

My question is: what Azure technology or technologies (e.g. automation runbook, logic app) could be used to stitch this thing together to give me back my weekend? Thank you in advance.

答:
This might be solvable with Durable Functions - and the External Events pattern: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-external-events

A timer-trigerded Function weekly kicks off an orchestrator Function

The orchestrator starts your VM (or a docker container etc.) that contains your data loader thing and injects a callback URL.

The orchestrator now waits for an external event (see link above)

The callback-URL points to another Azure Function that raises the event to continue the orchestrator: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-external-events#send-events

the orchestrator starts the next external task with the same pattern...


问:
Showing loading with Lottie with AsyncTask
I am supposed to use the Android standard for showing loading in my app. I see this awesome library's in Lottie https://lottiefiles.com/890-loading-animation. Can someone help me understand how to use it in Asynctask in Android and on an overlay in Android?

I was able to do start and stop animation.

答:
```<code> new AsyncTask<String, String, String>() {
    /**
     * Before starting background set visibility VISIBLE to Lottie anim.
     * */
    @Override
    protected void onPreExecute() {
    }

    @Override
    protected String doInBackground(String... params) {
        // TODO fetch url data do bg process.
        return null;
    }

    /**
     * Update visibility GONE to Lottie anim..
     */
    protected void onPostExecute(String result) {
           // NO NEED to use activity.runOnUiThread(), code execute here under UI thread.

             // Updating parsed JSON data into ListView
             final List data = new Gson().fromJson(result);
            // updating listview
            ((ListActivity) activity).updateUI(data);
    }

};
</code>```

<p>}</p>

Body:
 new AsyncTask<String, String, String>() {
    /**
     * Before starting background set visibility VISIBLE to Lottie anim.
     * */
    @Override
    protected void onPreExecute() {
    }

    @Override
    protected String doInBackground(String... params) {
        // TODO fetch url data do bg process.
        return null;
    }

    /**
     * Update visibility GONE to Lottie anim..
     */
    protected void onPostExecute(String result) {
           // NO NEED to use activity.runOnUiThread(), code execute here under UI thread.

             // Updating parsed JSON data into ListView
             final List data = new Gson().fromJson(result);
            // updating listview
            ((ListActivity) activity).updateUI(data);
    }

};

}


问:
why can't Xcode find this header file?
Hi I'm getting an xcode "no such file or directory" for:

```<code>#import "Three20Core.h"
</code>```

I also note when I'm typing in the #import statement it recognises, and helps autocomplete, the "Three20Core.h" file, however when I compile I get the error?

This is the main library file header for the Three20 library (from Facebook).  So I've got the three20 directory at the same level as my app directory.  In the Xcode application target build settings:

Header Search Paths - "$(BUILT_PRODUCTS_DIR)/../../../three20" and recursive, and

User Header Search Paths - same as above.

Any fault finding advice?

答:
Have you followed this steps?
http://three20.info/article/2010-10-06-Adding-Three20-To-Your-Project</p>

Title: why can't Xcode find this header file?

Body:
Hi I'm getting an xcode "no such file or directory" for:

#import "Three20Core.h"

I also note when I'm typing in the #import statement it recognises, and helps autocomplete, the "Three20Core.h" file, however when I compile I get the error?

This is the main library file header for the Three20 library (from Facebook).  So I've got the three20 directory at the same level as my app directory.  In the Xcode application target build settings:

Header Search Paths - "$(BUILT_PRODUCTS_DIR)/../../../three20" and recursive, and

User Header Search Paths - same as above.

Any fault finding advice?


问:
Databinding during Navigation in UWP
I'm using Windows Template Studio to create a simple UWP app. I'm using the built-in MVVM template for Multiple Pages.
I have 2 Pages on the app. Both the pages contain the few textboxes where the user can enter some values. Data binding is working perfectly on both the pages individually. My problem is:
When I navigate to Page 2 and return back on Page 1, the value in the Textboxes return to the original initialization values and do not remain the last updated values.

I am expecting that when I return to Page 1 from Page 2, the values on Page 1 should be the last updated values.
I've followed a lot of tutorials but could not find a comprehensive solution to it.
I am just getting started with UWP and MVVM so it may be hard for me to wrap my head around some of the basic concepts.
Any help in this regard is appreciated.

答:
Have a look at NavigationCacheMode

https://learn.microsoft.com/en-us/uwp/api/windows.ui.xaml.controls.page.navigationcachemode

This should allow you to Cache the data you've entered and will persist whilst navigating to different frames

Title: Databinding during Navigation in UWP


问:
How to implement a custom adapter with listview?
Hi I'm working with an android app when I need to parse an array in the list view. I have created a custom adapter for that but I'm missing something here.</p>

```<code>public class IndustryAdapter extends ArrayAdapter<Industry> {
    Context context;
    int resource;
    public IndustryAdapter(Context context, ArrayList<Industry> industries) {
        super(context, industries);
    }

    @Override
    public View getView(View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
        }
        TextView tvName = (TextView)convertView.findViewById(R.id.tvName);
        TextView tvDescription = (TextView)convertView.findViewById(R.id.tvDescription);

        return convertView;
    }

}

On the super(context, industries) is showing an error for industries:

required: 'int'
error: incompatible types: ArrayList<Industry> cannot be converted to int
</code>```

答:
You should just change your super constructor invoke. Because it receive the layout resource which you gonna inflate. Like this:

```<code>public IndustryAdapter(Context context, ArrayList<Industry> industries) {
            super(context, android.R.layout.simple_list_item_1);
        }
</code>```

Body:
Hi I'm working with an android app when I need to parse an array in the list view. I have created a custom adapter for that but I'm missing something here.

public class IndustryAdapter extends ArrayAdapter<Industry> {
    Context context;
    int resource;
    public IndustryAdapter(Context context, ArrayList<Industry> industries) {
        super(context, industries);
    }

    @Override
    public View getView(View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
        }
        TextView tvName = (TextView)convertView.findViewById(R.id.tvName);
        TextView tvDescription = (TextView)convertView.findViewById(R.id.tvDescription);

        return convertView;
    }

}

On the super(context, industries) is showing an error for industries:

required: 'int'
error: incompatible types: ArrayList<Industry> cannot be converted to int

Body:
You should just change your super constructor invoke. Because it receive the layout resource which you gonna inflate. Like this:

public IndustryAdapter(Context context, ArrayList<Industry> industries) {
            super(context, android.R.layout.simple_list_item_1);
        }


问:
Docker - cannot connect to the Docker daemon
I'm trying to start a new Docker container with:

```<code>docker run -it ubuntu /bin/bash
</code>```

However I get the following

Checking for the daemon, I get

Any idea what the problem might be?

答:
I got this problem.  In my case, ps showed that the docker daemon was not running.  Problem was, I had no clue why.

$ sudo docker -d

attempts to start the daemon manually and displays an error message if it fails.

In my case, my kernel was a bit old and didn't support docker.

There are lots of reason why the daemon may not start, so it's best to find out if it's running and if not, why not.

Body:
I'm trying to start a new Docker container with:

docker run -it ubuntu /bin/bash

However I get the following

Checking for the daemon, I get

Any idea what the problem might be?


问:
Getting error using bearer authorization to sync PouchDB to Cloudant
I am an experienced JavaScript programmer, but new to PouchDB, Cloudant, and oAuth. When I try to sync PouchDB and Cloudant using Bearer Authorization, I get the error:

```<code>"_reader access is required for this request", status: 401

</code>```

I am trying to write a demo web app, using PouchDB and Cloudant.  I set up an IBM account.  I created one service called Cloudant-xx.  I chose Authentication Method:   IBM Cloud IAM (I did not choose "and legacy...").  I went to the dashboard for this service and 1) created a database (myDatabase), and 2) selected the head-profile on the left of the screen, then [CORS], and disabled CORS (for development).

I went back to the service, selected [Service Credentials], and created a new service credential.  This gave me an object with {"apikey": "ELB4lEVA...IO", ..., "username": "451c...74-bluemix"}.

I used curl to get an access token:

```<code>curl -k -X POST \
  --header "Content-Type: application/x-www-form-urlencoded" \
  --header "Accept: application/json" \
  --data-urlencode "grant_type=urn:ibm:params:oauth:grant-type:apikey" \
  --data-urlencode "apikey=ELB4lEVA...IO" \
  "https://iam.cloud.ibm.com/identity/token"
</code>```

which returned {"access_token":"eyJra...6fJns","token_type":"Bearer","expires_in":3600,"expiration":1558965151,"scope":"ibm openid"}

Within the hour, I copied and pasted the access token into my javascript code, ran the code, and got the error "_reader access is required for this request" (see above).  I cannot find where to set _reader access.  Can anybody help me?  Thanks!

```<code>    let localDb;
    const localName = "myDatabase";
    const remoteUrl = "https://451...d974-bluemix.cloudantnosqldb.appdomain.cloud/myDatabase";
    const token = "eyJra...6fJns";
    const syncOptions = {
        live: true,
        retry: true,
        continuous: true,
        ajax: {
            headers: {
                Authorization: "Bearer " + token,
            },
        },
    };
    localDb = new PouchDB(localName);
    localDb.sync(remoteUrl, syncOptions).on('change', function (info) {
        console.log(8888, "change", info);
    }).on('paused', function (info) {
        console.log(8888, "paused", info);
    }).on('active', function (info) {
        console.log(8888, "active", info);
    }).on('denied', function (err) {
        console.log(8888, "denied", err);
    }).on('complete', function (info) {
        console.log(8888, "denied", info);
    }).on('error', function (err) {
        console.log(8888, "error", err);
    });
    console.log(4444, localDb);
</code>```

In the console I see:

```<code>4444 PouchDB {__opts: {…}, auto_compaction: undefined, prefix: "_pouch_", name: "myDatabase", _adapter: "idb", …}
index.js:194

451...d974-bluemix.cloudantnosqldb.appdomain.cloud/:1 GET https://451...d974-bluemix.cloudantnosqldb.appdomain.cloud/myDatabase/ 401
index.js:192

8888 "error" CustomPouchError {error: "unauthorized", reason: "_reader access is required for this request", status: 401, name: "unauthorized", message: "_reader access is required for this request", …}
</code>```

答:
I answered my own question.  Turns out I was following out-of-date examples.  In PouchDB 7.0, {ajax: {headers: {}} has been replaced with fetch: function (url, opts) {}.  Plus I had to use a PouchDB instance instead of a string for the remote database.

https://pouchdb.com/api.html#create_database

Options for remote databases:

fetch(url, opts): Intercept or override the HTTP request, you can add or modify any headers or options relating to the http request then return a new fetch Promise.

This now works.

```<code>    let localDb;
    const localName = "myDatabase";
    const remoteUrl = "https://451...74-bluemix.cloudantnosqldb.appdomain.cloud/myDatabase";
    const token = "eyJ...448";
    const remoteOptions = {
        fetch: function (url, opts) {
            opts.headers.set("Authorization", "Bearer " + token);
            return PouchDB.fetch(url, opts);
        }
    };
    const syncOptions = {
        live: true,
        retry: true,
        continuous: true,
    };
    localDb = new PouchDB(localName);
    const remoteDb = new PouchDB(remoteUrl, remoteOptions);
    localDb.sync(remoteDb, syncOptions).on("change", function (info) {
        console.log(8888, "change", info);
    }).on("paused", function (info) {...})...
</code>```

Body:
I am an experienced JavaScript programmer, but new to PouchDB, Cloudant, and oAuth. When I try to sync PouchDB and Cloudant using Bearer Authorization, I get the error:

"_reader access is required for this request", status: 401

I am trying to write a demo web app, using PouchDB and Cloudant.  I set up an IBM account.  I created one service called Cloudant-xx.  I chose Authentication Method:   IBM Cloud IAM (I did not choose "and legacy...").  I went to the dashboard for this service and 1) created a database (myDatabase), and 2) selected the head-profile on the left of the screen, then [CORS], and disabled CORS (for development).

I went back to the service, selected [Service Credentials], and created a new service credential.  This gave me an object with {"apikey": "ELB4lEVA...IO", ..., "username": "451c...74-bluemix"}.

I used curl to get an access token:

curl -k -X POST \
  --header "Content-Type: application/x-www-form-urlencoded" \
  --header "Accept: application/json" \
  --data-urlencode "grant_type=urn:ibm:params:oauth:grant-type:apikey" \
  --data-urlencode "apikey=ELB4lEVA...IO" \
  "https://iam.cloud.ibm.com/identity/token"

which returned {"access_token":"eyJra...6fJns","token_type":"Bearer","expires_in":3600,"expiration":1558965151,"scope":"ibm openid"}

Within the hour, I copied and pasted the access token into my javascript code, ran the code, and got the error "_reader access is required for this request" (see above).  I cannot find where to set _reader access.  Can anybody help me?  Thanks!

    let localDb;
    const localName = "myDatabase";
    const remoteUrl = "https://451...d974-bluemix.cloudantnosqldb.appdomain.cloud/myDatabase";
    const token = "eyJra...6fJns";
    const syncOptions = {
        live: true,
        retry: true,
        continuous: true,
        ajax: {
            headers: {
                Authorization: "Bearer " + token,
            },
        },
    };
    localDb = new PouchDB(localName);
    localDb.sync(remoteUrl, syncOptions).on('change', function (info) {
        console.log(8888, "change", info);
    }).on('paused', function (info) {
        console.log(8888, "paused", info);
    }).on('active', function (info) {
        console.log(8888, "active", info);
    }).on('denied', function (err) {
        console.log(8888, "denied", err);
    }).on('complete', function (info) {
        console.log(8888, "denied", info);
    }).on('error', function (err) {
        console.log(8888, "error", err);
    });
    console.log(4444, localDb);

In the console I see:

4444 PouchDB {__opts: {…}, auto_compaction: undefined, prefix: "_pouch_", name: "myDatabase", _adapter: "idb", …}
index.js:194

451...d974-bluemix.cloudantnosqldb.appdomain.cloud/:1 GET https://451...d974-bluemix.cloudantnosqldb.appdomain.cloud/myDatabase/ 401
index.js:192

8888 "error" CustomPouchError {error: "unauthorized", reason: "_reader access is required for this request", status: 401, name: "unauthorized", message: "_reader access is required for this request", …}

Body:
I answered my own question.  Turns out I was following out-of-date examples.  In PouchDB 7.0, {ajax: {headers: {}} has been replaced with fetch: function (url, opts) {}.  Plus I had to use a PouchDB instance instead of a string for the remote database.

https://pouchdb.com/api.html#create_database

Options for remote databases:

fetch(url, opts): Intercept or override the HTTP request, you can add or modify any headers or options relating to the http request then return a new fetch Promise.

This now works.

    let localDb;
    const localName = "myDatabase";
    const remoteUrl = "https://451...74-bluemix.cloudantnosqldb.appdomain.cloud/myDatabase";
    const token = "eyJ...448";
    const remoteOptions = {
        fetch: function (url, opts) {
            opts.headers.set("Authorization", "Bearer " + token);
            return PouchDB.fetch(url, opts);
        }
    };
    const syncOptions = {
        live: true,
        retry: true,
        continuous: true,
    };
    localDb = new PouchDB(localName);
    const remoteDb = new PouchDB(remoteUrl, remoteOptions);
    localDb.sync(remoteDb, syncOptions).on("change", function (info) {
        console.log(8888, "change", info);
    }).on("paused", function (info) {...})...


问:
What’s the function of map()?
What’s is the function of map() in my code?</p>

```<code>squares = list(map(lambda x: x**2, range(10)))
</code>```

答:
That code (squares = list(map(lambda x: x**2, range(10)))) is strictly similar to:

```<code>f = lambda x: x**2
squares = []
for x in range(10):
    squares.append(f(x))
</code>```

Title: What’s the function of map()?

Body:
What’s is the function of map() in my code?

squares = list(map(lambda x: x**2, range(10)))

Body:
That code (squares = list(map(lambda x: x**2, range(10)))) is strictly similar to:

f = lambda x: x**2
squares = []
for x in range(10):
    squares.append(f(x))


问:
changing object keys acording to an array
i have an object and 2 arrays. i want to change object keys according to arr2, object keys and arr1 values are identical while arr1 and arr2 placement of values in arrays are identical but not values themselves, while i don't want to ask how to solve it want to know how should i approach this problem, thank you for your time

```<code>    const object = {
        name1: "some value",
        name3: "some value",
        name2: "some value",
        etc...}
    const arr1 = ["name1", "name2", "name3"]
    const arr2 = ["Name1", "Name2", "Name3"]
</code>```

expected outcome

```<code>    const newObject = {
        Name1: "some value",
        Name3: "some value",
        Name2: "some value",
        etc...}
</code>```

答:
I assume you are mapping them by positions in your arr1 and arr2.
Just run a loop.

 const oldObject = {
        name1: "some value",
        name3: "some value",
        name2: "some value",
};

const arr1 = ["name1", "name2", "name3"];
const arr2 = ["Name1", "Name2", "Name3"];

var newObj = {};

for (var i = 0; i < arr2.length; i++) {
  newObj[arr2[i]] = oldObject[arr1[i]];
}

console.log(newObj);```

Body:
i have an object and 2 arrays. i want to change object keys according to arr2, object keys and arr1 values are identical while arr1 and arr2 placement of values in arrays are identical but not values themselves, while i don't want to ask how to solve it want to know how should i approach this problem, thank you for your time

    const object = {
        name1: "some value",
        name3: "some value",
        name2: "some value",
        etc...}
    const arr1 = ["name1", "name2", "name3"]
    const arr2 = ["Name1", "Name2", "Name3"]

expected outcome

    const newObject = {
        Name1: "some value",
        Name3: "some value",
        Name2: "some value",
        etc...}


答:
You can use reduce()

const object = {
        name1: "some value",
        name3: "some value",
        name2: "some value"
}

const arr1 = ["name1", "name2", "name3"]
const arr2 = ["Name1", "Name2", "Name3"]

const res = arr1.reduce((ac,a,i) => (ac[arr2[i]] = object[a],ac),{});
console.log(res)```

Title: changing object keys acording to an array


问:
How to select a value from a DropDownList in a Word Macro using VBA?
I am creating a macro using both vbscript and vba, this macro is being called by the script code and works well but when I try to select a value outside the macro itself, I keep getting an error about the way im trying to set the value.

I have named the dropdownlist as "Result" and when I try to set the value it does not work, I also tried with the default name "DropDownList" , but none of those options seems to work, maybe i am missing object references.

I already declared the objects that I need

```<code>Set objWord = CreateObject("Word.Application")
Set activeDoc= objWord.ActiveDocument

activeDoc.FormFields("Result").DropDown.Value = 2
</code>```

The error i am getting right now is that "The Requested memeber of the coleection does not exist."

The only solution I can come up with is to set the value when I'm creating the dropdown in the macro:

```<code>ActiveDocument.Tables(1).Cell(Row: = 4, Column: = 4).Select
Set objCC =
    Selection.Range.ContentControls.Add(wdContentControlDropDownList)
With objCC
    .Title = "Result"
    .Tag = "Result"
    .DropdownListEntries.Add("Passed", "Passed").Select
End with
</code>```

答:
I got everything messed up, but in the end I realized what was my mistake. I wasn't using the tag so the Item was loose, I had to use the index of the correct content control</p>

```<code>Set objCc = activeDoc.ContentControls.Item(5)
Set objLe1 = objCc.DropdownListEntries.Item(1)
objLe1.Select
</code>```

Body:
I am creating a macro using both vbscript and vba, this macro is being called by the script code and works well but when I try to select a value outside the macro itself, I keep getting an error about the way im trying to set the value.

I have named the dropdownlist as "Result" and when I try to set the value it does not work, I also tried with the default name "DropDownList" , but none of those options seems to work, maybe i am missing object references.

I already declared the objects that I need

Set objWord = CreateObject("Word.Application")
Set activeDoc= objWord.ActiveDocument

activeDoc.FormFields("Result").DropDown.Value = 2

The error i am getting right now is that "The Requested memeber of the coleection does not exist."

The only solution I can come up with is to set the value when I'm creating the dropdown in the macro:

ActiveDocument.Tables(1).Cell(Row: = 4, Column: = 4).Select
Set objCC =
    Selection.Range.ContentControls.Add(wdContentControlDropDownList)
With objCC
    .Title = "Result"
    .Tag = "Result"
    .DropdownListEntries.Add("Passed", "Passed").Select
End with

Body:
I got everything messed up, but in the end I realized what was my mistake. I wasn't using the tag so the Item was loose, I had to use the index of the correct content control

Set objCc = activeDoc.ContentControls.Item(5)
Set objLe1 = objCc.DropdownListEntries.Item(1)
objLe1.Select


问:
Sometime I can't connect to mysql db with node.js while offline until I'm online, other time it just works, why?
My node.js program use the mysql module which I use with xampp. Why does it (sometime)require an internet connection to connect to my db in localhost using the mysql node module while other times it works fine while offline? It won't connect to my db which looks fine in phpmyadmin while offline but once I tried while online then it worked for a while offline then it seems to require internet once again. Why?</p>

答:
Behalf on using 'localhost' as your host you should use '127.0.0.1'
That Will solve your problem

```<code>const host='127.0.0.1';
const user='root';
const password='root';
const database='node_db'

var connection = mysql.createConnection({
  host:host,
  user:user,
  password: password,
  database: database
})
</code>```

Body:
Behalf on using 'localhost' as your host you should use '127.0.0.1'
That Will solve your problem

const host='127.0.0.1';
const user='root';
const password='root';
const database='node_db'

var connection = mysql.createConnection({
  host:host,
  user:user,
  password: password,
  database: database
})


问:
How to prevent 'click' event to fire before 'dblclick' event
I have to handle two events which are 'click' and 'dblclick' but the click event always fires before dblclick event and don't let dblclick event to execute. How can I make the event to execute correctly 'click' and 'dblclick'</p>

```<code>google.maps.event.addListener(map, 'dblclick', function(event) {
   polygon(map, event.latLng)
 });

 google.maps.event.addListener(map, 'click', function(event) {
   click_events(map, event.latLng)
 });
</code>```

答:
Use setTimeout and maintain the timeout object so that you can clear it on double click</p>

```<code>var timeoutObj;
var timeoutThreshhold = ...; //number of milliseconds to wait for double click

google.maps.event.addListener(map, 'dblclick', function(event) {
   if (timeoutObj) {
     clear timeoutObj;
   }
   polygon(map, event.latLng);
 });

 google.maps.event.addListener(map, 'click', function(event) {
   timeoutObj = setTimeout(function() {
     timeoutObj = null;
     click_events(map, event.latLng);
   }, timeoutThreadhold);
 });
</code>```

Body:
I have to handle two events which are 'click' and 'dblclick' but the click event always fires before dblclick event and don't let dblclick event to execute. How can I make the event to execute correctly 'click' and 'dblclick'

google.maps.event.addListener(map, 'dblclick', function(event) {
   polygon(map, event.latLng)
 });

 google.maps.event.addListener(map, 'click', function(event) {
   click_events(map, event.latLng)
 });

Body:
Use setTimeout and maintain the timeout object so that you can clear it on double click

var timeoutObj;
var timeoutThreshhold = ...; //number of milliseconds to wait for double click

google.maps.event.addListener(map, 'dblclick', function(event) {
   if (timeoutObj) {
     clear timeoutObj;
   }
   polygon(map, event.latLng);
 });

 google.maps.event.addListener(map, 'click', function(event) {
   timeoutObj = setTimeout(function() {
     timeoutObj = null;
     click_events(map, event.latLng);
   }, timeoutThreadhold);
 });