问:
Count and summation of positive and negative number sequences
I want to write a code to count and sum any positive and negative series of numbers.

Numbers are either positive or negative(no zero).

I have written codes with for loops. Is there any creative alternative?

Data

R

set.seed(100)
x <- round(rnorm(20, sd = 0.02), 3)
```
<h3>python</h3>
<pre class="lang-py prettyprint-override"><code>x = [-0.01, 0.003, -0.002, 0.018, 0.002, 0.006, -0.012, 0.014, -0.017, -0.007,

     0.002, 0.002, -0.004, 0.015, 0.002, -0.001, -0.008, 0.01, -0.018, 0.046]
</code>```

loops

R

sign_indicator <- ifelse(x > 0, 1,-1)
number_of_sequence <- rep(NA, 20)
n <- 1
for (i in 2:20) {
  if (sign_indicator[i] == sign_indicator[i - 1]) {
    n <- n + 1
  } else{
    n <- 1
  }
  number_of_sequence[i] <- n

}
number_of_sequence[1] <- 1

#############################

summation <- rep(NA, 20)

for (i in 1:20) {
  summation[i] <- sum(x[i:(i + 1 - number_of_sequence[i])])
}
```
<h3>python</h3>
<pre class="lang-py prettyprint-override"><code>sign_indicator = [1 if i > 0 else -1 for i in X]

number_of_sequence = [1]
N = 1
for i in range(1, len(sign_indicator)):
    if sign_indicator[i] == sign_indicator[i - 1]:
        N += 1
    else:
        N = 1
    number_of_sequence.append(N)

#############################
summation = []

for i in range(len(X)):
    if number_of_sequence[i] == 1:
          summation.append(X[i])

    else:
        summation.append(sum(X[(i + 1 - number_of_sequence[i]):(i + 1)]))
</code>```

result

```<code>        x n_of_sequence    sum
1  -0.010             1 -0.010
2   0.003             1  0.003
3  -0.002             1 -0.002
4   0.018             1  0.018
5   0.002             2  0.020
6   0.006             3  0.026
7  -0.012             1 -0.012
8   0.014             1  0.014
9  -0.017             1 -0.017
10 -0.007             2 -0.024
11  0.002             1  0.002
12  0.002             2  0.004
13 -0.004             1 -0.004
14  0.015             1  0.015
15  0.002             2  0.017
16 -0.001             1 -0.001
17 -0.008             2 -0.009
18  0.010             1  0.010
19 -0.018             1 -0.018
20  0.046             1  0.046
</code>```

答:
In Python, apart from defining a class to store the memory variables, you can use a closure to achieve the same.

```<code>def run():
    count = 0
    last_sign = 0

    def sign(i):
        return 1 if i > 0 else -1

    def f(i):
        nonlocal count
        nonlocal last_sign
        if sign(i) == last_sign:
            count = count+1
        else:
            last_sign = sign(i)
            count = 1
        return count

    return f

f = run()
y = [f(i) for i in x]
</code>```

Note this works for Python 3 only (in Python 2 I think you cannot modify the closure variable like this). Similar thing for summation as well.

Body:
I want to write a code to count and sum any positive and negative series of numbers.

Numbers are either positive or negative(no zero).

I have written codes with for loops. Is there any creative alternative?

Data

R

set.seed(100)
x <- round(rnorm(20, sd = 0.02), 3)

python

x = [-0.01, 0.003, -0.002, 0.018, 0.002, 0.006, -0.012, 0.014, -0.017, -0.007,

     0.002, 0.002, -0.004, 0.015, 0.002, -0.001, -0.008, 0.01, -0.018, 0.046]

loops

R

sign_indicator <- ifelse(x > 0, 1,-1)
number_of_sequence <- rep(NA, 20)
n <- 1
for (i in 2:20) {
  if (sign_indicator[i] == sign_indicator[i - 1]) {
    n <- n + 1
  } else{
    n <- 1
  }
  number_of_sequence[i] <- n

}
number_of_sequence[1] <- 1

#############################

summation <- rep(NA, 20)

for (i in 1:20) {
  summation[i] <- sum(x[i:(i + 1 - number_of_sequence[i])])
}

python

sign_indicator = [1 if i > 0 else -1 for i in X]

number_of_sequence = [1]
N = 1
for i in range(1, len(sign_indicator)):
    if sign_indicator[i] == sign_indicator[i - 1]:
        N += 1
    else:
        N = 1
    number_of_sequence.append(N)

#############################
summation = []

for i in range(len(X)):
    if number_of_sequence[i] == 1:
          summation.append(X[i])

    else:
        summation.append(sum(X[(i + 1 - number_of_sequence[i]):(i + 1)]))

result

        x n_of_sequence    sum
1  -0.010             1 -0.010
2   0.003             1  0.003
3  -0.002             1 -0.002
4   0.018             1  0.018
5   0.002             2  0.020
6   0.006             3  0.026
7  -0.012             1 -0.012
8   0.014             1  0.014
9  -0.017             1 -0.017
10 -0.007             2 -0.024
11  0.002             1  0.002
12  0.002             2  0.004
13 -0.004             1 -0.004
14  0.015             1  0.015
15  0.002             2  0.017
16 -0.001             1 -0.001
17 -0.008             2 -0.009
18  0.010             1  0.010
19 -0.018             1 -0.018
20  0.046             1  0.046

Body:
In Python, apart from defining a class to store the memory variables, you can use a closure to achieve the same.

def run():
    count = 0
    last_sign = 0

    def sign(i):
        return 1 if i > 0 else -1

    def f(i):
        nonlocal count
        nonlocal last_sign
        if sign(i) == last_sign:
            count = count+1
        else:
            last_sign = sign(i)
            count = 1
        return count

    return f

f = run()
y = [f(i) for i in x]

Note this works for Python 3 only (in Python 2 I think you cannot modify the closure variable like this). Similar thing for summation as well.


来源: stackexchange

问:
Is the XML datatype transmitted as binary xml representation?
Is XMLDATA transmitted as binary xml dom representation, or as an xml string?, when accessed with command.ExecuteXmlReader()?

A documentation link would be perfect.

What serialization/deserialization steps involved on the sql server and client side?

UPDATE:

The question is not about how to use the classes provided by net framework.

It's about the internal details of data transmission during execution of an Adonet command on an SQL Server connection, resulting in an XMLDATA column in a resultset.

答:
There are three sample applications that demonstrate using the XML datatype in .NET available in the SQL Server Samples download at Codeplex.  I believe you'll find them useful.

Once the samples are installed, have a look at the sample in the following folder: C:\Program Files\Microsoft SQL Server\100\Samples\Engine\XML\XmlManuInstructions

About halfway down the code file there's a demonstration how to retrieve XML as an XMLDocument object.

More info: Sample XML Applications at MSDN

ContentLicense: CC BY-SA 3.0


问:
How do I pass two different pieces of state from my ngrx effect to my service function?
I have an effects function where I'm trying to pass data from my dispatched action as well as a separate selector to a function in a service, but I'm getting lost in the RXJS syntax. I'm pretty sure I'm not mapping the data correctly. Please see the relevant code.

// effects

```<code> updateCohort$ = createEffect(() =>
    this.actions$.pipe(
        ofType(getCohortActions.updateActiveCohort.type),
        withLatestFrom(this.store.pipe(select(activeCohort))),
        map(([action, selector ]) => (
            this.cohortFeaturesServices.updateCohorts(action, selector)
        )),
</code>```

// service

```<code>public updateCohorts(action, selector): Observable<any> {
    const url = `api/services/cohorts/frontend/`;

    return this.http.patch(`${url}/${selector.id}/`, action.changes);
}
</code>```

Visual Studio Code underlines the entire function and I get the following error in my console.

Type 'Observable>' is not assignable to type 'Observable'.
          Property 'type' is missing in type 'Observable' but required in type 'Action'.

How can I fix my effect and successfully pass my action and my selector to my service call?

答:
For anyone else they may come across the same issue I figured it out. I wasn't returning an action.</p>

```<code>updateCohort$ = createEffect(() =>
    this.actions$.pipe(
        ofType(getCohortActions.updateActiveCohort.type),
        withLatestFrom(this.store.pipe(select(activeCohort))),
        exhaustMap(([action, cohort]) => this.cohortFeaturesServices.updateCohorts(action, cohort).pipe(

        )),
        map((response) => ({
            type: getCohortActions.updateActiveCohortSuccess.type, // success action
            success: response
        })),
        catchError((err) => of(getCohortActions.updateActiveCohortError(err))) // error action
    )
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an effects function where I'm trying to pass data from my dispatched action as well as a separate selector to a function in a service, but I'm getting lost in the RXJS syntax. I'm pretty sure I'm not mapping the data correctly. Please see the relevant code.

// effects

 updateCohort$ = createEffect(() =>
    this.actions$.pipe(
        ofType(getCohortActions.updateActiveCohort.type),
        withLatestFrom(this.store.pipe(select(activeCohort))),
        map(([action, selector ]) => (
            this.cohortFeaturesServices.updateCohorts(action, selector)
        )),

// service

public updateCohorts(action, selector): Observable<any> {
    const url = `api/services/cohorts/frontend/`;

    return this.http.patch(`${url}/${selector.id}/`, action.changes);
}

Visual Studio Code underlines the entire function and I get the following error in my console.

Type 'Observable>' is not assignable to type 'Observable'.
          Property 'type' is missing in type 'Observable' but required in type 'Action'.

How can I fix my effect and successfully pass my action and my selector to my service call?

Body:
For anyone else they may come across the same issue I figured it out. I wasn't returning an action.

updateCohort$ = createEffect(() =>
    this.actions$.pipe(
        ofType(getCohortActions.updateActiveCohort.type),
        withLatestFrom(this.store.pipe(select(activeCohort))),
        exhaustMap(([action, cohort]) => this.cohortFeaturesServices.updateCohorts(action, cohort).pipe(

        )),
        map((response) => ({
            type: getCohortActions.updateActiveCohortSuccess.type, // success action
            success: response
        })),
        catchError((err) => of(getCohortActions.updateActiveCohortError(err))) // error action
    )
)


问:
Infinispan initial state transfer timout
I am working on setting up a replicated infinispan (9.4.16.Final, Wildfly 18.1) cache for two nodes (server1 and server2) and I am running into an issue where the initial state transfer times out on startup. This only happens when I am upgrading my application.

```<code>ERROR [2020-02-14 21:54:47,870] [org.infinispan.remoting.transport.jgroups.JGroupsTransport] (thread-13,ejb,server1) ISPN000474: Error processing request 2017@server2
ERROR [2020-02-14 21:54:47,876] [thread-13,ejb,server1] [transport.jgroups.JGroupsTransport] [] - ISPN000474: Error processing request 2020@server2

