问:
Duplicate lines of code consecutively with Pycharm
I am currently creating a script which has approximately 100 lines of code. Within PyCharm, I am interested in duplicating each line of code consecutively throughout the script. An example demonstrating the desired output is shown below.

```<code># Current Code

print("Hello World")
print("I enjoy python")
print("Stack Overflow is amazing")

# Desired Output

print("Hello World")
print("Hello World")
print("Hello World")
print("I enjoy python")
print("I enjoy python")
print("I enjoy python")
print("Stack Overflow is amazing")
print("Stack Overflow is amazing")
print("Stack Overflow is amazing")
</code>```

As this is only a sample with 3 original lines of code, I simply created duplicates of the code by copying and pasting each line. In projects which contain over 100 lines of code, this would be impractical. How can I do this in PyCharm without copying and pasting line by line?

-Thanks

答:
Try this, with test.py being your input script:

```<code>x = [e.strip() for e in open("test.py", "r").readlines()]  # get lines, strip them of the '\n'
r = [(x[i]+'\n') * 3 for i in range(len(x))]               # multiply each line by three
with open("test_out.py", "w") as out:                      # open an output, writing mode
    out.write(''.join(r))                                  # join the lines, write to output
    out.close()                                            # close the file (keep things clean)
</code>```

Stripping each line of the '\n' (which might be there or not on the very last line) ensure the last line is always written properly, that is, not as

print("Stack Overflow is amazing")print("Stack Overflow is amazing")print("Stack Overflow is amazing")

but as

```<code>print("Stack Overflow is amazing")
print("Stack Overflow is amazing")
print("Stack Overflow is amazing")
</code>```

if the carriage return isn't there.

Don't forget to change the output filename to an actual path if you want your output file somewhere else !

Body:
I am currently creating a script which has approximately 100 lines of code. Within PyCharm, I am interested in duplicating each line of code consecutively throughout the script. An example demonstrating the desired output is shown below.

# Current Code

print("Hello World")
print("I enjoy python")
print("Stack Overflow is amazing")

# Desired Output

print("Hello World")
print("Hello World")
print("Hello World")
print("I enjoy python")
print("I enjoy python")
print("I enjoy python")
print("Stack Overflow is amazing")
print("Stack Overflow is amazing")
print("Stack Overflow is amazing")

As this is only a sample with 3 original lines of code, I simply created duplicates of the code by copying and pasting each line. In projects which contain over 100 lines of code, this would be impractical. How can I do this in PyCharm without copying and pasting line by line?

-Thanks

Body:
Try this, with test.py being your input script:

x = [e.strip() for e in open("test.py", "r").readlines()]  # get lines, strip them of the '\n'
r = [(x[i]+'\n') * 3 for i in range(len(x))]               # multiply each line by three
with open("test_out.py", "w") as out:                      # open an output, writing mode
    out.write(''.join(r))                                  # join the lines, write to output
    out.close()                                            # close the file (keep things clean)

Stripping each line of the '\n' (which might be there or not on the very last line) ensure the last line is always written properly, that is, not as

print("Stack Overflow is amazing")print("Stack Overflow is amazing")print("Stack Overflow is amazing")

but as

print("Stack Overflow is amazing")
print("Stack Overflow is amazing")
print("Stack Overflow is amazing")

if the carriage return isn't there.

Don't forget to change the output filename to an actual path if you want your output file somewhere else !


来源: stackexchange

问:
How can I junit test the last block of this equal?
How can I JUnit test the last block of this equal?

Any help would be much appreciated. This is the method in question:

```<code>@Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    //unreachable block
    ServiceOrderRelationship serviceOrderRelationship = (ServiceOrderRelationship) o;
    return Objects.equals(this.id, serviceOrderRelationship.id) &&
        Objects.equals(this.href, serviceOrderRelationship.href) &&
        Objects.equals(this.relationshipType, serviceOrderRelationship.relationshipType) &&
        Objects.equals(this.baseType, serviceOrderRelationship.baseType) &&
        Objects.equals(this.schemaLocation, serviceOrderRelationship.schemaLocation) &&
        Objects.equals(this.type, serviceOrderRelationship.type) &&
        Objects.equals(this.referredType, serviceOrderRelationship.referredType);
  }
</code>```

This is what I've been doing but I can never reach the last block of code inside the equals method:

```<code>@Test
public void testEquals() throws Exception {

    assertFalse(serviceOrderRelationship.equals(null));
    assertTrue(serviceOrderRelationship.equals(serviceOrderRelationship));
    assertFalse(serviceOrderRelationship.equals(serviceOrderRelationship1));
}
</code>```

答:
First of all, thank you all for your responses!

This is how I was able to reach the last block of the equals method. I had to initialize both objects di and di1 and set every variable to the same value, then test the equals condition switching back and forth one variable at a time to a different value. This is an example from another POJO:

```<code>    // Initialize objects
    di.setEdgeId("edgeId");
    di.setIdentityEndpoint("identityEndpoint");
    di.setUsername("username");

    di1.setEdgeId("edgeId");
    di1.setIdentityEndpoint("identityEndpoint");
    di1.setUsername("username");

    // Change value of var and test equal
    di1.setEdgeId("edgeIdm");
    assertFalse(di.equals(di1));
    di1.setEdgeId("edgeId");

    // same
    di1.setIdentityEndpoint("identityEndpointm");
    assertFalse(di.equals(di1));
    di1.setIdentityEndpoint("identityEndpoint");

    // Same
    di1.setUsername("usernamem");
    assertFalse(di.equals(di1));
    di1.setUsername("username");

    // Then at the end perform the other tests
    assertTrue(di.equals(di));
    assertTrue(di.equals(di1));
    assertFalse(di.equals(null));
    assertFalse(di.equals(42));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I JUnit test the last block of this equal?

Any help would be much appreciated. This is the method in question:

@Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    //unreachable block
    ServiceOrderRelationship serviceOrderRelationship = (ServiceOrderRelationship) o;
    return Objects.equals(this.id, serviceOrderRelationship.id) &&
        Objects.equals(this.href, serviceOrderRelationship.href) &&
        Objects.equals(this.relationshipType, serviceOrderRelationship.relationshipType) &&
        Objects.equals(this.baseType, serviceOrderRelationship.baseType) &&
        Objects.equals(this.schemaLocation, serviceOrderRelationship.schemaLocation) &&
        Objects.equals(this.type, serviceOrderRelationship.type) &&
        Objects.equals(this.referredType, serviceOrderRelationship.referredType);
  }

This is what I've been doing but I can never reach the last block of code inside the equals method:

@Test
public void testEquals() throws Exception {

    assertFalse(serviceOrderRelationship.equals(null));
    assertTrue(serviceOrderRelationship.equals(serviceOrderRelationship));
    assertFalse(serviceOrderRelationship.equals(serviceOrderRelationship1));
}

Body:
First of all, thank you all for your responses!

This is how I was able to reach the last block of the equals method. I had to initialize both objects di and di1 and set every variable to the same value, then test the equals condition switching back and forth one variable at a time to a different value. This is an example from another POJO:

    // Initialize objects
    di.setEdgeId("edgeId");
    di.setIdentityEndpoint("identityEndpoint");
    di.setUsername("username");

    di1.setEdgeId("edgeId");
    di1.setIdentityEndpoint("identityEndpoint");
    di1.setUsername("username");

    // Change value of var and test equal
    di1.setEdgeId("edgeIdm");
    assertFalse(di.equals(di1));
    di1.setEdgeId("edgeId");

    // same
    di1.setIdentityEndpoint("identityEndpointm");
    assertFalse(di.equals(di1));
    di1.setIdentityEndpoint("identityEndpoint");

    // Same
    di1.setUsername("usernamem");
    assertFalse(di.equals(di1));
    di1.setUsername("username");

    // Then at the end perform the other tests
    assertTrue(di.equals(di));
    assertTrue(di.equals(di1));
    assertFalse(di.equals(null));
    assertFalse(di.equals(42));


问:
Convert date format from "month_name day, year" to "yyyy-mm-dd" in BigQuery
I have a column with date format as "month_name day, yyyy", for example, "July 4, 2000". Now I want to convert it to ISO "yyyy-mm-dd". Is there any function I can call to do it in standard SQL?

```<code>UPDATE target_name
SET col = function(col)
</code>```

How do I use python client to update a column with the above function or update a new column using the function after creating it as below ?

```<code>original_schema = table.schema
new_schema = original_schema[:]
new_schema.append(bigquery.SchemaField('new_date', 'DATE'))
table.schema = new_schema
table = client.update_table(table, ['schema'])
</code>```

Thanks!

答:
You can use date functions: parse_date() turns the string to a date, and then format_date() converts the date to a string in the desired format:

```<code>update target_name set col = format_date('%F', parse_date('%B %e, %Y', col))
</code>```

Body:
I have a column with date format as "month_name day, yyyy", for example, "July 4, 2000". Now I want to convert it to ISO "yyyy-mm-dd". Is there any function I can call to do it in standard SQL?

UPDATE target_name
SET col = function(col)

How do I use python client to update a column with the above function or update a new column using the function after creating it as below ?

original_schema = table.schema
new_schema = original_schema[:]
new_schema.append(bigquery.SchemaField('new_date', 'DATE'))
table.schema = new_schema
table = client.update_table(table, ['schema'])

Thanks!

Body:
You can use date functions: parse_date() turns the string to a date, and then format_date() converts the date to a string in the desired format:

update target_name set col = format_date('%F', parse_date('%B %e, %Y', col))


问:
Is it possible to connect a certain SKU purchase with a certain campaign?
We are able to track transactions on our e-commerce and also track people who landed on the website through a LinkedIn display campaign for instance. But not possible to know how to connect these 2 information. Thank you!</p>

答: You need to set up User-ID features: https://support.google.com/analytics/answer/3123666?hl=en


问:
Create separate MD5 file for each file recursively
I've been wanting to keep an eye on my file storage, and watch for files that get corrupted over time.

To that end, I'm trying to write a Linux bash / shell script to recurse through a directory and create an MD5 hashsum file for each file, in the same directory as each file. I'm not a fan of having a single file that contains all of the hashes, because it'd all fall over if that single file ever became damaged or lost.

```<code>- Directory 1
    - TestFile.txt
    - TestFile.txt.md5
    - AnotherTestFile.wav
    - AnotherTestFile.wav.md5
- Directory 2
    - MyDetails.docx
    - MyDetails.docx.md5
</code>```

I've tried to use the md5sum command in a variety of ways, but it always wants to either:

Create all of the hashes in a single file.

Create separate .md5 hash files for each file, but the filenames within the md5 hash file contain the full file path (e.g. ./Documents/Directory1/TestFile.txt), not just the file name (e.g. TestFile.txt).

I do have a tool on Windows that does this (MD5Checker), but it is hashing the files on my file server over the network. I'd prefer something that can run natively on a Linux OS.

Any thoughts?

My latest attempt (I know it's bad)

It creates the MD5 file, but the file path in the hashsum file is the full file path, not the base file path.

```<code>#!/bin/bash

function md5_dir {
for file in $1/*;
do
        if [[ -f "$file" && ! $file == *.md5 ]];
        then
                file_basename=$(basename "$file");
                echo "$file" "$file_basename";
                md5sum "$file" > "$file.md5";
        fi;
        if [[ -d "$file" ]];
        then
                md5_dir $file
        fi;
done;
}

echo "$1"
md5_dir "$1";
</code>```

答:
md5sum always prints the pathname it's given after the checksum, there's no option to make it only print the basename. Extract the checksum from the output and then write that with the basename to the md5 file.

```<code>read sum pathname < <(md5sum "$file")
printf "%s %s\n" $sum "$file_basename" > "$file.md5"
</code>```

Body:
I've been wanting to keep an eye on my file storage, and watch for files that get corrupted over time.

To that end, I'm trying to write a Linux bash / shell script to recurse through a directory and create an MD5 hashsum file for each file, in the same directory as each file. I'm not a fan of having a single file that contains all of the hashes, because it'd all fall over if that single file ever became damaged or lost.

- Directory 1
    - TestFile.txt
    - TestFile.txt.md5
    - AnotherTestFile.wav
    - AnotherTestFile.wav.md5
- Directory 2
    - MyDetails.docx
    - MyDetails.docx.md5

I've tried to use the md5sum command in a variety of ways, but it always wants to either:

Create all of the hashes in a single file.

Create separate .md5 hash files for each file, but the filenames within the md5 hash file contain the full file path (e.g. ./Documents/Directory1/TestFile.txt), not just the file name (e.g. TestFile.txt).

I do have a tool on Windows that does this (MD5Checker), but it is hashing the files on my file server over the network. I'd prefer something that can run natively on a Linux OS.

Any thoughts?

My latest attempt (I know it's bad)

It creates the MD5 file, but the file path in the hashsum file is the full file path, not the base file path.

#!/bin/bash

function md5_dir {
for file in $1/*;
do
        if [[ -f "$file" && ! $file == *.md5 ]];
        then
                file_basename=$(basename "$file");
                echo "$file" "$file_basename";
                md5sum "$file" > "$file.md5";
        fi;
        if [[ -d "$file" ]];
        then
                md5_dir $file
        fi;
done;
}

echo "$1"
md5_dir "$1";

Body:
md5sum always prints the pathname it's given after the checksum, there's no option to make it only print the basename. Extract the checksum from the output and then write that with the basename to the md5 file.

read sum pathname < <(md5sum "$file")
printf "%s %s\n" $sum "$file_basename" > "$file.md5"


问:
How do I get the next day's date in JS in YYYY-MM-DD format?
Seems like a simple question, but all the timezone ins and outs in JS are causing me a bunch of headaches.

Basically, if I have a date like the following:

```<code>2018-04-06
</code>```

I want to be able to get the next day's date as such:

```<code>2018-04-07
</code>```

I found the following snippet on SO for doing this (kind of):

```<code>var date = new Date('2018-04-06');
date.setDate(date + 1);
</code>```

The problem is that I'm getting the date back with the adjusted timezone, and because I'm in the US ET timezone, it's giving me that date minus five hours, which is actually the same day as where I started.

I've been through countless SO posts trying to find an answer to this seemingly simple question, but for any given date, regardless of the timezone the user is in, how do I get the next day's date in YYYY-MM-DD format? Thank you.

答:
Strings in the format YYYY-MM-DD are parsed as UTC so in this case, do everything in UTC (see Why does Date.parse give incorrect results? and How can I add 1 day to current date?).

The toISOString method will return the string in the required format, just trim the redundant time part, e.g.

let s = '2018-04-06';
let d = new Date(s);
d.setUTCDate(d.getUTCDate() + 1);
console.log(d.toISOString().substr(0,10));```

Body:
Seems like a simple question, but all the timezone ins and outs in JS are causing me a bunch of headaches.

Basically, if I have a date like the following:

2018-04-06

I want to be able to get the next day's date as such:

2018-04-07

I found the following snippet on SO for doing this (kind of):

var date = new Date('2018-04-06');
date.setDate(date + 1);

The problem is that I'm getting the date back with the adjusted timezone, and because I'm in the US ET timezone, it's giving me that date minus five hours, which is actually the same day as where I started.

I've been through countless SO posts trying to find an answer to this seemingly simple question, but for any given date, regardless of the timezone the user is in, how do I get the next day's date in YYYY-MM-DD format? Thank you.


问:
Is Future.wait trully asynchonous in Dart?
I need to wait for many Future to complete their computation, a bunch of HTTP requests, I don't want to await all of them in order as this will result in each Future being evaluated in order, one after the other, kinda synchronously, which is wasteful as some Future might complete sooner than others.

I can't find in the docs of Future.wait is truly asynchronous, firing all the Future at the same time, or if its the same as calling them one after the other, waiting for the previous to complete to call the next.

In a nushell: I am looking for the best performant way to get the results of many HTTP requests in Dart.

答:
Future.wait does await multiple futures in an asynchronous way, as in each of the futures is started independently of one another. By contrast, Future.forEach will loop through the list of futures and await on them in sequence.

For example, if you had the following list of futures:

var futures = [
  Future.delayed(Duration(seconds, 3)).then((_) => print('1')),
  Future.delayed(Duration(seconds, 2)).then((_) => print('2')),
  Future.delayed(Duration(seconds, 1)).then((_) => print('3')),
];
```

<p>Calling <code>Future.wait</code> on this list would result in the following output:</p>

<pre class="lang-dart prettyprint-override"><code>3 (after 1 second)
2 (after 2 seconds)
1 (after 3 seconds)
</code>```

Whereas calling Future.forEach on the list would result in this:

1 (after 3 seconds)
2 (after 5 seconds)
3 (after 6 seconds)
```

This is because wait fires them all simultaneously then handles them as they all resolve while forEach fires them individually in order and waits for each one to resolve before going to the next one.

(Here is the usual disclaimer that asynchronous programming is not the same thing as parallel programming, and that Dart is an inherently single-threaded language so true parallelism cannot be achieved with futures alone.)

Body:
Future.wait does await multiple futures in an asynchronous way, as in each of the futures is started independently of one another. By contrast, Future.forEach will loop through the list of futures and await on them in sequence.

For example, if you had the following list of futures:

var futures = [
  Future.delayed(Duration(seconds, 3)).then((_) => print('1')),
  Future.delayed(Duration(seconds, 2)).then((_) => print('2')),
  Future.delayed(Duration(seconds, 1)).then((_) => print('3')),
];

Calling Future.wait on this list would result in the following output:

3 (after 1 second)
2 (after 2 seconds)
1 (after 3 seconds)

Whereas calling Future.forEach on the list would result in this:

1 (after 3 seconds)
2 (after 5 seconds)
3 (after 6 seconds)

This is because wait fires them all simultaneously then handles them as they all resolve while forEach fires them individually in order and waits for each one to resolve before going to the next one.

(Here is the usual disclaimer that asynchronous programming is not the same thing as parallel programming, and that Dart is an inherently single-threaded language so true parallelism cannot be achieved with futures alone.)


答:
find is the go-to tool for recursively doing anything with files:

```<code>find . -type f ! -name '*.md5' -execdir sh -c 'md5sum "$1" > "$1.md5"' _ {} \;
</code>```

This picks files (not named '*.md5') and runs the given inlined shell script with the filename as $1.

Title: Create separate MD5 file for each file recursively

Body:
find is the go-to tool for recursively doing anything with files:

find . -type f ! -name '*.md5' -execdir sh -c 'md5sum "$1" > "$1.md5"' _ {} \;

This picks files (not named '*.md5') and runs the given inlined shell script with the filename as $1.


问:
Python Datastructure Suggestion
i am building a small search engine to search a collection of pdfs. From each pdf i extract a set of tokens and store it in database. I do not want to store duplicate tokens in database, instead i want to store count of each token in the database. Does python has any special datastructure that do not store duplicates but stores the counts of each token?</p>

答:
I'd suggest to use a simple dictionary to store the count like

```<code>storage = {} # initialize
# ...
if !storage.has_key(token):
  storage[token] = 1
else:
  storage[token] += 1
</code>```

EDIT

That said, if you're using Python 3 I'd follow Space_C0wb0y's suggestion to use the Counter class ...

ContentLicense: CC BY-SA 3.0

Title: Python Datastructure Suggestion

Body:
I'd suggest to use a simple dictionary to store the count like

storage = {} # initialize
# ...
if !storage.has_key(token):
  storage[token] = 1
else:
  storage[token] += 1

EDIT

That said, if you're using Python 3 I'd follow Space_C0wb0y's suggestion to use the Counter class ...


问:
How to simulate a click on a Font Awesome Icon using Jest?
I'm testing through Jest and am trying to test the click on a Font Awesome Icon. I've tried different ways to find the 'node', but I get the error that "Method “simulate” is meant to be run on 1 node. 0 found instead." Any insight would be helpful.

The error I get when I try different inputs to component.find() is: Method “simulate” is meant to be run on 1 node. 0 found instead.

StringEditor

```<code>const clearInput = () => {
    onRemove()
}

render (
    ...
    <FontAwesomeIcon icon={['fal', 'times-circle']} className="clear-button"
    onClick={clearInput} /> : null`
)
</code>```

onRemove is a callback function.

```<code>it('should call clearInput thus onRemove', () =>{

    const onRemove= jest.fn()
    const component = mount(<StringEditor {...defaultProps}  onRemove={onRemove} />)
    component.find('<dont know what to put>').simulate('click')
    expect(saveValueFn).toBeCalled()
})
</code>```

答:
You can use the Object Property Selector: https://airbnb.io/enzyme/docs/api/selector.html#4-object-property-selector

Or a React Component Constructor: https://airbnb.io/enzyme/docs/api/selector.html#2-a-react-component-constructor

Body:
I'm testing through Jest and am trying to test the click on a Font Awesome Icon. I've tried different ways to find the 'node', but I get the error that "Method “simulate” is meant to be run on 1 node. 0 found instead." Any insight would be helpful.

The error I get when I try different inputs to component.find() is: Method “simulate” is meant to be run on 1 node. 0 found instead.

StringEditor

const clearInput = () => {
    onRemove()
}

render (
    ...
    <FontAwesomeIcon icon={['fal', 'times-circle']} className="clear-button"
    onClick={clearInput} /> : null`
)

onRemove is a callback function.

it('should call clearInput thus onRemove', () =>{

    const onRemove= jest.fn()
    const component = mount(<StringEditor {...defaultProps}  onRemove={onRemove} />)
    component.find('<dont know what to put>').simulate('click')
    expect(saveValueFn).toBeCalled()
})


问:
how to animate css element only when it appears on a window?
i know that there is parallax but i want something else like in this website joinhandshake.com

for example i have this code

html

```<code><div class="black-div"></div>
   <div class="animated-div">
       <h1>Lorem ipsum dolor sit amet consectetur adipisicing elit. Odit temporibus fuga sit quam fugit! Dignissimos quis qui, praesentium id nihil, aspernatur nostrum, dolores dolor molestiae error molestias ipsum ipsam at.</h1>
   </div>
</code>```

css

```<code>
.black-div {
    background-color: black;
    height: 130vh;
}
 @keyframes rotate-scale-up {
    0% {
      transform: scale(1) rotateZ(0);
    }
    50% {
      transform: scale(2) rotateZ(180deg);
    }
    100% {
      transform: scale(1) rotateZ(360deg);
    }
  }
  .animated-div {
    animation: rotate-scale-up 0.65s linear both;
}
</code>```

the problem is that when i load the page, the text gets animated, so how can i prevent that?

答:
To check if an element is in view, use the Intersection Observer API. This API is built for this exact purpose and requires little to no calculations, only a check with the isIntersecting value, to see if an element has entered the view.

The IntersectionObserverIn uses a callback function to do something whenever an element has entered or left the view. In this function you can specify what should happen when that does.

I've made a snippet with an example on how it works and how you can implement it.

/**
 * What to do when an item enters the screen
 * If it is in the screen, isIntersecting will be true.
 * Add a class when it is.
 */
const intersectionCallback = (entries) => {
  for (const entry of entries) { // Loop over all elements that either enter or exit the view.
    if (entry.isIntersecting) { // This is true when the element is in view.
      entry.target.classList.add('show'); // Add a class.
    }
  }
}

/**
 * Create a observer and use the instersectionCallback as
 * the instructions for what to do when an element enters
 * or leaves the view
 */
const observer = new IntersectionObserver(intersectionCallback);

/**
 * Get all .item elements and loop over them.
 * Observe each individual item.
 */
const items = document.querySelectorAll('.item');
for (const item of items) {
  observer.observe(item);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.item {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  height: 200px;
  width: 100%;
  margin-bottom: 20px;
  opacity: 0;
  transition: opacity 1s ease-out;
}

.item:nth-of-type(odd) {
  background-color: #333;
}

.item:nth-of-type(even) {
  background-color: #111;
}

.item.show {
  opacity: 1;
}</code>```

Hello

Hello

Hello

Hello

Hello

Hello

Hello
```

Body:
i know that there is parallax but i want something else like in this website joinhandshake.com

for example i have this code

html

Lorem ipsum dolor sit amet consectetur adipisicing elit. Odit temporibus fuga sit quam fugit! Dignissimos quis qui, praesentium id nihil, aspernatur nostrum, dolores dolor molestiae error molestias ipsum ipsam at.

css

.black-div {
    background-color: black;
    height: 130vh;
}
 @keyframes rotate-scale-up {
    0% {
      transform: scale(1) rotateZ(0);
    }
    50% {
      transform: scale(2) rotateZ(180deg);
    }
    100% {
      transform: scale(1) rotateZ(360deg);
    }
  }
  .animated-div {
    animation: rotate-scale-up 0.65s linear both;
}

the problem is that when i load the page, the text gets animated, so how can i prevent that?

Body:
To check if an element is in view, use the Intersection Observer API. This API is built for this exact purpose and requires little to no calculations, only a check with the isIntersecting value, to see if an element has entered the view.

The IntersectionObserverIn uses a callback function to do something whenever an element has entered or left the view. In this function you can specify what should happen when that does.

I've made a snippet with an example on how it works and how you can implement it.

/**
 * What to do when an item enters the screen
 * If it is in the screen, isIntersecting will be true.
 * Add a class when it is.
 */
const intersectionCallback = (entries) => {
  for (const entry of entries) { // Loop over all elements that either enter or exit the view.
    if (entry.isIntersecting) { // This is true when the element is in view.
      entry.target.classList.add('show'); // Add a class.
    }
  }
}

/**
 * Create a observer and use the instersectionCallback as
 * the instructions for what to do when an element enters
 * or leaves the view
 */
const observer = new IntersectionObserver(intersectionCallback);

/**
 * Get all .item elements and loop over them.
 * Observe each individual item.
 */
const items = document.querySelectorAll('.item');
for (const item of items) {
  observer.observe(item);
}

.item {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  height: 200px;
  width: 100%;
  margin-bottom: 20px;
  opacity: 0;
  transition: opacity 1s ease-out;
}

.item:nth-of-type(odd) {
  background-color: #333;
}

.item:nth-of-type(even) {
  background-color: #111;
}

.item.show {
  opacity: 1;
}

<div class="item">Hello</div>
<div class="item">Hello</div>
<div class="item">Hello</div>
<div class="item">Hello</div>
<div class="item">Hello</div>
<div class="item">Hello</div>
<div class="item">Hello</div>


问:
displaying records from mysql in ul and li format with php
i want to display the mysql's fetched results with php and html in unordered list and list format  as like http://www.miniclip.com/games/en/. you can see in the all games categories in the footer in alphabetical order. the same requirement i do have. i guess i have written the logic its working fine. but i am unable to represent it properly. you can see in the following link above the footer. http://www.playtoongames.com/play1...

code:

```<code><?php
$gameQuery = mysql_query ("SELECT name, LEFT(name, 1) AS first_char FROM games WHERE UPPER(name) BETWEEN 'A' AND 'Z' OR name BETWEEN '0' AND '9' ORDER BY name");
$current_char = '';
   while ($gameRow = mysql_fetch_assoc($gameQuery)){
     if ($_SESSION['lang'] == 'fr'){
         $description = $gameRow['description_fr'];
     }else{
   $description = $gameRow['description'];
 }
?>

<div style='float:left' title="<img src='<?php echo $gameRow['sitePath'];?>games/images/<?php echo $gameRow['img_100x75'];?>' width='230' height='112' class='thumb' alt='<?php echo $gameRow['name'];?>'/>" class='tooltip'>

                     <ul>
                     <li>
     <a href='<?php echo $gameRow['sitePath'];?>play/<?php echo str_replace(' ','_',$gameRow['name']);?>'><?php echo $gameRow['name'];?></a>
                     </li>
                      </ul>
</div>
</code>```

can anybody look into this...

Regards,
sam.

答:
Well, I think the key is that there are 6 columns, which just means you'll need to break your array into 6 different parts.

Here's some psuedocode:

```<code>$pArr = $from_sql_array; // I'll let you take care of that.
$itmCount = count($pArr);
$itmsPerCol = ceil($itmCount / 6.0);
for ($ii=0; $ii < 6; $ii++)
{
  $pCol = array_slice($pArr, $itmsPerCol * $ii, $itmsPerCol);
  echo '<ul class="floatleft"><li>'.implode("</li>\n<li>",$pCol).'</li></ul>';
}
</code>```

Body:
i want to display the mysql's fetched results with php and html in unordered list and list format  as like http://www.miniclip.com/games/en/. you can see in the all games categories in the footer in alphabetical order. the same requirement i do have. i guess i have written the logic its working fine. but i am unable to represent it properly. you can see in the following link above the footer. http://www.playtoongames.com/play1...

code:

<?php
$gameQuery = mysql_query ("SELECT name, LEFT(name, 1) AS first_char FROM games WHERE UPPER(name) BETWEEN 'A' AND 'Z' OR name BETWEEN '0' AND '9' ORDER BY name");
$current_char = '';
   while ($gameRow = mysql_fetch_assoc($gameQuery)){
     if ($_SESSION['lang'] == 'fr'){
         $description = $gameRow['description_fr'];
     }else{
   $description = $gameRow['description'];
 }
?>

<div style='float:left' title="<img src='<?php echo $gameRow['sitePath'];?>games/images/<?php echo $gameRow['img_100x75'];?>' width='230' height='112' class='thumb' alt='<?php echo $gameRow['name'];?>'/>" class='tooltip'>

     <a href='<?php echo $gameRow['sitePath'];?>play/<?php echo str_replace(' ','_',$gameRow['name']);?>'><?php echo $gameRow['name'];?>

can anybody look into this...

Regards,
sam.

Body:
Well, I think the key is that there are 6 columns, which just means you'll need to break your array into 6 different parts.

Here's some psuedocode:

$pArr = $from_sql_array; // I'll let you take care of that.
$itmCount = count($pArr);
$itmsPerCol = ceil($itmCount / 6.0);
for ($ii=0; $ii < 6; $ii++)
{
  $pCol = array_slice($pArr, $itmsPerCol * $ii, $itmsPerCol);
  echo '<ul class="floatleft"><li>'.implode("</li>\n<li>",$pCol).'</li></ul>';
}


问:
Is it possible to import *.vue files in a folder?
I hate repeating things in code. For now I am importing vue files like this in my main.js.

```<code>import Default     from '../../src/components/default.vue';
import Home        from '../../src/components/home.vue';
import hakkinda    from '../../src/components/hakkinda.vue';
import projeler    from '../../src/components/projeler.vue';
import servisler   from '../../src/components/servisler.vue';
import yetenekler  from '../../src/components/yetenekler.vue';
import yetenek     from '../../src/components/yetenek.vue';
import referanslar from '../../src/components/referanslar.vue';
import iletisim    from '../../src/components/iletisim.vue';
</code>```

Is there a way to do same thing with less lines? Could be great if I can assign variable name from filename. Can PHP help about it? But then how to compile main.js? I did not figured out.

答:
Based on Potray and Fosuze's working answers for easy reference:</p>

```<code>const files = require.context('.', false, /\.vue$/)
const modules = {}
files.keys().forEach((key) => {
     if (key === './index.js') return
     modules[key.replace(/(\.\/|\.vue)/g, '')] = files(key)
})
export default modules
</code>```

Body:
I hate repeating things in code. For now I am importing vue files like this in my main.js.

import Default     from '../../src/components/default.vue';
import Home        from '../../src/components/home.vue';
import hakkinda    from '../../src/components/hakkinda.vue';
import projeler    from '../../src/components/projeler.vue';
import servisler   from '../../src/components/servisler.vue';
import yetenekler  from '../../src/components/yetenekler.vue';
import yetenek     from '../../src/components/yetenek.vue';
import referanslar from '../../src/components/referanslar.vue';
import iletisim    from '../../src/components/iletisim.vue';

Is there a way to do same thing with less lines? Could be great if I can assign variable name from filename. Can PHP help about it? But then how to compile main.js? I did not figured out.

Body:
Based on Potray and Fosuze's working answers for easy reference:

const files = require.context('.', false, /\.vue$/)
const modules = {}
files.keys().forEach((key) => {
     if (key === './index.js') return
     modules[key.replace(/(\.\/|\.vue)/g, '')] = files(key)
})
export default modules


问:
Socket.IO not working from Angular despite allowing origin
I am trying to use socket.io to connect my angular 8 app to my node.js server, my app is using REST endpoints on the same server without issue but socket.io always fails with CORS related error.

This is the relevant part from my server:

```<code>const app: Application = express();

app.use(cors({credentials: false}));

// The application will have it's routes on /api
app.use("/api", routes);
app.use(express.static(path.join(__dirname+'/public/')));
// Everything else will be redirected to the FE app
app.all("/*", (req: Request, res: Response) => {
    res.sendFile(path.join(__dirname+'/public/index.html'));
})

let port = process.env.PORT || configs.port;

app.listen(port, () => {
    console.log('server online on port', port);
});

let server = require('http').Server(app);
let io = require('socket.io')(server, { origins: ['http://localhost:4200'] });
// io.origins(['http://localhost:4200']);

io.on('connection', function (socket: Socket) {
    console.log('WEB SOCKET CONNECTION');
    socket.emit('news', { hello: 'world' });
    socket.on('my other event', function (data: any) {
        console.log(data);
    });
});
</code>```

And this is on the client:

```<code>    this.socket = io.connect(configs.baseURL);
</code>```

The error in full is:

Access to XMLHttpRequest at 'http://localhost:8080/socket.io/?EIO=3&transport=polling&t=N1QG96g' from origin 'http://localhost:4200' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

Thank you for reading, I've googled this error message and found some fixes like my attempt to add the client to the origins on the server but nothing has worked so far.

答:
pass origin: true to the cors middleware

```<code>app.use(cors({credentials: false, origin: true}));
</code>```

Body:
I am trying to use socket.io to connect my angular 8 app to my node.js server, my app is using REST endpoints on the same server without issue but socket.io always fails with CORS related error.

This is the relevant part from my server:

const app: Application = express();

app.use(cors({credentials: false}));

// The application will have it's routes on /api
app.use("/api", routes);
app.use(express.static(path.join(__dirname+'/public/')));
// Everything else will be redirected to the FE app
app.all("/*", (req: Request, res: Response) => {
    res.sendFile(path.join(__dirname+'/public/index.html'));
})

let port = process.env.PORT || configs.port;

app.listen(port, () => {
    console.log('server online on port', port);
});

let server = require('http').Server(app);
let io = require('socket.io')(server, { origins: ['http://localhost:4200'] });
// io.origins(['http://localhost:4200']);

io.on('connection', function (socket: Socket) {
    console.log('WEB SOCKET CONNECTION');
    socket.emit('news', { hello: 'world' });
    socket.on('my other event', function (data: any) {
        console.log(data);
    });
});

And this is on the client:

    this.socket = io.connect(configs.baseURL);

The error in full is:

Access to XMLHttpRequest at 'http://localhost:8080/socket.io/?EIO=3&transport=polling&t=N1QG96g' from origin 'http://localhost:4200' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

Thank you for reading, I've googled this error message and found some fixes like my attempt to add the client to the origins on the server but nothing has worked so far.

Body:
pass origin: true to the cors middleware

app.use(cors({credentials: false, origin: true}));


问:
Difference Between ViewResult() and ActionResult()
What is the difference between ViewResult() and ActionResult() in ASP.NET MVC?

```<code>public ViewResult Index()
{
    return View();
}

public ActionResult Index()
{
    return View();
}
</code>```

答:
To save you some time here is the answer from a link in a previous answer at https://forums.asp.net/t/1448398.aspx

ActionResult is an abstract class, and it's base class for ViewResult class.

In MVC framework, it uses ActionResult class to reference the object your action method returns. And invokes ExecuteResult method on it.

And ViewResult is an implementation for this abstract class. It will try to find a view page (usually aspx page) in some predefined paths(/views/controllername/, /views/shared/, etc) by the given view name.

It's usually a good practice to have your method return a more specific class. So if you are sure that your action method will return some view page, you can use ViewResult. But if your action method may have different behavior, like either render a view or perform a redirection. You can use the more general base class ActionResult as the return type.

Body:
What is the difference between ViewResult() and ActionResult() in ASP.NET MVC?

public ViewResult Index()
{
    return View();
}

public ActionResult Index()
{
    return View();
}


问:
How to automatically refresh data when opening Excel document using existing ODBC connection?
Already created an ODBC connection to get data from a file in our SQL server. It works fine when executing the ODBC in Excel manually.

Now I would like to have an Excel file that automatically, on opening, executes that ODBC connection and updates the data. But I don't know how to start my VBA code.

答:
Do you have SQL server admin privileges that would allow you to create stored procedures? If so, then you can create a query that can be externally linked to your excel document.

If that is not available to you, I would suggest re-creating the SQL query within VBA. If you only need a specific range of data (say within a date range or certain product) then you could modify the command text of the ODBC connection to your liking under the Data ribbon. Additionally, the file can refresh the data upon opening the file if the checkbox "Refresh data when opening the file" has been ticked in the Connection Properties.


问:
std::lower_bound and comparator function with different types?
I have an array of structures, sorted on a member of a structure, something like:

```<code>struct foo
{
    int bar;
    double baz;
};

// An array of foo, sorted on .bar
foo foos[] = { ........ };
// foos[0] = {0, 0.245}
// foos[1] = {1, -943.2}
// foos[2] = {2, 304.222}
// etc...
</code>```

I want to find the element with a specific .bar value. It might or might not be in the array, and I'd like to do it in O(log(n)) time, since the array is sorted.

std::lower_bound is what I'd normally go for, but I need to specify a comparison function. However, the type of the members of the array (struct foo) and the searched value (int) are not the same, thus, my comparator is:

```<code>bool comp(foo a, int b)
{
    // ...
}
// --- or ---
bool comp(int a, foo b)
{
    // ...
}
</code>```

It looks like the first will work with gcc, but I was wondering if the order of the arguments to the comparison function was specified by the standard, or if I'm relying on compiler behavior.

I'd like to avoid constructing a foo to pass to std::lower_bound here, as a full foo isn't required, and could be costly. My other option would be to wrap the foo * in a custom iterator that only exposed the .bar member.

答:
This should really be a comment to wilhelmtell's post, but I don't have enough points to do that yet...

I just wanted to point out that this also works for the MS compiler, but you'll need to define

```<code>comp(foo lhs, foo rhs)
</code>```

otherwise your code won't compile in debug mode.

ContentLicense: CC BY-SA 2.5

Body:
I have an array of structures, sorted on a member of a structure, something like:

struct foo
{
    int bar;
    double baz;
};

// An array of foo, sorted on .bar
foo foos[] = { ........ };
// foos[0] = {0, 0.245}
// foos[1] = {1, -943.2}
// foos[2] = {2, 304.222}
// etc...

I want to find the element with a specific .bar value. It might or might not be in the array, and I'd like to do it in O(log(n)) time, since the array is sorted.

std::lower_bound is what I'd normally go for, but I need to specify a comparison function. However, the type of the members of the array (struct foo) and the searched value (int) are not the same, thus, my comparator is:

bool comp(foo a, int b)
{
    // ...
}
// --- or ---
bool comp(int a, foo b)
{
    // ...
}

It looks like the first will work with gcc, but I was wondering if the order of the arguments to the comparison function was specified by the standard, or if I'm relying on compiler behavior.

I'd like to avoid constructing a foo to pass to std::lower_bound here, as a full foo isn't required, and could be costly. My other option would be to wrap the foo * in a custom iterator that only exposed the .bar member.

Body:
This should really be a comment to wilhelmtell's post, but I don't have enough points to do that yet...

I just wanted to point out that this also works for the MS compiler, but you'll need to define

comp(foo lhs, foo rhs)

otherwise your code won't compile in debug mode.


问:
Dynamic loading of classes can't address namespace/use
I have noticed that when I am using namespacing that loading classes dynamically doesn't work the same as when I'm loading them statically. So, for instance, without the use of namespaces the following are equivalent in their action of instantiating a class called FooBar:

```<code>$foobar = new FooBar();
</code>```

and

```<code>$classname = "FooBar";
$foobar = new $classname;
</code>```

However if when using namespacing I have some code like this:

```<code><?php

namespace Structure\Library;

$foobar = new UserService();
$classname = "UserService";
$barfoo = new $classname;
</code>```

In this case the UserService class's fully qualified name is Structure\Library\UserService and if I use the fully qualified name it works in both cases but if I use just the shortcut name of 'UserService' it only works when instantiated with the static method. Is there a way to get it to work for both?

P.S. I am using an autoloader for all classes ... but I'm assuming that the problem is happening before the autoloader and is effecting the class string that is passed to the autoloader.

答:
The following dynamically instantiates $barfoo as a Structure\Library\UserService object:

```<code>namespace Structure\Library;

$classname = __NAMESPACE__ . "\\" . "UserService";
$barfoo = new $classname;
</code>```

Body:
I have noticed that when I am using namespacing that loading classes dynamically doesn't work the same as when I'm loading them statically. So, for instance, without the use of namespaces the following are equivalent in their action of instantiating a class called FooBar:

$foobar = new FooBar();

and

$classname = "FooBar";
$foobar = new $classname;

However if when using namespacing I have some code like this:

<?php

namespace Structure\Library;

$foobar = new UserService();
$classname = "UserService";
$barfoo = new $classname;

In this case the UserService class's fully qualified name is Structure\Library\UserService and if I use the fully qualified name it works in both cases but if I use just the shortcut name of 'UserService' it only works when instantiated with the static method. Is there a way to get it to work for both?

P.S. I am using an autoloader for all classes ... but I'm assuming that the problem is happening before the autoloader and is effecting the class string that is passed to the autoloader.

Body:
The following dynamically instantiates $barfoo as a Structure\Library\UserService object:

namespace Structure\Library;

$classname = __NAMESPACE__ . "\\" . "UserService";
$barfoo = new $classname;


问:
Microsoft Access Filter Query Via Combo Box
I need to create a form in Microsoft Access that will filter a query that I have created. I have a list of computer serial numbers and the corresponding computer lab where they are located. I would like to have a form where my users can use a combo box to select a lab and then see a list of all of the computers that are in that lab. I am unsure as to how to set up this form.</p>

答:
Put a drop down on the form and as the RowSource enter there something lime this:

    SELECT computerLab FROM MyTable GROUP BY computerLab
```

<p>The On Change event would look like this:</p>

<pre class="lang-vb prettyprint-override"><code>Private Sub cmbComputerLab_Change()
    If IsEmpty(cmbComputerLab) Then
        Me.RecordSource = "SELECT * FROM MyTable "
    Else
        Me.RecordSource = "SELECT * FROM MyTable WHERE computerLab = '" & cmbComputerLab & "'"
    End If
End Sub
</code>```

OwnerDisplayName: Patrick Smith

Body:
Put a drop down on the form and as the RowSource enter there something lime this:

    SELECT computerLab FROM MyTable GROUP BY computerLab

The On Change event would look like this:

Private Sub cmbComputerLab_Change()
    If IsEmpty(cmbComputerLab) Then
        Me.RecordSource = "SELECT * FROM MyTable "
    Else
        Me.RecordSource = "SELECT * FROM MyTable WHERE computerLab = '" & cmbComputerLab & "'"
    End If
End Sub


问:
How to make an image/object jump infinite times?
I am trying to make a clone of flappy bird to learn pygame and I'm a beginner. Just doing the basics, and I want the image to jump whenever the user presses space button or else the image keeps falling down. The problem I'm getting is that if I keep the space button pressed, it will keep flying upwards rather than just a single jump at a time. How do I fix this? (Someone explain the basic physics required to apply for the jump in flappy bird)

```<code>import pygame
pygame.init()

screen = pygame.display.set_mode((500,500))
c = pygame.image.load('cookie.png')

run = True
x,y = 50,50

while run:
    screen.fill((255,255,255))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()

    if keys[pygame.K_SPACE]:
        y -= 1
    else:
        y += 0.2

    screen.blit(c, (x,y))
    pygame.display.update()

pygame.quit()

</code>```

答:
The states which are returned by pygame.key.get_pressed() as long a key is hold down. The KEYDOWN occurs only once when the key is pressed.

Use the event to lift the bird. But the position of the bird has to be computed in the main loop, to keep the bird falling down continuously.

Furthermore use pygame.time.Clock respectively .tick() to c ontrol the flops per second:

import pygame
pygame.init()

screen = pygame.display.set_mode((500,500))
clock = pygame.time.Clock()

c = pygame.image.load('cookie.png')
run = True
x,y = 50,50

while run:
    clock.tick(60)

    fly = False
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        elif event.type == pygame.KEYDOWN:
           fly = event.key == pygame.K_SPACE

    if fly:
        y -= 20
    else:
        y += 1

    screen.fill((255,255,255))
    screen.blit(c, (x,y))
    pygame.display.update()

pygame.quit()
```

Body:
I am trying to make a clone of flappy bird to learn pygame and I'm a beginner. Just doing the basics, and I want the image to jump whenever the user presses space button or else the image keeps falling down. The problem I'm getting is that if I keep the space button pressed, it will keep flying upwards rather than just a single jump at a time. How do I fix this? (Someone explain the basic physics required to apply for the jump in flappy bird)

import pygame
pygame.init()

screen = pygame.display.set_mode((500,500))
c = pygame.image.load('cookie.png')

run = True
x,y = 50,50

while run:
    screen.fill((255,255,255))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()

    if keys[pygame.K_SPACE]:
        y -= 1
    else:
        y += 0.2

    screen.blit(c, (x,y))
    pygame.display.update()

pygame.quit()


问:
How to retry fetch in a loop when it throws an error
I have the following JS function:

```<code>func() {
  return fetch({
    ...
  }).then({
    ...
  })catch({
    ...
  })
}
</code>```

In it I return a promise returned by fetch(). In the event that it fails (ie calls catch() block) I want to repeat the whole thing. Something like having the whole thing in a while (true) loop, but I can't figure out how to do this with promises.

Any suggestions?

答:
You can simply write a loop and count down the attempts until one succeeds or you run out. async/await makes this easy. See below for a minimal, complete example.

Note that the fetch API uses the response.ok flag to ensure that the response status falls in the 200 range. Wrapping with a try/catch is only sufficient to cover connection failures. If the response indicates a bad request, a retry is likely inappropriate. This code resolves the promise in such cases but you could consider !response.ok as an error and retry if you wish.

const fetchWithRetry = async (url, opts, tries=2) => {
  const errs = [];

  for (let i = 0; i < tries; i++) {
    // log for illustration
    console.log(`trying GET '${url}' [${i + 1} of ${tries}]`);

    try {
      return await fetch(url, opts);
    }
    catch (err) {
      errs.push(err);
    }
  }

  throw errs;
};

fetchWithRetry("https://httpstat.us/400")
  .then(response => console.log("response is OK? " + response.ok))
  .catch(err => console.error(err));

fetchWithRetry("foo")
  .catch(err => console.error(err.map(e => e.toString())));

fetchWithRetry("https://httpstat.us/200")
  .then(response => response.text())
  .then(data => console.log(data))
  .catch(err => console.error(err));```

Pass the tries parameter as -1 if you want an infinite number of retries (but this doesn't seem like the common case to me).

Body:
I have the following JS function:

func() {
  return fetch({
    ...
  }).then({
    ...
  })catch({
    ...
  })
}

In it I return a promise returned by fetch(). In the event that it fails (ie calls catch() block) I want to repeat the whole thing. Something like having the whole thing in a while (true) loop, but I can't figure out how to do this with promises.

Any suggestions?

Body:
You can simply write a loop and count down the attempts until one succeeds or you run out. async/await makes this easy. See below for a minimal, complete example.

Note that the fetch API uses the response.ok flag to ensure that the response status falls in the 200 range. Wrapping with a try/catch is only sufficient to cover connection failures. If the response indicates a bad request, a retry is likely inappropriate. This code resolves the promise in such cases but you could consider !response.ok as an error and retry if you wish.

const fetchWithRetry = async (url, opts, tries=2) => {
  const errs = [];

  for (let i = 0; i < tries; i++) {
    // log for illustration
    console.log(`trying GET '${url}' [${i + 1} of ${tries}]`);

    try {
      return await fetch(url, opts);
    }
    catch (err) {
      errs.push(err);
    }
  }

  throw errs;
};

fetchWithRetry("https://httpstat.us/400")
  .then(response => console.log("response is OK? " + response.ok))
  .catch(err => console.error(err));

fetchWithRetry("foo")
  .catch(err => console.error(err.map(e => e.toString())));

fetchWithRetry("https://httpstat.us/200")
  .then(response => response.text())
  .then(data => console.log(data))
  .catch(err => console.error(err));

Pass the tries parameter as -1 if you want an infinite number of retries (but this doesn't seem like the common case to me).


问:
CUDA: Unified Memory and change of pointer address?
I'm using cuBlas to create a library for some matrix operations. I first implemented a matrix mult

Snippet of library header class (.h file)

#include "cusolverDn.h"  // NOLINT
#include "cuda_runtime.h"  // NOLINT
#include "device_launch_parameters.h"  // NOLINT

namespace perception_core {
namespace matrix_transform {

class CudaMatrixTransformations {
 public:
  CudaMatrixTransformations();

  ~CudaMatrixTransformations();

  void MatrixMultiplicationDouble(double *A, double *B, double *C, const int m, const int k, const int n);

 private:
  // Cublas stuff
  cudaError_t cudaStat1;
  cudaError_t cudaStat2;
  cublasHandle_t cublasH;
  cublasStatus_t cublas_status;

};

}  // namespace matrix_transform
}  // namespace perception_core

#endif  // LIB_CUDA_ROUTINES_INCLUDE_MATRIX_TRANSFORMS_H_
```

<p>Snippet of library class implementation for multiplication (.cu file)</p>

<pre class="lang-cpp prettyprint-override"><code>// This calculates the matrix mult C(m,n) = A(m,k) * B(k,n)
void CudaMatrixTransformations::MatrixMultiplicationDouble(
    double *A, double *B, double *C, int m, int k, const int n) {

      // Calculate size of each array
      size_t s_A = m * k;
      size_t s_B = k * n;
      size_t s_C = m * n;

      // Create the arrays to use in the GPU
      double *d_A = NULL;
      double *d_B = NULL;
      double *d_C = NULL;

      // Allocate memory
      cudaStat1 = cudaMallocManaged(&d_A, s_A * sizeof(double));
      cudaStat2 = cudaMallocManaged(&d_B, s_B * sizeof(double));
      assert(cudaSuccess == cudaStat1);
      assert(cudaSuccess == cudaStat2);
      cudaStat1 = cudaMallocManaged(&d_C, s_C * sizeof(double));
      assert(cudaSuccess == cudaStat1);

      // Copy the data to the device data
      memcpy(d_A, A, s_A * sizeof(double));
      memcpy(d_B, B, s_B * sizeof(double));

      // Set up stuff for using CUDA
      int lda = m;
      int ldb = k;
      int ldc = m;
      const double alf = 1;
      const double bet = 0;
      const double *alpha = &alf;
      const double *beta = &bet;

      cublas_status = cublasCreate(&cublasH);
      assert(cublas_status == CUBLAS_STATUS_SUCCESS);

      // Perform multiplication
        cublas_status = cublasDgemm(cublasH, // CUDA handle
        CUBLAS_OP_N, CUBLAS_OP_N, // no operation on matrices
        m, n, k, // dimensions in the matrices
        alpha, // scalar for multiplication
        d_A, lda, // matrix d_A and its leading dim
        d_B, ldb, // matrix d_B and its leading dim
        beta, // scalar for multiplication
        d_C, ldc // matrix d_C and its leading dim
        );

      cudaStat1 = cudaDeviceSynchronize();
      assert(cublas_status == CUBLAS_STATUS_SUCCESS);
      assert(cudaSuccess == cudaStat1);

        // Destroy the handle
        cublasDestroy(cublasH);

      C = (double*)malloc(s_C * sizeof(double));
      memcpy(C, d_C, s_C * sizeof(double));

      // Make sure to free resources
      if (d_A) cudaFree(d_A);
      if (d_B) cudaFree(d_B);
      if (d_C) cudaFree(d_C);

      return;
  }

CudaMatrixTransformations::CudaMatrixTransformations() {
    cublas_status = CUBLAS_STATUS_SUCCESS;
    cudaStat1 = cudaSuccess;
    cudaStat2 = cudaSuccess;
  }
</code>```

Then I created a gtest program to test my function. Where I passed a double *result = NULL; as my C parameter in my MatrixMultiplicationDouble function.

Snippet of gtest program (.cc file)

TEST_F(MatrixTransformsTest, MatrixMultiplication) {
  double loc_q[] = {3, 4, 5, 6, 7 ,8};
  double *q = loc_q;
  double loc_w[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
  double *w = loc_w;
  double *result = NULL;
  double loc_result[M_ROWS * M_COLS] = {14, 50, 86, 122, 23, 86, 149, 212};
  matrix_result = loc_result;

  size_t m = 4;
  size_t k = 3;
  size_t n = 2;

  perception_core::matrix_transform::CudaMatrixTransformations transforms;
  transforms.MatrixMultiplicationDouble(w, q, result, m, k, n);
  auto rr = std::addressof(result);
  printf("\nC addr: %p\n", rr);

  std::cout << "result:\n";
  print_matrix(result, m, n);
  EXPECT_TRUE(compare<double>(result, matrix_result, m * n));
}
```

<p>The routine in cuBlas works fine as I can see the result when I print the matrix inside the <code>.cu</code> file. However, when I try to access <code>result</code> in my gtest file, I get a seg fault. Upon further inspection I noticed that the address of the <code>result</code> pointer is <strong>different</strong> inside the <code>.cu</code> and in the <code>.cpp</code>. As an example I get: </p>

<pre class="lang-sh prettyprint-override"><code>C addr: 0x7ffc5749db08 (inside .cu)

C addr: 0x7ffc5749dba0 (inside .cpp)
</code>```

I thought that by using Unified Memory I could access that pointer either from host or device. I can't seem to find an answer as to why this address changes and fix the seg fault issue. Is there something I'm missing about using Unified Memory? Thank  you!

答:
This line isn't doing what you need:

```<code>cudaStat1 = cudaMallocManaged(&C, s_C * sizeof(double));
</code>```

when you modify the numerical value of the C pointer, that modification will not show up in the calling environment.  That is the nature of pass-by-value, and the numerical value of the C pointer is being passed by value when you call CudaMatrixTransformations::MatrixMultiplicationDouble

So that line will work inside your function (perhaps), but the results won't be passed back to the calling environment that way.

I would suggest reworking your code so that you handle C in a fashion similar to how you are handling A and B.  Create an extra pointer d_C, do your cudaMallocManaged on that, then before returning, memcpy the results from d_C back to C.  This assumes you are allocating properly for the C pointer before calling this function.

Also note that at the end you are freeing A and B - that's not what you want, I don't think.  You should free d_A, d_B, and d_C before returning.

There are other issues with your code as well.  For example you refer to returning a result pointer but I don't see any evidence of that.  I don't see any pointer named result, actually.  Furthermore, the function prototype (in the class definition) doesn't match your implementation.  The prototype suggests a return double* whereas your implementation returns void.

And since I'm listing observations, I don't think your use of addressof is giving you the information you presume it is.  If you're going to compare numerical pointer values, you need to compare the values themselves, not the address of the location where those values are stored.

Body:
I'm using cuBlas to create a library for some matrix operations. I first implemented a matrix mult

Snippet of library header class (.h file)

#include "cusolverDn.h"  // NOLINT
#include "cuda_runtime.h"  // NOLINT
#include "device_launch_parameters.h"  // NOLINT

namespace perception_core {
namespace matrix_transform {

class CudaMatrixTransformations {
 public:
  CudaMatrixTransformations();

  ~CudaMatrixTransformations();

  void MatrixMultiplicationDouble(double *A, double *B, double *C, const int m, const int k, const int n);

 private:
  // Cublas stuff
  cudaError_t cudaStat1;
  cudaError_t cudaStat2;
  cublasHandle_t cublasH;
  cublasStatus_t cublas_status;

};

}  // namespace matrix_transform
}  // namespace perception_core

#endif  // LIB_CUDA_ROUTINES_INCLUDE_MATRIX_TRANSFORMS_H_

Snippet of library class implementation for multiplication (.cu file)

// This calculates the matrix mult C(m,n) = A(m,k) * B(k,n)
void CudaMatrixTransformations::MatrixMultiplicationDouble(
    double *A, double *B, double *C, int m, int k, const int n) {

      // Calculate size of each array
      size_t s_A = m * k;
      size_t s_B = k * n;
      size_t s_C = m * n;

      // Create the arrays to use in the GPU
      double *d_A = NULL;
      double *d_B = NULL;
      double *d_C = NULL;

      // Allocate memory
      cudaStat1 = cudaMallocManaged(&d_A, s_A * sizeof(double));
      cudaStat2 = cudaMallocManaged(&d_B, s_B * sizeof(double));
      assert(cudaSuccess == cudaStat1);
      assert(cudaSuccess == cudaStat2);
      cudaStat1 = cudaMallocManaged(&d_C, s_C * sizeof(double));
      assert(cudaSuccess == cudaStat1);

      // Copy the data to the device data
      memcpy(d_A, A, s_A * sizeof(double));
      memcpy(d_B, B, s_B * sizeof(double));

      // Set up stuff for using CUDA
      int lda = m;
      int ldb = k;
      int ldc = m;
      const double alf = 1;
      const double bet = 0;
      const double *alpha = &alf;
      const double *beta = &bet;

      cublas_status = cublasCreate(&cublasH);
      assert(cublas_status == CUBLAS_STATUS_SUCCESS);

      // Perform multiplication
        cublas_status = cublasDgemm(cublasH, // CUDA handle
        CUBLAS_OP_N, CUBLAS_OP_N, // no operation on matrices
        m, n, k, // dimensions in the matrices
        alpha, // scalar for multiplication
        d_A, lda, // matrix d_A and its leading dim
        d_B, ldb, // matrix d_B and its leading dim
        beta, // scalar for multiplication
        d_C, ldc // matrix d_C and its leading dim
        );

      cudaStat1 = cudaDeviceSynchronize();
      assert(cublas_status == CUBLAS_STATUS_SUCCESS);
      assert(cudaSuccess == cudaStat1);

        // Destroy the handle
        cublasDestroy(cublasH);

      C = (double*)malloc(s_C * sizeof(double));
      memcpy(C, d_C, s_C * sizeof(double));

      // Make sure to free resources
      if (d_A) cudaFree(d_A);
      if (d_B) cudaFree(d_B);
      if (d_C) cudaFree(d_C);

      return;
  }

CudaMatrixTransformations::CudaMatrixTransformations() {
    cublas_status = CUBLAS_STATUS_SUCCESS;
    cudaStat1 = cudaSuccess;
    cudaStat2 = cudaSuccess;
  }

Then I created a gtest program to test my function. Where I passed a double *result = NULL; as my C parameter in my MatrixMultiplicationDouble function.

Snippet of gtest program (.cc file)

TEST_F(MatrixTransformsTest, MatrixMultiplication) {
  double loc_q[] = {3, 4, 5, 6, 7 ,8};
  double *q = loc_q;
  double loc_w[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
  double *w = loc_w;
  double *result = NULL;
  double loc_result[M_ROWS * M_COLS] = {14, 50, 86, 122, 23, 86, 149, 212};
  matrix_result = loc_result;

  size_t m = 4;
  size_t k = 3;
  size_t n = 2;

  perception_core::matrix_transform::CudaMatrixTransformations transforms;
  transforms.MatrixMultiplicationDouble(w, q, result, m, k, n);
  auto rr = std::addressof(result);
  printf("\nC addr: %p\n", rr);

  std::cout << "result:\n";
  print_matrix(result, m, n);
  EXPECT_TRUE(compare<double>(result, matrix_result, m * n));
}

The routine in cuBlas works fine as I can see the result when I print the matrix inside the .cu file. However, when I try to access result in my gtest file, I get a seg fault. Upon further inspection I noticed that the address of the result pointer is different inside the .cu and in the .cpp. As an example I get:

C addr: 0x7ffc5749db08 (inside .cu)

C addr: 0x7ffc5749dba0 (inside .cpp)

I thought that by using Unified Memory I could access that pointer either from host or device. I can't seem to find an answer as to why this address changes and fix the seg fault issue. Is there something I'm missing about using Unified Memory? Thank  you!

Body:
This line isn't doing what you need:

cudaStat1 = cudaMallocManaged(&C, s_C * sizeof(double));

when you modify the numerical value of the C pointer, that modification will not show up in the calling environment.  That is the nature of pass-by-value, and the numerical value of the C pointer is being passed by value when you call CudaMatrixTransformations::MatrixMultiplicationDouble

So that line will work inside your function (perhaps), but the results won't be passed back to the calling environment that way.

I would suggest reworking your code so that you handle C in a fashion similar to how you are handling A and B.  Create an extra pointer d_C, do your cudaMallocManaged on that, then before returning, memcpy the results from d_C back to C.  This assumes you are allocating properly for the C pointer before calling this function.

Also note that at the end you are freeing A and B - that's not what you want, I don't think.  You should free d_A, d_B, and d_C before returning.

There are other issues with your code as well.  For example you refer to returning a result pointer but I don't see any evidence of that.  I don't see any pointer named result, actually.  Furthermore, the function prototype (in the class definition) doesn't match your implementation.  The prototype suggests a return double* whereas your implementation returns void.

And since I'm listing observations, I don't think your use of addressof is giving you the information you presume it is.  If you're going to compare numerical pointer values, you need to compare the values themselves, not the address of the location where those values are stored.


问:
The connection to the server localhost:8080 was refused - did you specify the right host or port?
when i am trying to test the configuration of kubectl

```<code>kubectl get svc
</code>```

i am getting this

error: the server doesn't have a resource type "svc"

when I try this command

```<code>kubectl get services
</code>```

i am getting error:

The connection to the server localhost:8080 was refused - did you specify the right host or port?

and i am following this userguide to deploy a kubernetes application on my mac

https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html#eks-create-cluster

```<code>Admins-MacBook-Pro:~ Harshin$ kubectl version --short --client
Client Version: v1.10.3
</code>```

答:
You may have used sudo in the wrong place. Chown your home directory:

```<code>sudo chown -R loggedonuser .
</code>```

Body:
when i am trying to test the configuration of kubectl

kubectl get svc

i am getting this

error: the server doesn't have a resource type "svc"

when I try this command

kubectl get services

i am getting error:

The connection to the server localhost:8080 was refused - did you specify the right host or port?

and i am following this userguide to deploy a kubernetes application on my mac

https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html#eks-create-cluster

Admins-MacBook-Pro:~ Harshin$ kubectl version --short --client
Client Version: v1.10.3

Body:
You may have used sudo in the wrong place. Chown your home directory:

sudo chown -R loggedonuser .


问:
Get the focussed element on focus change
I'm trying to keep a record of the last text input element that had focus. My code:

```<code>document.addEventListener('focus', function(e) {
    var obj = document.activeElement;
    if(obj instanceof HTMLInputElement && obj.type == 'text'){
        console.log('true');
    }
}, false);
</code>```

Of course I did console.log(obj); and it triggers fine on the body element, but no where else. Other than that it seems it only triggers once. I'm not sure what I'm doing wrong or if this is even the right approach to do it. So I hope you guys can help me out.

Note: I know I can easily solve the problem with a click event instead, but anyone using Tab to go through the form elements would have an issue. So that's not a solution.

答:
You can bind with window and allow the bubbling and you will get the element with target.

window.addEventListener('focus', function(e) {
    if (e.target.id) console.log(e.target.id)
}, true);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="tb1">
<input type="button" id="btn1" value="button">
test</code>```

Body:
I'm trying to keep a record of the last text input element that had focus. My code:

document.addEventListener('focus', function(e) {
    var obj = document.activeElement;
    if(obj instanceof HTMLInputElement && obj.type == 'text'){
        console.log('true');
    }
}, false);

Of course I did console.log(obj); and it triggers fine on the body element, but no where else. Other than that it seems it only triggers once. I'm not sure what I'm doing wrong or if this is even the right approach to do it. So I hope you guys can help me out.

Note: I know I can easily solve the problem with a click event instead, but anyone using Tab to go through the form elements would have an issue. So that's not a solution.

Body:
You can bind with window and allow the bubbling and you will get the element with target.

window.addEventListener('focus', function(e) {
    if (e.target.id) console.log(e.target.id)
}, true);

<input type="text" id="tb1">
<input type="button" id="btn1" value="button">
<a href="#foo" id="link1">test</a>


问:
How to send an event to gtag?
I can’t catch the target with the event type, the rest of the targets (via the transition link) work successfully

doing so

Goal Setting -> Own

Target Description -> Event

Target Details ->
Category equals custom
Action equals add_2_order

here

In the code I do it and does not work:

```<code>gtag('event', 'add_2_order', {'event_category':'custom'});
</code>```

still did and still doesn't work

```<code>gtag('event', 'my_add_2_order', {'event_category':'custom','event_action':'add_2_order'});
</code>```

still true .. what am I doing wrong and where to look?
gtag in the head is inserted, but not a single event target works and all goals work if they hit the page

答:
This is the right code:

```<code>gtag('event', 'add_2_order', { 'event_category': 'custom' });
</code>```

If it doesn't work it means that something is blocking the event and you can't find it in the event report either.

Title: How to send an event to gtag?

Body:
I can’t catch the target with the event type, the rest of the targets (via the transition link) work successfully

doing so

Goal Setting -> Own

Target Description -> Event

Target Details ->
Category equals custom
Action equals add_2_order

here

In the code I do it and does not work:

gtag('event', 'add_2_order', {'event_category':'custom'});

still did and still doesn't work

gtag('event', 'my_add_2_order', {'event_category':'custom','event_action':'add_2_order'});

still true .. what am I doing wrong and where to look?
gtag in the head is inserted, but not a single event target works and all goals work if they hit the page

Body:
This is the right code:

gtag('event', 'add_2_order', { 'event_category': 'custom' });

If it doesn't work it means that something is blocking the event and you can't find it in the event report either.


问:
How to assert an actual value against 2 or more expected values?
I'm testing a method to see if it returns the correct string. This string is made up of a lot of lines whose order might change, thus usually giving 2 possible combinations. That order is not important for my application.

However, because the order of the lines might change, writing just an Assert statement will not work, since sometimes it will pass the test, and sometimes it will fail the test.

So, is it possible to write a test that will assert an actual string value against 2 or more expected string values and see if it is equal to any of them?

答:
The simplest/most efficient might be

```<code>assert str.equals(result1) || str.equals(result2);
</code>```

This will effectively have no overhead when you don't have assertions turned on.

Body:
The simplest/most efficient might be

assert str.equals(result1) || str.equals(result2);

This will effectively have no overhead when you don't have assertions turned on.


问:
Is Laravel blade '@include()' case-sensitive?
I'm getting a "blade not found shop.cart.favorites" error when running in Docker on Ubuntu.  (Therefore: "case-sensitive file system.")

I suspect that the culprit is case-sensitivity.  The path to the blade file is:

```<code> resources/views/Shop/Cart/favorites.blade.php
                 ^    ^
</code>```

Did I guess correctly?

答:
In the process of rendering a View, the view() method in Laravel checks to see if a Blade template file exists at the path provided using the PHP built-in method file_exists().

Although the docs don't mention it at all, it has long been observed that this function can be case sensitive (typically on *nix-based filesystems, though not on Windows).  But since you don't necessarily know where your code will be run (e.g. if you are creating a package), best practice for cross-platform compatibility is to use only lowercase filenames for Blade template files.

Body:
I'm getting a "blade not found shop.cart.favorites" error when running in Docker on Ubuntu.  (Therefore: "case-sensitive file system.")

I suspect that the culprit is case-sensitivity.  The path to the blade file is:

 resources/views/Shop/Cart/favorites.blade.php
                 ^    ^

Did I guess correctly?


问:
How to place two div side-by-side in a HTML page
I have created a simple HTML page, where I have a parent div with over-flow enabled in both axes. Now within that div, there are 2 divs which I want to place side by side.

#Result {
  margin: 0 auto;
  padding: 0;
  background-color: rgba(0, 0, 0, .02);
  padding-top: 25px;
  font-size: 16px;
  overflow: scroll;
  width: 99%;
  height: calc(100% - 90px - 70px);
  position: absolute;
}

#Left,
#Right {
  height: calc(99vh - 90px - 70px);
  width: 28vw;
  margin: 0 auto;
  padding: 0;
  display: inline-block;
  float: left;
  text-align: center;
  background-color: rgba(0, 0, 0, .04);
  border-right: 1px solid #a6a6a6;
  border-bottom: 1px solid #a6a6a6;
}

#Right {
  background-color: rgba(0, 0, 0, .5);
  border-right: 0px solid #737373;
  padding-left: 15px;
  margin-right: 15px;
  width: 2000px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='Result'>
  <div id='Left'>

  </div>
  <div id='Right'>

  </div>
</div></code>```

Codepen - https://codepen.io/Volabos/pen/qBdNyPa?editors=1100

However unfortunately, the 3rd div is moved down if its width is taken a large number. How can I place the 2nd and 3rd div side by side?

答:
You can use float:left; and clear:right;

https://codepen.io/osmanraifgunes/pen/PoqzByB?editors=1100

Body:
I have created a simple HTML page, where I have a parent div with over-flow enabled in both axes. Now within that div, there are 2 divs which I want to place side by side.

#Result {
  margin: 0 auto;
  padding: 0;
  background-color: rgba(0, 0, 0, .02);
  padding-top: 25px;
  font-size: 16px;
  overflow: scroll;
  width: 99%;
  height: calc(100% - 90px - 70px);
  position: absolute;
}

#Left,
#Right {
  height: calc(99vh - 90px - 70px);
  width: 28vw;
  margin: 0 auto;
  padding: 0;
  display: inline-block;
  float: left;
  text-align: center;
  background-color: rgba(0, 0, 0, .04);
  border-right: 1px solid #a6a6a6;
  border-bottom: 1px solid #a6a6a6;
}

#Right {
  background-color: rgba(0, 0, 0, .5);
  border-right: 0px solid #737373;
  padding-left: 15px;
  margin-right: 15px;
  width: 2000px;
}

Codepen - https://codepen.io/Volabos/pen/qBdNyPa?editors=1100

However unfortunately, the 3rd div is moved down if its width is taken a large number. How can I place the 2nd and 3rd div side by side?


问:
COM library not creatable on SQL Server 2014 COM
We are running SQL Server 2014 64 bit on Windows Server 2012 64 bit and having troubles with an old COM library written in VB6.

sp_OACreate is returning null with no error.

The COM library is registered and located on the server itself and it can be successfully invoked by a test program executed from the server desktop using the SQL account or other account.

Other COM objects such as "Scripting.FileSystemObject" can be created and destroyed in SQL using the same login or other logins. Only our custom COM library is failing.

Would this be a permissions issue at the server or database level or could it be something else? We use this same COM library on many other SQL Server.

答: The component being a VB6 creation it was required to register it to run out of process.</p>


问:
Haskell streaming - how to separate 1 stream into 2 after copy?
In haskell streaming, there is an example of copy

```<code>>>> (S.toList . mapped S.toList . chunksOf 5) $  (S.toList . mapped S.toList . chunksOf 3) $ S.copy $ each [1..10]
[[1,2,3,4,5],[6,7,8,9,10]] :> ([[1,2,3],[4,5,6],[7,8,9],[10]] :> ())
</code>```

Is it possible to separate this into two "clean" streams such that it can print below results?

```<code>>>>S.print stream1
[[1,2,3,4,5],[6,7,8,9,10]]
>>>S.print stream2
[[1,2,3],[4,5,6],[7,8,9],[10]]
</code>```

Note there is no more ':>' in the above result. More generally, I am not sure whether there are functions that 'simplify' the nested streams (or stream of streams) from m or (Of a) part in Stream (Of a) m r

```<code>f1::Stream (Of a) (Stream (Of b) m) r -> Stream (Of b) m r
f2::Stream (Of a) (Stream (Of b) m) r -> Stream (Of a) m r
f3::Stream (Stream (Of a) m) r -> Stream (Of a) m r
</code>```

[Update]

The background of this question is I am looking for idiomatic ways to re-use an underlying stream multiple times. The stream is pulled from database and the IO can be expensive. I also want to get a reference to the intermediate streams so that I can better structure my code. Some mock code:

```<code>my-stream-fn = do
  original_stream <- pull_from_database
  let  (o1, s1) = calc_moving_average $ S.copy original_stream
       (o2, s2) = calc_max $ S.copy o1
       (o3, s3) = calc_min $ S.copy o2
  S.print $ S.zipWith3 (\x y z-> (x, y, z)) s1 s2 s3
</code>```

What I wish is o1 o2 and o3 being exactly the same as original_stream and pull_from_database IO operation done only once when original_stream is pulled.

答:
```<code>f1 = S.effects @(Stream (Of _) _)
  :: Monad m
  => Stream (Of a) (Stream (Of b) m) r
  -> Stream (Of b) r
f2 = hoist @(Stream (Of _)) S.effects
  :: Monad m
  => Stream (Of a) (Stream (Of b) m) r
  -> Stream (Of a) m r
</code>```

(typevars renamed for clarity, see docs for effects), and f3 doesn't kind-check.

It feels like you're trying to defeat the point of streaming. You construct the pipeline, source to sink, and run it - the key is that there's no (implicit) intermediate accumulation of values. Your question is slightly loose and thus different to answer precisely, but if you wish to run all the effects of the first stream, then all the effects of the second stream, then you must be willing to store the (computation representing the) second stream until the first stream has finished effecting => you've accumulated the second stream (and thus not really streamed it). Hence why S.copy is designed for interleaving the effects. Cf. this github issue.

[Response to Update]

I think part of what's confusing you is that you're using pure streams, and in the absence of effects then the restrictions are less obviously-motivated. Use identifiers for the components of the pipeline, not the partial results. Also in your example, then you should be combining folds, eg.

```<code>import qualified Control.Foldl as L
import qualified Streaming.Prelude as S

myStreamFn =
  let movingAvg n = {-# ... #-}
      combinedAcc = (,,) <$> L.minimum <*> L.maximum <*> movingAvg 10
  in  S.print
   $  L.purely S.fold combinedAcc
   $  pullFromDatabase
</code>```

Another function you might like to consider is S.store, eg.

```<code>myStreamFn
  = pullFromDatabase
  & S.store S.maximum
  & S.store (L.purely S.fold L.minimum)
  & S.store movingAvg
  & S.print
</code>```

Body:
In haskell streaming, there is an example of copy

>>> (S.toList . mapped S.toList . chunksOf 5) $  (S.toList . mapped S.toList . chunksOf 3) $ S.copy $ each [1..10]
[[1,2,3,4,5],[6,7,8,9,10]] :> ([[1,2,3],[4,5,6],[7,8,9],[10]] :> ())

Is it possible to separate this into two "clean" streams such that it can print below results?

>>>S.print stream1
[[1,2,3,4,5],[6,7,8,9,10]]
>>>S.print stream2
[[1,2,3],[4,5,6],[7,8,9],[10]]

Note there is no more ':>' in the above result. More generally, I am not sure whether there are functions that 'simplify' the nested streams (or stream of streams) from m or (Of a) part in Stream (Of a) m r

f1::Stream (Of a) (Stream (Of b) m) r -> Stream (Of b) m r
f2::Stream (Of a) (Stream (Of b) m) r -> Stream (Of a) m r
f3::Stream (Stream (Of a) m) r -> Stream (Of a) m r

[Update]

The background of this question is I am looking for idiomatic ways to re-use an underlying stream multiple times. The stream is pulled from database and the IO can be expensive. I also want to get a reference to the intermediate streams so that I can better structure my code. Some mock code:

my-stream-fn = do
  original_stream <- pull_from_database
  let  (o1, s1) = calc_moving_average $ S.copy original_stream
       (o2, s2) = calc_max $ S.copy o1
       (o3, s3) = calc_min $ S.copy o2
  S.print $ S.zipWith3 (\x y z-> (x, y, z)) s1 s2 s3

What I wish is o1 o2 and o3 being exactly the same as original_stream and pull_from_database IO operation done only once when original_stream is pulled.

Body:
f1 = S.effects @(Stream (Of _) _)
  :: Monad m
  => Stream (Of a) (Stream (Of b) m) r
  -> Stream (Of b) r
f2 = hoist @(Stream (Of _)) S.effects
  :: Monad m
  => Stream (Of a) (Stream (Of b) m) r
  -> Stream (Of a) m r

(typevars renamed for clarity, see docs for effects), and f3 doesn't kind-check.

It feels like you're trying to defeat the point of streaming. You construct the pipeline, source to sink, and run it - the key is that there's no (implicit) intermediate accumulation of values. Your question is slightly loose and thus different to answer precisely, but if you wish to run all the effects of the first stream, then all the effects of the second stream, then you must be willing to store the (computation representing the) second stream until the first stream has finished effecting => you've accumulated the second stream (and thus not really streamed it). Hence why S.copy is designed for interleaving the effects. Cf. this github issue.

[Response to Update]

I think part of what's confusing you is that you're using pure streams, and in the absence of effects then the restrictions are less obviously-motivated. Use identifiers for the components of the pipeline, not the partial results. Also in your example, then you should be combining folds, eg.

import qualified Control.Foldl as L
import qualified Streaming.Prelude as S

myStreamFn =
  let movingAvg n = {-# ... #-}
      combinedAcc = (,,) <$> L.minimum <*> L.maximum <*> movingAvg 10
  in  S.print
   $  L.purely S.fold combinedAcc
   $  pullFromDatabase

Another function you might like to consider is S.store, eg.

myStreamFn
  = pullFromDatabase
  & S.store S.maximum
  & S.store (L.purely S.fold L.minimum)
  & S.store movingAvg
  & S.print


问:
How to correctly query the mysql database from bash script?
I've been trying to correctly create a user and database for an hour using the bash script, but I'm still getting error messages. I paste the code below. I will be grateful for your help!

```<code>#!/bin/bash

username="useursur"
passworduser="dnfndfvjdngdg"

sudo mysql -u $username -p$passworduser <<EOF
    CREATE USER 'wpdb'@'localhost' IDENTIFIED BY 'fsafdasdfsadfasdf';
    CREATE DATABASE wpdb;
    GRANT ALL PRIVILEGES ON wpdb.* TO 'wpdb';
    FLUSH PRIVILEGES;
EOF
</code>```

I changed the command to

```<code>sudo mysql -u $username -p$passworduser -e "CREATE USER 'wpdb'@'localhost' IDENTIFIED BY 'fsafdasdfsadfasdf';CREATE DATABASE wpdb;GRANT ALL PRIVILEGES ON wpdb.* TO 'wpdb';FLUSH PRIVILEGES;"
</code>```

As a result I get this error:

```<code>mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 1133 (42000) at line 1: Can't find any matching row in the user table
</code>```

答:
You need to specify the user and host when you GRANT.

```<code>GRANT ALL PRIVILEGES ON wpdb.* TO 'wpdb';
</code>```

Should be:

```<code>GRANT ALL PRIVILEGES ON wpdb.* TO 'wpdb'@'localhost';
</code>```

Body:
I've been trying to correctly create a user and database for an hour using the bash script, but I'm still getting error messages. I paste the code below. I will be grateful for your help!

#!/bin/bash

username="useursur"
passworduser="dnfndfvjdngdg"

sudo mysql -u $username -p$passworduser <<EOF
    CREATE USER 'wpdb'@'localhost' IDENTIFIED BY 'fsafdasdfsadfasdf';
    CREATE DATABASE wpdb;
    GRANT ALL PRIVILEGES ON wpdb.* TO 'wpdb';
    FLUSH PRIVILEGES;
EOF

I changed the command to

sudo mysql -u $username -p$passworduser -e "CREATE USER 'wpdb'@'localhost' IDENTIFIED BY 'fsafdasdfsadfasdf';CREATE DATABASE wpdb;GRANT ALL PRIVILEGES ON wpdb.* TO 'wpdb';FLUSH PRIVILEGES;"

As a result I get this error:

mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 1133 (42000) at line 1: Can't find any matching row in the user table

Body:
You need to specify the user and host when you GRANT.

GRANT ALL PRIVILEGES ON wpdb.* TO 'wpdb';

Should be:

GRANT ALL PRIVILEGES ON wpdb.* TO 'wpdb'@'localhost';


问:
Global error handling of file_get_contents() PHP
I am occasionally getting errors while using file_get_contents and its used a fair bit in my script. I know I can suppress errors individually with @file_get_contents and that I can set global error messages with

```<code>//error handler function
function customError($errno)
  {
  echo 'Oh No!';
  }

//set error handler
set_error_handler("customError");
</code>```

But how do I specifically set an error handler for all file_get_content's uses?

Thanks

答: you may set your custom error_handler before invoking file_get_contents and then use restore_error_handler() function right after file_get_contents. if there is multiple usage of file_get_contents in your code, you may wrap file_get_contents by some custom function.</p>

Body:
I am occasionally getting errors while using file_get_contents and its used a fair bit in my script. I know I can suppress errors individually with @file_get_contents and that I can set global error messages with

//error handler function
function customError($errno)
  {
  echo 'Oh No!';
  }

//set error handler
set_error_handler("customError");

But how do I specifically set an error handler for all file_get_content's uses?

Thanks


问:
Prevent one failed subtask failing all tasks in Flyte
I have a dynamic_task which kicks off a number of python_tasks. However, as soon as one of the python_tasks fails, the other ones that are still running would fail as well. Is this by design? Is there a way to change this behavior so that other tasks can still complete without failing?

答:
This is by design, as a means to save resources, but it is configurable.  Presumably, dynamic tasks are related to each other, and downstream tasks will need the output of all of them.  So if one fails, the default behavior is to fail the rest.

If you'd like to change this, create your dynamic task with a float as this argument in the decorator: https://github.com/lyft/flytekit/blob/d4cfedc4c580f08bf904e6e474a0b948a4608737/flytekit/common/tasks/sdk_dynamic.py#L84


问:
Nginx inside docker container not responding
My Dockerfile is:

```<code>FROM nginx
</code>```

I start a container on AWS docker run -d --name ng_ex -p 8082:80 nginx and :

```<code>$ sudo docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES
6489cbb430b9        nginx               "nginx -g 'daemon of…"   22 minutes ago      Up 22 minutes       0.0.0.0:8082->80/tcp   ng_ex
</code>```

And inside a container:

```<code>service nginx status
[ ok ] nginx is running.
</code>```

But when I try to send a request thought browser on my.ip.address:8082 I get a timeout error instead Nginx welcome page. What is my mistake and how to fix it?

答:
If you're on an VM on aws, means that you must setup your security group to allow connection on port 8082 from all internet or only your IP/proxyIP. (The timeout may come from this).

Then my.ip.address:8082 should works

If you're inside your VM get the container IP:

docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name_or_id.

Then curl < container IP >:8082

If stil not working confirm on build your container EXPOSE 80

Body:
My Dockerfile is:

FROM nginx

I start a container on AWS docker run -d --name ng_ex -p 8082:80 nginx and :

$ sudo docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES
6489cbb430b9        nginx               "nginx -g 'daemon of…"   22 minutes ago      Up 22 minutes       0.0.0.0:8082->80/tcp   ng_ex

And inside a container:

service nginx status
[ ok ] nginx is running.

But when I try to send a request thought browser on my.ip.address:8082 I get a timeout error instead Nginx welcome page. What is my mistake and how to fix it?


问:
robots.txt file being overridden / injected from external source?
We have a couple of Wordpress sites with this same issue.  They appear to have a "robots.txt" file with the following contents:

```<code>User-Agent: *
Crawl-Delay: 300
User-Agent: MJ12bot
Disallow: /
User-agent: MegaIndex.ru
Disallow: /
User-agent: megaindex.com
Disallow: /
</code>```

We have absolutely no idea where this robots.txt file is coming from.

We have looked and there is definitely no "robots.txt" file in the public_html root folder or any sub-folder that we can see.

We have deactivated every single plugin on the site and even changed themes, but the robots.txt file remains exactly the same.  It seems as though it is somehow being injected into the site from an external source somehow!

We have been assured that it couldn't be coming from Google Tag Manager.

Just wondering if anyone happens to recognise the above robots.txt contents and knows how it is existing on our sites???

答:
You have a few possibilities.

Some security plugins (WordFence, iTheme etc) actually add files to your site. These files don't generally go away when you just "disable" the plugins. They need to be actually removed/uninstalled and sometimes you have to manually go through and do it.

WordPress will generate a virtual robots.txt.

If Google has cached that. You can go in and tell Google to look at the robots.txt again.

You should also be able to overwrite it by creating your own by just making a robots.txt file and putting it in the root or using another plugin to do it.

Body:
We have a couple of Wordpress sites with this same issue.  They appear to have a "robots.txt" file with the following contents:

User-Agent: *
Crawl-Delay: 300
User-Agent: MJ12bot
Disallow: /
User-agent: MegaIndex.ru
Disallow: /
User-agent: megaindex.com
Disallow: /

We have absolutely no idea where this robots.txt file is coming from.

We have looked and there is definitely no "robots.txt" file in the public_html root folder or any sub-folder that we can see.

We have deactivated every single plugin on the site and even changed themes, but the robots.txt file remains exactly the same.  It seems as though it is somehow being injected into the site from an external source somehow!

We have been assured that it couldn't be coming from Google Tag Manager.

Just wondering if anyone happens to recognise the above robots.txt contents and knows how it is existing on our sites???