ERROR [2020-02-14 20:49:54,732] [org.jboss.msc.service.fail] (ServerService Thread Pool -- 90) MSC000001: Failed to start service org.wildfly.clustering.infinispan.cache.mycontainer.mycache: org.jboss.msc.service.StartException in service org.wildfly.clustering.infinispan.cache.mycontainer.mycache: org.infinispan.commons.CacheException: Initial state transfer timed out for cache mycache on server1
    at org.wildfly.clustering.service@18.0.1.Final//org.wildfly.clustering.service.FunctionalService.start(FunctionalService.java:70)
    at org.wildfly.clustering.service@18.0.1.Final//org.wildfly.clustering.service.AsyncServiceConfigurator$AsyncService.lambda$start$0(AsyncServiceConfigurator.java:117)
    at org.jboss.threads@2.3.3.Final//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
    at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
    at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
    at java.base/java.lang.Thread.run(Thread.java:834)
    at org.jboss.threads@2.3.3.Final//org.jboss.threads.JBossThread.run(JBossThread.java:485)
Caused by: org.infinispan.commons.CacheException: Initial state transfer timed out for cache mycache on server1
    at org.infinispan@9.4.16.Final//org.infinispan.statetransfer.StateTransferManagerImpl.waitForInitialStateTransferToComplete(StateTransferManagerImpl.java:238)
    at org.infinispan@9.4.16.Final//org.infinispan.cache.impl.CacheImpl.start(CacheImpl.java:1113)
    at org.infinispan@9.4.16.Final//org.infinispan.cache.impl.AbstractDelegatingCache.start(AbstractDelegatingCache.java:511)
    at org.infinispan@9.4.16.Final//org.infinispan.manager.DefaultCacheManager.wireAndStartCache(DefaultCacheManager.java:657)
    at org.infinispan@9.4.16.Final//org.infinispan.manager.DefaultCacheManager.createCache(DefaultCacheManager.java:601)
    at org.infinispan@9.4.16.Final//org.infinispan.manager.DefaultCacheManager.internalGetCache(DefaultCacheManager.java:484)
    at org.infinispan@9.4.16.Final//org.infinispan.manager.DefaultCacheManager.getCache(DefaultCacheManager.java:468)
    at org.infinispan@9.4.16.Final//org.infinispan.manager.DefaultCacheManager.getCache(DefaultCacheManager.java:454)
    at org.jboss.as.clustering.infinispan@18.0.1.Final//org.jboss.as.clustering.infinispan.DefaultCacheContainer.getCache(DefaultCacheContainer.java:83)
    at org.wildfly.clustering.infinispan.spi@18.0.1.Final//org.wildfly.clustering.infinispan.spi.service.CacheServiceConfigurator.get(CacheServiceConfigurator.java:77)
    at org.wildfly.clustering.infinispan.spi@18.0.1.Final//org.wildfly.clustering.infinispan.spi.service.CacheServiceConfigurator.get(CacheServiceConfigurator.java:55)
    at org.wildfly.clustering.service@18.0.1.Final//org.wildfly.clustering.service.FunctionalService.start(FunctionalService.java:67)
    ... 7 more

ERROR [2020-02-14 21:54:47,864] [Controller Boot Thread] [as.controller.management-operation] [] - WFLYCTL0013: Operation ("add") failed - address: ([
    ("subsystem" => "infinispan"),
    ("cache-container" => "mycontainer"),
    ("replicated-cache" => "mycache"),
    ("component" => "backups")
]) - failure description: {"WFLYCTL0080: Failed services" => {"org.wildfly.clustering.infinispan.cache.mycontainer.mycache" => "org.infinispan.commons.CacheException: Initial state transfer timed out for cache mycache on server1
    Caused by: org.infinispan.commons.CacheException: Initial state transfer timed out for cache mycache on server1"}}
</code>```

My configuration:

```<code><cache-container name="mycontainer">
    <transport/>
    <replicated-cache name="mycache">
        <locking acquire-timeout="30000" isolation="REPEATABLE_READ"/>
        <expiration interval="60000" lifespan="1200000" max-idle="-1"/>
        <file-store/>
    </replicated-cache>
</cache-container>
</code>```

Can someone help? I've spent several hours trying to fix this but haven't had any luck. Thanks!

答:
You have two options:

1- Increase the timeout

OR

2- Set await-initial-transfer="false"

```<code>    <replicated-cache name="mycache">
        <locking acquire-timeout="30000" isolation="REPEATABLE_READ"/>
        <expiration interval="60000" lifespan="1200000" max-idle="-1"/>
        <file-store/>
<state-transfer enabled="true" timeout="60000" await-initial-transfer="false"/>
    </replicated-cache>
    ```
```

Body:
I am working on setting up a replicated infinispan (9.4.16.Final, Wildfly 18.1) cache for two nodes (server1 and server2) and I am running into an issue where the initial state transfer times out on startup. This only happens when I am upgrading my application.

ERROR [2020-02-14 21:54:47,870] [org.infinispan.remoting.transport.jgroups.JGroupsTransport] (thread-13,ejb,server1) ISPN000474: Error processing request 2017@server2
ERROR [2020-02-14 21:54:47,876] [thread-13,ejb,server1] [transport.jgroups.JGroupsTransport] [] - ISPN000474: Error processing request 2020@server2

ERROR [2020-02-14 20:49:54,732] [org.jboss.msc.service.fail] (ServerService Thread Pool -- 90) MSC000001: Failed to start service org.wildfly.clustering.infinispan.cache.mycontainer.mycache: org.jboss.msc.service.StartException in service org.wildfly.clustering.infinispan.cache.mycontainer.mycache: org.infinispan.commons.CacheException: Initial state transfer timed out for cache mycache on server1
    at org.wildfly.clustering.service@18.0.1.Final//org.wildfly.clustering.service.FunctionalService.start(FunctionalService.java:70)
    at org.wildfly.clustering.service@18.0.1.Final//org.wildfly.clustering.service.AsyncServiceConfigurator$AsyncService.lambda$start$0(AsyncServiceConfigurator.java:117)
    at org.jboss.threads@2.3.3.Final//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
    at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
    at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
    at java.base/java.lang.Thread.run(Thread.java:834)
    at org.jboss.threads@2.3.3.Final//org.jboss.threads.JBossThread.run(JBossThread.java:485)
Caused by: org.infinispan.commons.CacheException: Initial state transfer timed out for cache mycache on server1
    at org.infinispan@9.4.16.Final//org.infinispan.statetransfer.StateTransferManagerImpl.waitForInitialStateTransferToComplete(StateTransferManagerImpl.java:238)
    at org.infinispan@9.4.16.Final//org.infinispan.cache.impl.CacheImpl.start(CacheImpl.java:1113)
    at org.infinispan@9.4.16.Final//org.infinispan.cache.impl.AbstractDelegatingCache.start(AbstractDelegatingCache.java:511)
    at org.infinispan@9.4.16.Final//org.infinispan.manager.DefaultCacheManager.wireAndStartCache(DefaultCacheManager.java:657)
    at org.infinispan@9.4.16.Final//org.infinispan.manager.DefaultCacheManager.createCache(DefaultCacheManager.java:601)
    at org.infinispan@9.4.16.Final//org.infinispan.manager.DefaultCacheManager.internalGetCache(DefaultCacheManager.java:484)
    at org.infinispan@9.4.16.Final//org.infinispan.manager.DefaultCacheManager.getCache(DefaultCacheManager.java:468)
    at org.infinispan@9.4.16.Final//org.infinispan.manager.DefaultCacheManager.getCache(DefaultCacheManager.java:454)
    at org.jboss.as.clustering.infinispan@18.0.1.Final//org.jboss.as.clustering.infinispan.DefaultCacheContainer.getCache(DefaultCacheContainer.java:83)
    at org.wildfly.clustering.infinispan.spi@18.0.1.Final//org.wildfly.clustering.infinispan.spi.service.CacheServiceConfigurator.get(CacheServiceConfigurator.java:77)
    at org.wildfly.clustering.infinispan.spi@18.0.1.Final//org.wildfly.clustering.infinispan.spi.service.CacheServiceConfigurator.get(CacheServiceConfigurator.java:55)
    at org.wildfly.clustering.service@18.0.1.Final//org.wildfly.clustering.service.FunctionalService.start(FunctionalService.java:67)
    ... 7 more

ERROR [2020-02-14 21:54:47,864] [Controller Boot Thread] [as.controller.management-operation] [] - WFLYCTL0013: Operation ("add") failed - address: ([
    ("subsystem" => "infinispan"),
    ("cache-container" => "mycontainer"),
    ("replicated-cache" => "mycache"),
    ("component" => "backups")
]) - failure description: {"WFLYCTL0080: Failed services" => {"org.wildfly.clustering.infinispan.cache.mycontainer.mycache" => "org.infinispan.commons.CacheException: Initial state transfer timed out for cache mycache on server1
    Caused by: org.infinispan.commons.CacheException: Initial state transfer timed out for cache mycache on server1"}}

My configuration:

<cache-container name="mycontainer">
    <transport/>
    <replicated-cache name="mycache">
        <locking acquire-timeout="30000" isolation="REPEATABLE_READ"/>
        <expiration interval="60000" lifespan="1200000" max-idle="-1"/>
        <file-store/>
    </replicated-cache>
</cache-container>

Can someone help? I've spent several hours trying to fix this but haven't had any luck. Thanks!

Body:
You have two options:

1- Increase the timeout

OR

2- Set await-initial-transfer="false"

    <replicated-cache name="mycache">
        <locking acquire-timeout="30000" isolation="REPEATABLE_READ"/>
        <expiration interval="60000" lifespan="1200000" max-idle="-1"/>
        <file-store/>
<state-transfer enabled="true" timeout="60000" await-initial-transfer="false"/>
    </replicated-cache>
    ```


问:
git log show everything _except_ tags
The situation:
I use tags in git to flag version releases. I also have a quick command to show me a simple graph in git with all my active dev branches:

```<code>git log --oneline --graph --simplify-by-decoration --all
</code>```

The issue is that this shows all of the tags, eating up a lot of real estate on the screen. Is there a way I can filter out the tags? I still want all of the other information (i.e. just the active development branches).

I've tried using --exclude="refs/tags/* to no avail - any other suggestions?

I've included an image of what my git log looks like with all the tags cluttering it.

答:
The command I'm looking for is:

```<code>    git log --oneline --graph --decorate --simplify-by-decoration --branches --remotes --decorate-refs=refs/heads --decorate-refs=refs/remotes
</code>```

Thanks to @jthill and @torek for helping with this issue.

EDIT:

After further experimenting, I found the following command:

```<code>log --oneline --graph --decorate --simplify-by-decoration --all --decorate-refs-exclude=refs/tags
</code>```

The above command will include all local and remote branches, including the HEAD indicator, and will exclude tags

Title: git log show everything _except_ tags

Body:
The situation:
I use tags in git to flag version releases. I also have a quick command to show me a simple graph in git with all my active dev branches:

git log --oneline --graph --simplify-by-decoration --all

The issue is that this shows all of the tags, eating up a lot of real estate on the screen. Is there a way I can filter out the tags? I still want all of the other information (i.e. just the active development branches).

I've tried using --exclude="refs/tags/* to no avail - any other suggestions?

I've included an image of what my git log looks like with all the tags cluttering it.

Body:
The command I'm looking for is:

    git log --oneline --graph --decorate --simplify-by-decoration --branches --remotes --decorate-refs=refs/heads --decorate-refs=refs/remotes

Thanks to @jthill and @torek for helping with this issue.

EDIT:

After further experimenting, I found the following command:

log --oneline --graph --decorate --simplify-by-decoration --all --decorate-refs-exclude=refs/tags

The above command will include all local and remote branches, including the HEAD indicator, and will exclude tags


问:
JScript, string length
What I can use in "Microsoft JScript" instead length() with string. String class does not have Method length() or I did't find. What a best way to get string length?

答: There should be a length property you can use.  Note that it's not a method, but a property, so you call it via myStr.length, not myStr.length() (no parentheses).

Title: JScript, string length


问:
Avoiding [weak self] for simple operations?
For short-running operations, is it acceptable to avoid [weak self]? For example, URLSession will retain the closure from dataTask(with:completion:):

```<code>final class ViewController: UIViewController {
  let label = UILabel()

  override func viewDidLoad() {
    super.viewDidLoad()
    URLSession.shared.dataTask(with: url) { data, response, error in
      guard let data = data else { return }
      let decodedString = String(bytes: data, encoding: .utf8)

      DispatchQueue.main.async {
        self.label.text = decodedString
      }
    }.resume()
  }
}
</code>```

In this case, the closure captures self strongly, which means even if this ViewController is held in memory by the closure. URLSession will hold the closure until the data task is complete, which means the life cycle of the ViewController can potentially be extended until dataTask completes.

In this situation, should we use capture lists to avoid this behavior? Is my reasoning correct that there's no reference cycle here?

答:
I think you've already got your answer here. It's not a reference cycle.

But to build a systematic approach, my advice here is one more simpler. Forget thinking about leaks and stuff.

Think about ownership and flow control and then memory-management

Ownership: Does this object need to own this other object? Should an object own its delegate? Should a subview own its parentiew? Does this request own this viewController?

Flow Control: How soon do I want to de-allocate this object? Immediately or upon the view being removed from the screen?

Memory-management: Is this a strong reference cycle?

This thought process not only helps you distinguish a true memory leak from something that isn't a leak. It also helps you design and read your code better and not just slavishly dump [weak self] all over the place.

Body:
For short-running operations, is it acceptable to avoid [weak self]? For example, URLSession will retain the closure from dataTask(with:completion:):

final class ViewController: UIViewController {
  let label = UILabel()

  override func viewDidLoad() {
    super.viewDidLoad()
    URLSession.shared.dataTask(with: url) { data, response, error in
      guard let data = data else { return }
      let decodedString = String(bytes: data, encoding: .utf8)

      DispatchQueue.main.async {
        self.label.text = decodedString
      }
    }.resume()
  }
}

In this case, the closure captures self strongly, which means even if this ViewController is held in memory by the closure. URLSession will hold the closure until the data task is complete, which means the life cycle of the ViewController can potentially be extended until dataTask completes.

In this situation, should we use capture lists to avoid this behavior? Is my reasoning correct that there's no reference cycle here?


问:
Serverless Framework - Setting up resource permissions for dynamodb
I've the following serverless.yml file.
I'm trying to assign read write permissions to the generated dynamodb..

So far it generates my lambda and the dynamodb table but the lambda isn't assigned permissions to access it.

I get no errors and it doesn't seem to add the permission to the dynamodb table.

Can anyone shed any light please?

```<code>service:
  name: catcam

custom:
  stage: ${opt:stage, self:provider.stage}
  tableName: ${self:custom.stage}-notes

environment:
  tableName: ${self:custom.tableName}

plugins:
  - '@hewmen/serverless-plugin-typescript'
  - serverless-plugin-optimize
  - serverless-offline

provider:
  name: aws
  runtime: nodejs12.x
  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:Query
        - dynamodb:Scan
        - dynamodb:GetItem
        - dynamodb:PutItem
        - dynamodb:UpdateItem
        - dynamodb:DeleteItem
      Resource:
        - { "Fn::GetAtt": ["NotesTable", "Arn" ] }
          #        - { !GetAtt NotesTable.Arn }

functions:
  main: # The name of the lambda function
    # The module 'handler' is exported in the file 'src/lambda'
    handler: src/lambda.handler
    events:
      - http:
          method: any
          path: /{any+}

resources:
  Resources:
    NotesTable:
      Type: AWS::DynamoDB::Table
      Properties:
        TableName: ${self:custom.tableName}
        AttributeDefinitions:
          - AttributeName: userId
            AttributeType: S
          - AttributeName: noteId
            AttributeType: S
        KeySchema:
          - AttributeName: userId
            KeyType: HASH
          - AttributeName: noteId
            KeyType: RANGE
        # Set the capacity to auto-scale
        BillingMode: PAY_PER_REQUEST

</code>```

答: Turns out there was nothing wrong with the above, it's correct!!.. it's was me being a banana and not matching the full name of the table with the environment in the application.. i.e. notes table becomes dev-notes for instance.. maybe the above will help someone.

Body:
I've the following serverless.yml file.
I'm trying to assign read write permissions to the generated dynamodb..

So far it generates my lambda and the dynamodb table but the lambda isn't assigned permissions to access it.

I get no errors and it doesn't seem to add the permission to the dynamodb table.

Can anyone shed any light please?

service:
  name: catcam

custom:
  stage: ${opt:stage, self:provider.stage}
  tableName: ${self:custom.stage}-notes

environment:
  tableName: ${self:custom.tableName}

plugins:
  - '@hewmen/serverless-plugin-typescript'
  - serverless-plugin-optimize
  - serverless-offline

provider:
  name: aws
  runtime: nodejs12.x
  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:Query
        - dynamodb:Scan
        - dynamodb:GetItem
        - dynamodb:PutItem
        - dynamodb:UpdateItem
        - dynamodb:DeleteItem
      Resource:
        - { "Fn::GetAtt": ["NotesTable", "Arn" ] }
          #        - { !GetAtt NotesTable.Arn }

functions:
  main: # The name of the lambda function
    # The module 'handler' is exported in the file 'src/lambda'
    handler: src/lambda.handler
    events:
      - http:
          method: any
          path: /{any+}

resources:
  Resources:
    NotesTable:
      Type: AWS::DynamoDB::Table
      Properties:
        TableName: ${self:custom.tableName}
        AttributeDefinitions:
          - AttributeName: userId
            AttributeType: S
          - AttributeName: noteId
            AttributeType: S
        KeySchema:
          - AttributeName: userId
            KeyType: HASH
          - AttributeName: noteId
            KeyType: RANGE
        # Set the capacity to auto-scale
        BillingMode: PAY_PER_REQUEST


问:
Growl/toast style notifications library for iOS
Can anyone recommend a library for implementing growl or toast-style notifications on iOS? For example, after a user saves a profile, I want to have a notification fade in, linger for 3 seconds, report "profile saved", and fade out. Right now I have a UIAlertView that interrupts the user's workflow with a single "OK" button, and I feel like that is overkill.

The Android Toast class is an example of what I am looking for on iOS.

Thanks!

答:
Hey you are looking for this.

https://github.com/PaulSolt/WEPopover#readme


问:
Fill between 4 points: Matplotlib won't let me add more points
I'm trying to make a bounding box. I have all the coordinates. Now, I need to fill between this space. No matter, what combination I try, it won't let me set a limit on y.

What I have:

```<code>import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(6, 6))
plt.imshow(np.random.randint(0, 255, (1200, 1200, 3)))

plt.fill_between([1080, 1120], [800, 800], color='blue', alpha=.5)

plt.show()
</code>```

What I need:

The y axis needs to stop around 200.

答:
The following code should allow you to do what you want to achieve.</p>

```<code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches

fig, ax = plt.subplots(figsize=(6, 6))
plt.imshow(np.random.randint(0, 255, (1200, 1200, 3)))

left_upper_corner = (200, 300)
width = 400
height = 150

rectangle = matplotlib.patches.Rectanglr(left_upper_corner, width, height, fill=“blue“, alpha=.5)
plt.show()
</code>```

Body:
I'm trying to make a bounding box. I have all the coordinates. Now, I need to fill between this space. No matter, what combination I try, it won't let me set a limit on y.

What I have:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(6, 6))
plt.imshow(np.random.randint(0, 255, (1200, 1200, 3)))

plt.fill_between([1080, 1120], [800, 800], color='blue', alpha=.5)

plt.show()

What I need:

The y axis needs to stop around 200.

Body:
The following code should allow you to do what you want to achieve.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches

fig, ax = plt.subplots(figsize=(6, 6))
plt.imshow(np.random.randint(0, 255, (1200, 1200, 3)))

left_upper_corner = (200, 300)
width = 400
height = 150

rectangle = matplotlib.patches.Rectanglr(left_upper_corner, width, height, fill=“blue“, alpha=.5)
plt.show()


问:
Annotating interrupt handlers and registers in Coverity-scan
I am in the process of setting up Coverity-Scan in an embedded systems project (C99 language). The codebase makes use of interrupts and system peripheral registers (like most embedded software). I don't know if it is ignoring code paths which are the results of interrupt handlers or volatile device registers changing.

Do I need to annotate interrupt handlers to mark that they be called at any time? If so, how?

Device registers are accessed through volatile pointers. Is there some annotation that I need to add to suggest to the analyzer what range of values a register can contain, or that they are actually volatile?

答:
Generally, you shouldn't need to do anything special such as annotation to analyze interrupt handlers.  Coverity scans every function in the code, even if it does not see an explicit call to it.  Coverity also understands 'volatile'.

It is possible to inform the analysis about constraints on variable values.  Look in the analysis manual for "modeling".  However, you probably don't need to do that unless you are seeing false positives due to infeasible values.

More generally, if you are concerned about Coverity missing results, I suggest deliberately inserting a few bugs similar to examples in the manual and see if the analysis catches them.  If not, you could try asking about specific examples here or contacting their support team.

(Disclosure: I used to work for Coverity/Synopsys.)


问:
Choosing Specific instances for scaling in and scaling out in AWS
Using Auto Scaling with Load balance in AWS, We can do the following things, according to my understanding:

we can scale up and scale down according to load.

all instances have the same image.

But I have a different problem:

if we have less load then we should terminate a big machine and start a small machine and vice versa.

small machine and the big machine has a different image

but I am not getting any help from AWS UI.

Can anyone help me on this issue?

答:
Basically John answered this question.

As alternative we can have some sophisticated scaling logic in any computing resource. For example AWS Alarms can send SNS notification, that Lambda reads and scale in or out using sophisticated logic you have (big or small instances etc.).


问:
Clip a child SPAN when it exceeds the height of the parent TD/TABLE
I am trying to have my outer table/td clip the inside SPAN when the span content exceeds the height of the outer table while preserving table alignment both vertically and center.

So instead of this:

I would get this:

https://jsfiddle.net/xstatic/nksf9r71/14/

table {
  background: red;
  width: 300px;
  height: 100px;
  table-layout: fixed;
  word-wrap: break-word;
  border-collapse: collapse;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
}

table td {
  text-align: center;
  vertical-align: middle;
  height: inherit;
  overflow: hidden;
  border-collapse: collapse;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  max-height: 0px;
}

table td span {
  padding: 10px;
  overflow: hidden;
  height: inherit;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table width="100%">
  <tr>
    <td><span>KITTENS DON'T ALWAYS GO TO HEAVEN</span></td>
  </tr>
</table></code>```

答:
Not sure what other requirements you have, but this will give you the output you're after:

table td div {
  height: 2rem; /* Or whatever height you're after*/
}
table td div div {
  margin: -0.5rem;
  overflow:hidden;
}```
</div>
</div>
</p>

<p>You'll have to add a wrapper div:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><tr><td><div><div>KITTENS DON'T ALWAYS GO TO HEAVEN</div></div></td></tr></code>```

However, this is a strange way to display a table cell. It may cause issues, down the road.

Body:
I am trying to have my outer table/td clip the inside SPAN when the span content exceeds the height of the outer table while preserving table alignment both vertically and center.

So instead of this:

I would get this:

https://jsfiddle.net/xstatic/nksf9r71/14/

table {
  background: red;
  width: 300px;
  height: 100px;
  table-layout: fixed;
  word-wrap: break-word;
  border-collapse: collapse;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
}

table td {
  text-align: center;
  vertical-align: middle;
  height: inherit;
  overflow: hidden;
  border-collapse: collapse;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  max-height: 0px;
}

table td span {
  padding: 10px;
  overflow: hidden;
  height: inherit;
}

    KITTENS DON'T ALWAYS GO TO HEAVEN

Body:
Not sure what other requirements you have, but this will give you the output you're after:

table td div {
  height: 2rem; /* Or whatever height you're after*/
}
table td div div {
  margin: -0.5rem;
  overflow:hidden;
}

You'll have to add a wrapper div:

<tr><td><div><div>KITTENS DON'T ALWAYS GO TO HEAVEN</div></div></td></tr>

However, this is a strange way to display a table cell. It may cause issues, down the road.


问:
VBA Deleting Active Sheet
I am trying to create a macro that deletes the active sheet without displaying the prompt. Which is what the code below does...This works great until the last sheet. I get the prompt no matter what. I do not want to delete the last sheet and at the same time, I don't want the error '1004' message to come up. Is there a way to change the code above to not delete my last sheet and not display the error message at the same time?</p>

```<code>Application.DisplayAlerts = False
ActiveSheet.Delete
Application.DisplayAlerts = True
</code>```

答:
This happens because you cannot delete the last worksheet in a workbook. Is the macro you have executed with a button? If you do not like the 1004 message, one possible solution may be to create a custom error message: </p>

```<code>Sub deleteActiveSheet()

Application.DisplayAlerts = False

 On Error GoTo Error
    ActiveSheet.Delete

Application.DisplayAlerts = True

Exit Sub
Error:
 MsgBox "you cannot delete the last worksheet in the workbook!"
End Sub
</code>```

Title: VBA Deleting Active Sheet

Body:
I am trying to create a macro that deletes the active sheet without displaying the prompt. Which is what the code below does...This works great until the last sheet. I get the prompt no matter what. I do not want to delete the last sheet and at the same time, I don't want the error '1004' message to come up. Is there a way to change the code above to not delete my last sheet and not display the error message at the same time?

Application.DisplayAlerts = False
ActiveSheet.Delete
Application.DisplayAlerts = True

Body:
This happens because you cannot delete the last worksheet in a workbook. Is the macro you have executed with a button? If you do not like the 1004 message, one possible solution may be to create a custom error message:

Sub deleteActiveSheet()

Application.DisplayAlerts = False

 On Error GoTo Error
    ActiveSheet.Delete

Application.DisplayAlerts = True

Exit Sub
Error:
 MsgBox "you cannot delete the last worksheet in the workbook!"
End Sub


问:
difference between 0.5 and 1/2 during integration
I'm trying to compute the next integral with x in power of 0.5. It is done by Mathematica:

What is strange about this calculation is that numbers don't represent where they came from (for instance, what is 0.0176839?)

As soon as I write (1/2) instead of "0.5" in the power of x, i get this:

What is the difference between 0.5 and 1/2 that can influence on integration?

Thank you in advance

答: It's one of the vagarities of the symbolic solver. The 0.5 goes down the route of giving you a solution that has a similar form as if you raised it to the power of 0.12 (or any other decimal number). The solution that you get when you specify 1/2 is a special case of the more general one that was given before.</p>


问:
Why does Array.prototype.filter() throw an error in Magnolia JavaScript models?
I'm attempting to filter a FreeMarker list in a Magnolia JavaScript model using Array.prototype.filter().

List

```<code>[#assign list = [1, 2, 3]]
</code>```

Model

var Model = function() {
  this.filterList = function(list) {
    return list.filter(function(item) {
      return item === 2
    });
  }
};

new Model();
```

<p><strong>Usage</strong></p>

```${model.filterList(list)}
```

<p>However, I get the following error.</p>

<pre class="lang-sh prettyprint-override"><code>Caused by: jdk.nashorn.internal.runtime.ECMAException: TypeError: list.filter is not a function
</code>```

Nashorn was implemented using ECMAScript-262 5.1.

The Nashorn JavaScript engine was first incorporated into JDK 8 via JEP 174 as a replacement for the Rhino scripting engine. When it was released, it was a complete implementation of the ECMAScript-262 5.1 standard. — JEP 335: Deprecate the Nashorn JavaScript Engine

Why despite the fact that Nashorn follows ECMAScript-262 5.1 do I get an error when using Array.prototype.filter()?

答:
The FreeMarker list you are passing to the model is a sequence, not a JavaScript array.

```<code>Sequence (3)
  0 = 1 (BigDecimal)
  1 = 2 (BigDecimal)
  2 = 3 (BigDecimal)
</code>```

To solve the issue, convert the FreeMarker list you are passing to the model to a JavaScript array using Java.from(). For example:

var Model = function() {
  this.filterList = function(list) {
    return Java.from(list).filter(function(item) {
      return item === 2
    });
  }
};

new Model();
```

Body:
I'm attempting to filter a FreeMarker list in a Magnolia JavaScript model using Array.prototype.filter().

List

[#assign list = [1, 2, 3]]

Model

var Model = function() {
  this.filterList = function(list) {
    return list.filter(function(item) {
      return item === 2
    });
  }
};

new Model();

Usage

${model.filterList(list)}

However, I get the following error.

Caused by: jdk.nashorn.internal.runtime.ECMAException: TypeError: list.filter is not a function

Nashorn was implemented using ECMAScript-262 5.1.

The Nashorn JavaScript engine was first incorporated into JDK 8 via JEP 174 as a replacement for the Rhino scripting engine. When it was released, it was a complete implementation of the ECMAScript-262 5.1 standard. — JEP 335: Deprecate the Nashorn JavaScript Engine

Why despite the fact that Nashorn follows ECMAScript-262 5.1 do I get an error when using Array.prototype.filter()?

Body:
The FreeMarker list you are passing to the model is a sequence, not a JavaScript array.

Sequence (3)
  0 = 1 (BigDecimal)
  1 = 2 (BigDecimal)
  2 = 3 (BigDecimal)

To solve the issue, convert the FreeMarker list you are passing to the model to a JavaScript array using Java.from(). For example:

var Model = function() {
  this.filterList = function(list) {
    return Java.from(list).filter(function(item) {
      return item === 2
    });
  }
};

new Model();


问:
Rules for binding query parameters in Razor Pages
In Razor Pages, it is quite convenient that if you were to call, for example,

```<code>http://localhost/foo?bar=42
</code>```

In the corresponding model, the bar key is automatically accessible in the OnGet constructor

```<code>public IActionResult OnGet(int bar)
{
    System.Console.WriteLine($"bar is {bar}");
}
</code>```

But what if the query parameter is poo?

```<code>http://localhost/foo?poo=42
</code>```

then in the model, bar does not get the value 42.

So simple enough, get the variables to match the query parameter key. But what if the key is hyphenated?

```<code>http://localhost/foo?foo-bar=42
</code>```

foo-bar is definitely not an acceptable variable name. How do I access this query parameter? What are the rules here?

In my specific case, I don't really have a choice but to receive these hyphenated query string parameters. Also, I'm on .net core 2.2.

答:
I think heiphens are represented by underscores, so foo-bar becomes foo_bar, however that goes against the standard C# naming convention.

I wouldn't recommend binding query parameters as handler parameters anyway. The cleanest solution is to define a property on your PageModel like so:

// from the Microsoft.AspNetCore.Mvc namespace
[FromQuery(Name = "foo-bar")]
public string FooBar { get; set; }
```

<p>This way, any time a query parameter matching that name is provided, it will <em>always</em> be bound. Regardless of whether or not the specific handler requested it. Then you can just access the property on your <code>PageModel</code> whenever you need it. So you example method becomes:</p>

<pre class="lang-cs prettyprint-override"><code>public void OnGet()
{
    System.Console.WriteLine($"bar is {FooBar}");
}
</code>```

Body:
In Razor Pages, it is quite convenient that if you were to call, for example,

http://localhost/foo?bar=42

In the corresponding model, the bar key is automatically accessible in the OnGet constructor

public IActionResult OnGet(int bar)
{
    System.Console.WriteLine($"bar is {bar}");
}

But what if the query parameter is poo?

http://localhost/foo?poo=42

then in the model, bar does not get the value 42.

So simple enough, get the variables to match the query parameter key. But what if the key is hyphenated?

http://localhost/foo?foo-bar=42

foo-bar is definitely not an acceptable variable name. How do I access this query parameter? What are the rules here?

In my specific case, I don't really have a choice but to receive these hyphenated query string parameters. Also, I'm on .net core 2.2.

Body:
I think heiphens are represented by underscores, so foo-bar becomes foo_bar, however that goes against the standard C# naming convention.

I wouldn't recommend binding query parameters as handler parameters anyway. The cleanest solution is to define a property on your PageModel like so:

// from the Microsoft.AspNetCore.Mvc namespace
[FromQuery(Name = "foo-bar")]
public string FooBar { get; set; }

This way, any time a query parameter matching that name is provided, it will always be bound. Regardless of whether or not the specific handler requested it. Then you can just access the property on your PageModel whenever you need it. So you example method becomes:

public void OnGet()
{
    System.Console.WriteLine($"bar is {FooBar}");
}


问:
K Means plot not showing properly
I am attempting to visualize the results of a K-Means clustering implementation on the Divorce dataset from UCI Machine Learning Repository.

My code is below:

```<code>import pandas as pd, seaborn as sns1
import matplotlib.pyplot as plt
from scipy import cluster
from sklearn.cluster import KMeans
from sklearn.model_selection import train_test_split

df = pd.read_csv('C:\\Users\\wundermahn\\Desktop\\code\\divorce.csv')
y = df['Class']
X = df.drop('Class', axis=1)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)

y_pred = KMeans(n_clusters=2, random_state=170).fit_predict(X_test)
plt.subplot(221)
plt.scatter(X_test[:, 0], X_test[:, 1], c=y_pred)
plt.title("Guess")

plt.show()
</code>```

This was heavily influenced by the hyperlink K-Means link above.

I am getting as an error:

```<code>Traceback (most recent call last):
  File "c:\Users\wundermahn\Desktop\code\kmeans.py", line 25, in <module>
    plt.scatter(X_test[:, 0], X_test[:, 1], c=y_pred)
  File "C:\Python367-64\lib\site-packages\pandas\core\frame.py", line 2800, in __getitem__
    indexer = self.columns.get_loc(key)
  File "C:\Python367-64\lib\site-packages\pandas\core\indexes\base.py", line 2646, in get_loc
    return self._engine.get_loc(key)
  File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 116, in pandas._libs.index.IndexEngine.get_loc
TypeError: '(slice(None, None, None), 0)' is an invalid key
</code>```

What am I doing incorrectly? Why is my slice None type when I am clearly passing data to it?

答:
plt.scatter expects x and y to be array_like. Apparently a dataframe is not array-like for this function.

If you convert either X or the input to plt_scatter to a Numpy array it should work.

```<code>import pandas as pd, seaborn as sns1
import matplotlib.pyplot as plt
from scipy import cluster
from sklearn.cluster import KMeans
from sklearn.model_selection import train_test_split
import numpy as np
df = pd.read_csv('divorce.csv', sep=';')
y = df['Class']
X = np.array(df.drop('Class', axis=1))

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)

y_pred = KMeans(n_clusters=2, random_state=170).fit_predict(X_test)
plt.subplot(221)
plt.scatter(X_test[:, 0], X_test[:, 1], c=y_pred)
plt.title("Guess")
plt.show()
</code>```

Title: K Means plot not showing properly

Body:
I am attempting to visualize the results of a K-Means clustering implementation on the Divorce dataset from UCI Machine Learning Repository.

My code is below:

import pandas as pd, seaborn as sns1
import matplotlib.pyplot as plt
from scipy import cluster
from sklearn.cluster import KMeans
from sklearn.model_selection import train_test_split

df = pd.read_csv('C:\\Users\\wundermahn\\Desktop\\code\\divorce.csv')
y = df['Class']
X = df.drop('Class', axis=1)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)

y_pred = KMeans(n_clusters=2, random_state=170).fit_predict(X_test)
plt.subplot(221)
plt.scatter(X_test[:, 0], X_test[:, 1], c=y_pred)
plt.title("Guess")

plt.show()

This was heavily influenced by the hyperlink K-Means link above.

I am getting as an error:

Traceback (most recent call last):
  File "c:\Users\wundermahn\Desktop\code\kmeans.py", line 25, in <module>
    plt.scatter(X_test[:, 0], X_test[:, 1], c=y_pred)
  File "C:\Python367-64\lib\site-packages\pandas\core\frame.py", line 2800, in __getitem__
    indexer = self.columns.get_loc(key)
  File "C:\Python367-64\lib\site-packages\pandas\core\indexes\base.py", line 2646, in get_loc
    return self._engine.get_loc(key)
  File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 116, in pandas._libs.index.IndexEngine.get_loc
TypeError: '(slice(None, None, None), 0)' is an invalid key

What am I doing incorrectly? Why is my slice None type when I am clearly passing data to it?

Body:
plt.scatter expects x and y to be array_like. Apparently a dataframe is not array-like for this function.

If you convert either X or the input to plt_scatter to a Numpy array it should work.

import pandas as pd, seaborn as sns1
import matplotlib.pyplot as plt
from scipy import cluster
from sklearn.cluster import KMeans
from sklearn.model_selection import train_test_split
import numpy as np
df = pd.read_csv('divorce.csv', sep=';')
y = df['Class']
X = np.array(df.drop('Class', axis=1))

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)

y_pred = KMeans(n_clusters=2, random_state=170).fit_predict(X_test)
plt.subplot(221)
plt.scatter(X_test[:, 0], X_test[:, 1], c=y_pred)
plt.title("Guess")
plt.show()


问:
Type 'Microsoft.VisualBasic.CompilerServices.DesignerGenerated' is not defined
When ever I start a blank WPF project in Visual Basic 2010 (SP1) I get the following error:

Type
  'Microsoft.VisualBasic.CompilerServices.DesignerGenerated'
  is not defined.

The error comes from the auto-generated code in MainWindow.g.i.vb - when I try to add a reference to Microsoft.VisualBasic, it says I can't because it will be added at runtime.

I search of the MSDN forums found nothing, a workaround on MS Connect was to install SP1 (which I have done).

Anyone else have this prob or know how to fix it?

答:
Try to install the file from Microsoft
VBWP7SetupENU.msi

See the instructions and the required files in:
http://msdn.microsoft.com/en-us/library/ff402530(v=vs.92).aspx#BKMK_Installing

Good luck

ContentLicense: CC BY-SA 2.5


问:
Undefined property: stdClass::$Unblinking Eternity
I'm trying to get a list of my items from the Steam service. I have two functions, 1 of them: receives all items from the Steam store, 2 functions receive the price, name, picture of the item. So, when I try to parse the data, in one of my account I get an error: Undefined property: stdClass::$Unblinking Eternity, and in my second account all parsing good.

var_dump($items); exit; show me:

```<code>object(stdClass)#547 (34183) { ["Orb of Deliverance"]=> object(stdClass)#546 (2)
{ ["price"]=> float(58.31) ["appid"]=> string(3) "570" } ["Planks of the Bogatyr"]=> object(stdClass)#54.......
</code>```

and some logs:

```<code>at HandleExceptions->handleError('8', 'Undefined property: stdClass::$Unblinking Eternity', '/var/app/Http/Controllers/InventoryController.php', '320', array('market_hash_name' => 'Unblinking Eternity', 'json' => '{"Orb of Deliverance":{"price":57.780000000000001,"appid":"570","count":427,"bprice":51.490000000000002,"bcount":11663},"Planks of the Bogatyr":{"price":0.14000000000000001,"appid":"570","count":922,"bprice":0.12,"bcount":859},"Headdress of the Ember Crane":{"price":0.16,"appid":"570","count":808,"bprice":0.14999999999999999,"bcount":218},"Sash of Divine Ascension":
</code>```

Error show at 320 line, 320 line its: if($items->$item_name == 'undefined'){

My 2 functions:

```<code>public static function getItemPrice($market_hash_name) {
    try {
        if(\Cache::has('prices')){
            $json = \Cache::get('prices');
            $items = json_decode($json);
            $item_name = $market_hash_name;
            if($items->$item_name == 'undefined'){
                return false;
            } else{
                return $items->$item_name->price;
            }
        } else {
            return false;
        }
    } catch(Exception $e){
        return false;
    }
}

public function getPriceItems()
{
    $data = file_get_contents("http://steamp.ru/v2/?key=key");
    if(!$data) return 'Error getting data';
    $data = json_decode($data);
    if(!isset($data->success)) return 'Error getting data';
    if($data->success && isset($data->items)){
        \Cache::put('prices', json_encode($data->items), 44640);
        return 'Successfully Parsing';
    } else if(isset($data->message)){
        return $data->message;
    }
    return 'Error getting data';
}
</code>```

How i understand, a problem with stdClass.

Where my mistake? How i can fix this error?

答:
In if ($items->$item_name == 'undefined') { you're referring to a dynamic property name without checking that it exists first.

You can check that using isset().

```<code>if (!isset($items->$item_name) || $items->$item_name == 'undefined') {
</code>```

I don't know if the item really will ever be the string 'undefined', though, so you might be able to do away with that part altogether.

```<code>if (!isset($items->$item_name)) {
</code>```

Body:
I'm trying to get a list of my items from the Steam service. I have two functions, 1 of them: receives all items from the Steam store, 2 functions receive the price, name, picture of the item. So, when I try to parse the data, in one of my account I get an error: Undefined property: stdClass::$Unblinking Eternity, and in my second account all parsing good.

var_dump($items); exit; show me:

object(stdClass)#547 (34183) { ["Orb of Deliverance"]=> object(stdClass)#546 (2)
{ ["price"]=> float(58.31) ["appid"]=> string(3) "570" } ["Planks of the Bogatyr"]=> object(stdClass)#54.......

and some logs:

at HandleExceptions->handleError('8', 'Undefined property: stdClass::$Unblinking Eternity', '/var/app/Http/Controllers/InventoryController.php', '320', array('market_hash_name' => 'Unblinking Eternity', 'json' => '{"Orb of Deliverance":{"price":57.780000000000001,"appid":"570","count":427,"bprice":51.490000000000002,"bcount":11663},"Planks of the Bogatyr":{"price":0.14000000000000001,"appid":"570","count":922,"bprice":0.12,"bcount":859},"Headdress of the Ember Crane":{"price":0.16,"appid":"570","count":808,"bprice":0.14999999999999999,"bcount":218},"Sash of Divine Ascension":

Error show at 320 line, 320 line its: if($items->$item_name == 'undefined'){

My 2 functions:

public static function getItemPrice($market_hash_name) {
    try {
        if(\Cache::has('prices')){
            $json = \Cache::get('prices');
            $items = json_decode($json);
            $item_name = $market_hash_name;
            if($items->$item_name == 'undefined'){
                return false;
            } else{
                return $items->$item_name->price;
            }
        } else {
            return false;
        }
    } catch(Exception $e){
        return false;
    }
}

public function getPriceItems()
{
    $data = file_get_contents("http://steamp.ru/v2/?key=key");
    if(!$data) return 'Error getting data';
    $data = json_decode($data);
    if(!isset($data->success)) return 'Error getting data';
    if($data->success && isset($data->items)){
        \Cache::put('prices', json_encode($data->items), 44640);
        return 'Successfully Parsing';
    } else if(isset($data->message)){
        return $data->message;
    }
    return 'Error getting data';
}

How i understand, a problem with stdClass.

Where my mistake? How i can fix this error?

Body:
In if ($items->$item_name == 'undefined') { you're referring to a dynamic property name without checking that it exists first.

You can check that using isset().

if (!isset($items->$item_name) || $items->$item_name == 'undefined') {

I don't know if the item really will ever be the string 'undefined', though, so you might be able to do away with that part altogether.

if (!isset($items->$item_name)) {


问:
Xamarin forms 4.x searchbar crashes when text changes
Summary: The program allows the user to have a list of players. I have it so that the user can add players to the SQLite database and modify or delete them. I am trying to create a Match between players, the idea being that the user will use the SearchBar to find the name and select it from the quick list as they type. I've been searching around for ways to use the SearchBar and how to access specific data from the SQLite database and I think I have it generating a list of Players to choose from. But when I run the program and attempt to search for a name, it crashes on the first letter and Visual Studio reports an error: SQLite.SQLiteException: 'no such column: a' (where 'a' is the first letter that I typed). In the background is the message: Your app has entered a break state, but there is no code to show because all threads were executing external code (typically system or framework code).

Here is how I have it set up. Here is the search bar on MatchEntryPage.xmal

```<code>                    <StackLayout>
                        <SearchBar Grid.Row="1"
                                   Grid.Column="0"
                                   Grid.ColumnSpan="3"
                                   Placeholder="Player 1"
                                   TextChanged="OnPlayer1SearchTextChanged"
                                   x:Name="Player1SearchBar" />
                        <ListView x:Name="Player1SearchList"
                                  Footer="" />
                    </StackLayout>
</code>```

Here is how I handle the text change in MatchEntryPage.xmal.cs

```<code>async void OnPlayer1SearchTextChanged(object sender, EventArgs e)
    {
        Player1SearchList.ItemsSource = await
            App.Database.GetPlayersByNameAsync(Player1SearchBar.Text);
    }
</code>```

In the player class definition PlayerDatabase.cs here is the function:

```<code>    public async Task<List<Player>>GetPlayersByNameAsync(string name)
    {
        List<Player> result = await _database.QueryAsync<Player>("SELECT * from Player where
             PlayerName LIKE " + name);
        return result;
    }
</code>```

Additional notes: Some of the reading I did mentioned that best practice is to not use SQL directly but I am unsure how to do this. Also, here are other functions in PlayerDatabase.cs that I am able to use to populate a ListView to show the full list of players in the database

```<code>    readonly SQLiteAsyncConnection _database;

    public PlayerDatabase(string dbPath)
    {
        _database = new SQLiteAsyncConnection(dbPath);
        _database.CreateTableAsync<Player>().Wait();
    }

    public Task<List<Player>> GetPlayersAsync()
    {
        return _database.Table<Player>().ToListAsync();
    }

    public Task<Player> GetPlayerAsync(int id)
    {
        return _database.Table<Player>()
            .Where(i => i.ID == id)
            .FirstOrDefaultAsync();
    }
</code>```

答:
Change:

```<code> public async Task<List<Player>>GetPlayersByNameAsync(string name)
    {
        List<Player> result = await _database.QueryAsync<Player>("SELECT * from Player where
             PlayerName LIKE " + name);
        return result;
    }
</code>```

to

```<code> public async Task<List<Player>>GetPlayersByNameAsync(string name)
    {
        List<Player> result = await _database.QueryAsync<Player>("SELECT * from Player where
             PlayerName LIKE '%" + name+ "%');
        return result;
    }
</code>```

But you should use SqlParameter instead of variables directly. To get better performance and avoid sql-injection - read here: C# SQLite Parameterized Select Using LIKE

I am not use to SqlLite, but it might be possible to write:

```<code>    public Task<IEnumerable<Player>> GetPlayerWithNamesOfAsync(string wildcardName)
    {
        return _database.Table<Player>()
            .Where(p => p.PlayerName.Contains(wildcardName))
            .ToArrayAsync();
    }
</code>```

Body:
Summary: The program allows the user to have a list of players. I have it so that the user can add players to the SQLite database and modify or delete them. I am trying to create a Match between players, the idea being that the user will use the SearchBar to find the name and select it from the quick list as they type. I've been searching around for ways to use the SearchBar and how to access specific data from the SQLite database and I think I have it generating a list of Players to choose from. But when I run the program and attempt to search for a name, it crashes on the first letter and Visual Studio reports an error: SQLite.SQLiteException: 'no such column: a' (where 'a' is the first letter that I typed). In the background is the message: Your app has entered a break state, but there is no code to show because all threads were executing external code (typically system or framework code).

Here is how I have it set up. Here is the search bar on MatchEntryPage.xmal

                    <StackLayout>
                        <SearchBar Grid.Row="1"
                                   Grid.Column="0"
                                   Grid.ColumnSpan="3"
                                   Placeholder="Player 1"
                                   TextChanged="OnPlayer1SearchTextChanged"
                                   x:Name="Player1SearchBar" />
                        <ListView x:Name="Player1SearchList"
                                  Footer="" />
                    </StackLayout>

Here is how I handle the text change in MatchEntryPage.xmal.cs

async void OnPlayer1SearchTextChanged(object sender, EventArgs e)
    {
        Player1SearchList.ItemsSource = await
            App.Database.GetPlayersByNameAsync(Player1SearchBar.Text);
    }

In the player class definition PlayerDatabase.cs here is the function:

    public async Task<List<Player>>GetPlayersByNameAsync(string name)
    {
        List<Player> result = await _database.QueryAsync<Player>("SELECT * from Player where
             PlayerName LIKE " + name);
        return result;
    }

Additional notes: Some of the reading I did mentioned that best practice is to not use SQL directly but I am unsure how to do this. Also, here are other functions in PlayerDatabase.cs that I am able to use to populate a ListView to show the full list of players in the database

    readonly SQLiteAsyncConnection _database;

    public PlayerDatabase(string dbPath)
    {
        _database = new SQLiteAsyncConnection(dbPath);
        _database.CreateTableAsync<Player>().Wait();
    }

    public Task<List<Player>> GetPlayersAsync()
    {
        return _database.Table<Player>().ToListAsync();
    }

    public Task<Player> GetPlayerAsync(int id)
    {
        return _database.Table<Player>()
            .Where(i => i.ID == id)
            .FirstOrDefaultAsync();
    }

Body:
Change:

 public async Task<List<Player>>GetPlayersByNameAsync(string name)
    {
        List<Player> result = await _database.QueryAsync<Player>("SELECT * from Player where
             PlayerName LIKE " + name);
        return result;
    }

to

 public async Task<List<Player>>GetPlayersByNameAsync(string name)
    {
        List<Player> result = await _database.QueryAsync<Player>("SELECT * from Player where
             PlayerName LIKE '%" + name+ "%');
        return result;
    }

But you should use SqlParameter instead of variables directly. To get better performance and avoid sql-injection - read here: C# SQLite Parameterized Select Using LIKE

I am not use to SqlLite, but it might be possible to write:

    public Task<IEnumerable<Player>> GetPlayerWithNamesOfAsync(string wildcardName)
    {
        return _database.Table<Player>()
            .Where(p => p.PlayerName.Contains(wildcardName))
            .ToArrayAsync();
    }


问:
Eclipse : Setting up the Ctrl+Space to display "Java Proposals" panel
When pressing Ctrl+Space on Eclipse, a panel appears, it's usually the "Java Proposals" panel which appears first, and when pressing again Ctrl+Space it appears other panel.

I have downloaded "Eclipse IDE for Java Developers" - Version "2019-12 (4.14.0)" and here, the default Ctrl+Space panel is no more the "Java Proposals". I have to press 3-4 times Ctrl+Space to find the panel I want.
How can I fix this ? How can I display the "Java Proposals" panel when pressing Ctrl+space only one time ?

This configuration disturb me

答: Go to Window -> Preferences -> Java -> Editor -> Content Assist -> Advanced and check your settings. You can change the content assist cycling settings and the default proposal kinds.


问:
Adaptive card is not rendered on Teams mobile app
We have an external bot configured to use MS Teams channel using message end point web hook. The following is the message posted to the  Ms Teams channel by the external bot. This response gets rendered as expected when MS Teams is accessed via web browser or MS Teams application on desktop computer. However,  the card is not rendered (seeing an empty line/block without any content)  when used with  Teams application on an android mobile phone. Would like to know what is going wrong here?Is this feature not supported on mobile? or are we missing something?  </p>

```<code>   "channelData":{
      "tenant":{
         "id":"xxxxxxxxxxxxxx"
      }
   },
   "attachments":[
      {
         "contentType":"application/vnd.microsoft.card.adaptive",
         "content":{
            "fallbackText":"Adaptive card version not supported",
            "type":"AdaptiveCards",
            "body":[
               {
                  "text":"Here is an adaptive card with a link to a task module",
                  "type":"TextBlock"
               },
               {
                  "type":"Image",
                  "url":"http://adaptivecards.io/content/cats/1.png"
               }
            ],
            "version":"1.0",
            "actions":[
               {
                  "type":"Action.OpenUrl",
                  "title":"Open Link",
                  "url":"https://teams.microsoft.com/l/task/xxxxx?url=https%3A%2F%2Fwww.wikipedia.com%0A&height=large&width=large&title=Wikipedia-Embed"
               }
            ]
         }
      }
   ],
   "replyToId":"xxxxxx",
   "serviceUrl":"https://smba.trafficmanager.net/amer/",
   "recipient":{
      "name":"xxxx xxxx",
      "aadObjectId":"xxxxx",
      "id":"xx:xxxxxxxx"
   },
   "localTimestamp":"2020-02-14T15:21:41.1360000-08:00",
   "channelType":"msteams",
   "from":{
      "name":"xxxxxx",
      "id":"xx:xxxxx"
   },
   "type":"message",
   "conversation":{
      "conversationType":"personal",
      "tenantId":"xxxxxx",
      "id":"x:xxxxxx"
   }
}```
</code>```

答:
You need to make sure the card's "type" is "AdaptiveCard" and not "AdaptiveCards".

```<code> {
    "fallbackText":"Adaptive card version not supported",
    "type":"AdaptiveCard",
    "body":[
       {
          "text":"Here is an adaptive card with a link to a task module",
          "type":"TextBlock"
       },
       {
          "type":"Image",
          "url":"http://adaptivecards.io/content/cats/1.png"
       }
    ],
    "version":"1.0",
    "actions":[
       {
          "type":"Action.OpenUrl",
          "title":"Open Link",
          "url":"https://teams.microsoft.com/l/task/xxxxx?url=https%3A%2F%2Fwww.wikipedia.com%0A&height=large&width=large&title=Wikipedia-Embed"
       }
    ]
 }
</code>```

Body:
We have an external bot configured to use MS Teams channel using message end point web hook. The following is the message posted to the  Ms Teams channel by the external bot. This response gets rendered as expected when MS Teams is accessed via web browser or MS Teams application on desktop computer. However,  the card is not rendered (seeing an empty line/block without any content)  when used with  Teams application on an android mobile phone. Would like to know what is going wrong here?Is this feature not supported on mobile? or are we missing something?

   "channelData":{
      "tenant":{
         "id":"xxxxxxxxxxxxxx"
      }
   },
   "attachments":[
      {
         "contentType":"application/vnd.microsoft.card.adaptive",
         "content":{
            "fallbackText":"Adaptive card version not supported",
            "type":"AdaptiveCards",
            "body":[
               {
                  "text":"Here is an adaptive card with a link to a task module",
                  "type":"TextBlock"
               },
               {
                  "type":"Image",
                  "url":"http://adaptivecards.io/content/cats/1.png"
               }
            ],
            "version":"1.0",
            "actions":[
               {
                  "type":"Action.OpenUrl",
                  "title":"Open Link",
                  "url":"https://teams.microsoft.com/l/task/xxxxx?url=https%3A%2F%2Fwww.wikipedia.com%0A&height=large&width=large&title=Wikipedia-Embed"
               }
            ]
         }
      }
   ],
   "replyToId":"xxxxxx",
   "serviceUrl":"https://smba.trafficmanager.net/amer/",
   "recipient":{
      "name":"xxxx xxxx",
      "aadObjectId":"xxxxx",
      "id":"xx:xxxxxxxx"
   },
   "localTimestamp":"2020-02-14T15:21:41.1360000-08:00",
   "channelType":"msteams",
   "from":{
      "name":"xxxxxx",
      "id":"xx:xxxxx"
   },
   "type":"message",
   "conversation":{
      "conversationType":"personal",
      "tenantId":"xxxxxx",
      "id":"x:xxxxxx"
   }
}```

Body:
You need to make sure the card's "type" is "AdaptiveCard" and not "AdaptiveCards".

 {
    "fallbackText":"Adaptive card version not supported",
    "type":"AdaptiveCard",
    "body":[
       {
          "text":"Here is an adaptive card with a link to a task module",
          "type":"TextBlock"
       },
       {
          "type":"Image",
          "url":"http://adaptivecards.io/content/cats/1.png"
       }
    ],
    "version":"1.0",
    "actions":[
       {
          "type":"Action.OpenUrl",
          "title":"Open Link",
          "url":"https://teams.microsoft.com/l/task/xxxxx?url=https%3A%2F%2Fwww.wikipedia.com%0A&height=large&width=large&title=Wikipedia-Embed"
       }
    ]
 }


问:
Using dynamic placeholders in cognito AdminCreateUser email
I create my users through the cognito-idp API calling adminCreateUser, but the problem I am having is that if I create the user that belongs to develop or to production I have set different environments and the link to click on the email would be a different URL.

At the moment I am sending an email that looks like this:

```<code><h3>Hello {username} !</h3>
<p>To finish your subscription please click on <a href="http://localhost:3000/signup?token={####}" >finish my subscription</a></p>
</code>```

But as you can see it would only cover the developer option, I would like instead to send an email with some placeholders that I can use dynamically whether we are creating a developer user or a production user like the use of the tag {url} would be a great help.

This is what I would like to do:

```<code><h3>Hello {name} !</h3>
<p>Your username is {username}</p>
<p>To finish your subscription to {project} please click on <a href="{url}{####}" >finish my subscription</a></p>
</code>```

Does AWS Cognito accepts this? I have read that you can do something similar through lambdas but not so sure if I can create my own variables or if its only the existing variables in cognito.

Somebody with more experience with cognito that can give me a hand on this?

Many thanks!

答:
You can use the AWS-Cognito-Custom-Message-Trigger to accomplish this. It is a bit more complicated because you are handling messages in a lambda function, but it is the only way to get the ability to access attributes and group names and such in your response.

Example code for the trigger lambda:

```<code>exports.handler = (event, context, callback) => {
    //
    if(event.userPoolId === "theSpecialUserPool") {
        // Identify why was this function invoked
        if(event.triggerSource === "CustomMessage_AdminCreateUser") {
            // Ensure that your message contains event.request.codeParameter event.request.usernameParameter. This is the placeholder for the code and username that will be sent to your user.
            event.response.smsMessage = "Welcome to the service. Your user name is " + event.request.usernameParameter + " Your temporary password is " + event.request.codeParameter;
            event.response.emailSubject = "Welcome to the service";
            event.response.emailMessage = "Welcome to the service. Your user name is " + event.request.usernameParameter + " Your temporary password is " + event.request.codeParameter;
        }
        // Create custom message for other events
    }
    // Customize messages for other user pools

    // Return to Amazon Cognito
    callback(null, event);
};
</code>```

Docs here: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-custom-message.html

Body:
I create my users through the cognito-idp API calling adminCreateUser, but the problem I am having is that if I create the user that belongs to develop or to production I have set different environments and the link to click on the email would be a different URL.

At the moment I am sending an email that looks like this:

Hello {username} !

To finish your subscription please click on finish my subscription

But as you can see it would only cover the developer option, I would like instead to send an email with some placeholders that I can use dynamically whether we are creating a developer user or a production user like the use of the tag {url} would be a great help.

This is what I would like to do:

Hello {name} !

Your username is {username}

To finish your subscription to {project} please click on finish my subscription

Does AWS Cognito accepts this? I have read that you can do something similar through lambdas but not so sure if I can create my own variables or if its only the existing variables in cognito.

Somebody with more experience with cognito that can give me a hand on this?

Many thanks!

Body:
You can use the AWS-Cognito-Custom-Message-Trigger to accomplish this. It is a bit more complicated because you are handling messages in a lambda function, but it is the only way to get the ability to access attributes and group names and such in your response.

Example code for the trigger lambda:

exports.handler = (event, context, callback) => {
    //
    if(event.userPoolId === "theSpecialUserPool") {
        // Identify why was this function invoked
        if(event.triggerSource === "CustomMessage_AdminCreateUser") {
            // Ensure that your message contains event.request.codeParameter event.request.usernameParameter. This is the placeholder for the code and username that will be sent to your user.
            event.response.smsMessage = "Welcome to the service. Your user name is " + event.request.usernameParameter + " Your temporary password is " + event.request.codeParameter;
            event.response.emailSubject = "Welcome to the service";
            event.response.emailMessage = "Welcome to the service. Your user name is " + event.request.usernameParameter + " Your temporary password is " + event.request.codeParameter;
        }
        // Create custom message for other events
    }
    // Customize messages for other user pools

    // Return to Amazon Cognito
    callback(null, event);
};

Docs here: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-custom-message.html


问:
Consolidating 300+ files into 5-8, OutOfMemory exception
I have 369 files that need to be formatted and consolidated into 5-8 files before being submitted to the server.  I can't submit the 369 files because that would overwhelm the metadata tables in our database (they can handle it, but it'd be 369 rows for what was essentially one file, which would make querying and utilizing those tables a nightmare) and I can't handle it as one file because the total of 3.6 GB is too much for SSIS to handle on our servers.

I wrote the following script to fix the issue:

```<code>        static void PrepPAIDCLAIMSFiles()
        {
            const string HEADER = "some long header text, trimmed for SO question";
            const string FOOTER = "some long footer text, trimmed for SO question";
            //path is defined as a static member of the containing class
            string[] files = Directory.GetFiles(path + @"split\");
            int splitFileCount = 0, finalFileCount = 0;
            List<string> newFileContents = new List<string>();
            foreach(string file in files)
            {
                try
                {
                    var contents = File.ReadAllLines(file).ToList();
                    var fs = File.OpenRead(file);
                    if (splitFileCount == 0)
                    {
                        //Grab everything except the header
                        contents = contents.GetRange(1, contents.Count - 1);
                    }
                    else if (splitFileCount == files.Length - 1)
                    {
                        //Grab everything except the footer
                        contents = contents.GetRange(0, contents.Count - 1);
                    }
                    if (!Directory.Exists(path + @"split\formatted"))
                    {
                        Directory.CreateDirectory(path + @"split\formatted");
                    }
                    newFileContents.AddRange(contents);
                    if (splitFileCount % 50 == 0 || splitFileCount >= files.Length)
                    {
                        Console.WriteLine($"{splitFileCount} {finalFileCount}");
                        var sb = new StringBuilder(HEADER);
                        foreach (var row in newFileContents)
                        {
                            sb.Append(row);
                        }
                        sb.Append(FOOTER);
                        newFileContents = new List<string>();
                        GC.Collect();
                        string fileName = file.Split('\\').Last();
                        string baseFileName = fileName.Split('.')[0];
                        DateTime currentTime = DateTime.Now;
                        baseFileName += "." + COMPANY_NAME_SetHHMMSS(currentTime, finalFileCount) + ".TXT";
                        File.WriteAllText(path + @"split\formatted\" + baseFileName, sb.ToString());
                        finalFileCount += 1;
                    }
                    splitFileCount += 1;
                }
                catch(OutOfMemoryException OOM)
                {
                    Console.WriteLine(file);
                    Console.WriteLine(OOM.Message);
                    break;
                }
            }
        }
</code>```

The way this works is it reads the split file, puts its rows into a string builder, every time it gets to a multiple of 50 files, it writes the string builder to a new file and starts over.  The COMPANY_NAME_SetHHMMSS() method ensures the file has a unique name, so it's not writing to the same file over and over (and I can verify this by seeing the output, it writes two files before exploding.)

It breaks when it gets to the 81st file.  System.OutOfMemoryException on var contents = File.ReadAllLines(file).ToList();.  There's nothing special about the 81st file, it's the same exact size as all the others (~10MB.)  The files this function delivers are about ~500MB.  It also has no trouble reading and processing all the files upto and not including the 81st, so I don't think that it's running out of memory reading the file, but running out of memory doing something else and it's at the 81st where memory runs out.

The newFileContents() list should be getting emptied by overwriting it with a new list, right?  That shouldn't be growing with every iteration in this function.  GC.Collect() was sort of a last ditch effort.

The original file that the 369 splits come from has been a headache for a few days now, causing UltraEdit to crash, SSIS to crash, C# to crash, etc.  Splitting it via 7zip seemed to be the only option that worked, and splitting it to 369 files seemed to be the only option 7zip had that didn't also reformat or somehow compress the file in an undesirable way.

Is there something that I'm missing?  Something in my code that keeps growing in memory?  I know File.ReadAllLines() opens and closes the file, so it should be disposed after called, right?  newFileContents() gets overwritten every 50th file, as does the string builder.  What else could I be doing?

答:
You should just be looping over the rows in your source files and appending them to a new file. You're holding the contents of up to 50 10MB files in memory at once, plus anything else you're doing. This may be because you're compiling for x86 instead of x64, but there isn't any reason this should use anywhere near that memory. Something like the following:</p>

```<code>        var files = Directory.Getfiles(System.IO.Path.Combing(path, "split")).ToList();
        //since you were skipping the first and last file
        files.Remove(files.FirstOrDefault());
        files.Remove(files.LastOrDefault());

        string combined_file_path = "<whatever you want to call this>";
        System.IO.StreamWriter combined_file_writer = null;
        try
        {
            foreach(var file in files)
            {
                //if multiple of 50, write footer, dispose of stream, and make a new stream
                if((files.IndexOf(file)) % 50 == 0)
                {
                    combined_file_writer?.WriteLine(FOOTER);
                    combined_file_writer?.Dispose();
                    combined_file_writer = new System.IO.StreamWriter(combined_file_path + "_1"); //increment the name somewhow
                    combined_file_writer.WriteLine(Header);
                }

                using(var file_reader = new System.IO.StreamReader(file))
                {
                    while(!file_reader.EOF)
                    {
                        combined_file_writer.WriteLine(file_reader.ReadLine());
                    }
                }

            }

            //finish out the last file
            combined_file_writer?.WriteLine(FOOTER);
        }
        finally
        {
            //dispose of last file
            combined_file_writer?.Dispose();
        }
</code>```

Body:
I have 369 files that need to be formatted and consolidated into 5-8 files before being submitted to the server.  I can't submit the 369 files because that would overwhelm the metadata tables in our database (they can handle it, but it'd be 369 rows for what was essentially one file, which would make querying and utilizing those tables a nightmare) and I can't handle it as one file because the total of 3.6 GB is too much for SSIS to handle on our servers.

I wrote the following script to fix the issue:

        static void PrepPAIDCLAIMSFiles()
        {
            const string HEADER = "some long header text, trimmed for SO question";
            const string FOOTER = "some long footer text, trimmed for SO question";
            //path is defined as a static member of the containing class
            string[] files = Directory.GetFiles(path + @"split\");
            int splitFileCount = 0, finalFileCount = 0;
            List<string> newFileContents = new List<string>();
            foreach(string file in files)
            {
                try
                {
                    var contents = File.ReadAllLines(file).ToList();
                    var fs = File.OpenRead(file);
                    if (splitFileCount == 0)
                    {
                        //Grab everything except the header
                        contents = contents.GetRange(1, contents.Count - 1);
                    }
                    else if (splitFileCount == files.Length - 1)
                    {
                        //Grab everything except the footer
                        contents = contents.GetRange(0, contents.Count - 1);
                    }
                    if (!Directory.Exists(path + @"split\formatted"))
                    {
                        Directory.CreateDirectory(path + @"split\formatted");
                    }
                    newFileContents.AddRange(contents);
                    if (splitFileCount % 50 == 0 || splitFileCount >= files.Length)
                    {
                        Console.WriteLine($"{splitFileCount} {finalFileCount}");
                        var sb = new StringBuilder(HEADER);
                        foreach (var row in newFileContents)
                        {
                            sb.Append(row);
                        }
                        sb.Append(FOOTER);
                        newFileContents = new List<string>();
                        GC.Collect();
                        string fileName = file.Split('\\').Last();
                        string baseFileName = fileName.Split('.')[0];
                        DateTime currentTime = DateTime.Now;
                        baseFileName += "." + COMPANY_NAME_SetHHMMSS(currentTime, finalFileCount) + ".TXT";
                        File.WriteAllText(path + @"split\formatted\" + baseFileName, sb.ToString());
                        finalFileCount += 1;
                    }
                    splitFileCount += 1;
                }
                catch(OutOfMemoryException OOM)
                {
                    Console.WriteLine(file);
                    Console.WriteLine(OOM.Message);
                    break;
                }
            }
        }

The way this works is it reads the split file, puts its rows into a string builder, every time it gets to a multiple of 50 files, it writes the string builder to a new file and starts over.  The COMPANY_NAME_SetHHMMSS() method ensures the file has a unique name, so it's not writing to the same file over and over (and I can verify this by seeing the output, it writes two files before exploding.)

It breaks when it gets to the 81st file.  System.OutOfMemoryException on var contents = File.ReadAllLines(file).ToList();.  There's nothing special about the 81st file, it's the same exact size as all the others (~10MB.)  The files this function delivers are about ~500MB.  It also has no trouble reading and processing all the files upto and not including the 81st, so I don't think that it's running out of memory reading the file, but running out of memory doing something else and it's at the 81st where memory runs out.

The newFileContents() list should be getting emptied by overwriting it with a new list, right?  That shouldn't be growing with every iteration in this function.  GC.Collect() was sort of a last ditch effort.

The original file that the 369 splits come from has been a headache for a few days now, causing UltraEdit to crash, SSIS to crash, C# to crash, etc.  Splitting it via 7zip seemed to be the only option that worked, and splitting it to 369 files seemed to be the only option 7zip had that didn't also reformat or somehow compress the file in an undesirable way.

Is there something that I'm missing?  Something in my code that keeps growing in memory?  I know File.ReadAllLines() opens and closes the file, so it should be disposed after called, right?  newFileContents() gets overwritten every 50th file, as does the string builder.  What else could I be doing?

Body:
You should just be looping over the rows in your source files and appending them to a new file. You're holding the contents of up to 50 10MB files in memory at once, plus anything else you're doing. This may be because you're compiling for x86 instead of x64, but there isn't any reason this should use anywhere near that memory. Something like the following:

        var files = Directory.Getfiles(System.IO.Path.Combing(path, "split")).ToList();
        //since you were skipping the first and last file
        files.Remove(files.FirstOrDefault());
        files.Remove(files.LastOrDefault());

        string combined_file_path = "<whatever you want to call this>";
        System.IO.StreamWriter combined_file_writer = null;
        try
        {
            foreach(var file in files)
            {
                //if multiple of 50, write footer, dispose of stream, and make a new stream
                if((files.IndexOf(file)) % 50 == 0)
                {
                    combined_file_writer?.WriteLine(FOOTER);
                    combined_file_writer?.Dispose();
                    combined_file_writer = new System.IO.StreamWriter(combined_file_path + "_1"); //increment the name somewhow
                    combined_file_writer.WriteLine(Header);
                }

                using(var file_reader = new System.IO.StreamReader(file))
                {
                    while(!file_reader.EOF)
                    {
                        combined_file_writer.WriteLine(file_reader.ReadLine());
                    }
                }

            }

            //finish out the last file
            combined_file_writer?.WriteLine(FOOTER);
        }
        finally
        {
            //dispose of last file
            combined_file_writer?.Dispose();
        }


问:
Catch array combine warning and print own error message?
I read some csv file and map the contents to the field names using array_combine:

```<code>$csv = array();
$a = array('some fields');
$b = array_combine($a, $csv);
</code>```

However if the field names in $a are different from what I specified in my csv file the method will fails with a warning

array_combine()
  [function.array-combine]: Both
  parameters should have an equal number
  of elements

I tried using try and catch but this does not work. As a note, I am working with zend framework.

Any ideas how to catch the warning?

答:
Grab the number of columns in the CSV and then compare it to $a's length. Since you didn't specify, I'll assume the array is one dimensional with each line from the CSV file.

```<code>if (count($csv) > 0 && count($a) == count(explode(',', $csv[0]))) {
    // Valid
} else {
    // Not valid
}
</code>```

Body:
I read some csv file and map the contents to the field names using array_combine:

$csv = array();
$a = array('some fields');
$b = array_combine($a, $csv);

However if the field names in $a are different from what I specified in my csv file the method will fails with a warning

array_combine()
  [function.array-combine]: Both
  parameters should have an equal number
  of elements

I tried using try and catch but this does not work. As a note, I am working with zend framework.

Any ideas how to catch the warning?

Body:
Grab the number of columns in the CSV and then compare it to $a's length. Since you didn't specify, I'll assume the array is one dimensional with each line from the CSV file.

if (count($csv) > 0 && count($a) == count(explode(',', $csv[0]))) {
    // Valid
} else {
    // Not valid
}