问:
'testthat', how should I interpret this failure?
I want to use 'testthat' to add tests to my package.

This is my test-file:

```<code>library(RBaseX)

test_that("Credentials are accepted", {
  skip_unless_socket_available()

  expect_error(BasexClient$new("localhost", 1984L, username = "admin", password = "denied"), "Access denied")

  Session <- BasexClient$new("localhost", 1984L, username = "admin", password = "admin")
  expect_equal(class(Session)[[1]], "BasexClient")
})
</code>```

skip_unless_socket_available  is defined in a separate helper.R-file:

```<code>skip_unless_socket_available <- function() {
  tryCatch({
    Socket <- socketConnection(host = "localhost", 1984,
                           open = "w+b", server = FALSE, blocking = TRUE, encoding = "utf-8")
    close(Socket)
    TRUE
  }, error = function(e) {
    skip(paste0("basexserver not available:\n'", conditionMessage(e), "'"))
  })
}
</code>```

When the program is executed I get this output:

```<code>Loading RBaseX
Testing RBaseX
✓ |  OK F W S | Context
✓ |   2       | test_RbaseX [0.2 s]
⠹ |   2 1     | test_RbaseX
══ Results ═══════════════════════════════
Duration: 0.3 s

OK:       2
Failed:   1
Warnings: 0
Skipped:  0
</code>```

No matter what I do, I still get 1 failure. Both exceptions, however, are handled correctly.

How should I act upon this failure?

Ben

After inserting 3 contexts() in test_RBaseX.R, I now get this output:

```<code>Loading RBaseX
Testing RBaseX
✓ |  OK F W S | Context
✓ |   2       | Access [0.1 s]
✓ |   2       | Create Session [0.1 s]
⠏ |   0       | Check setter/getter (and BasexClient$Execute())
✓ |   2       | Check setter/getter (and BasexClient$Execute())
⠏ |   0       | Intercept set/get is handled correctlyDatabase 'TestOpen' is niet gevonden.
Database 'TestOpen' is niet gevonden.
Database 'TestOpen' is niet gevonden.
✓ |   1       | Intercept set/get is handled correctly
⠙ |   1 1     | Intercept set/get is handled correctly
══ Results ════════════════════════════════════════════
Duration: 0.4 s

OK:       7
Failed:   1
Warnings: 0
Skipped:  0
</code>```

All tests give the expected result but then 1 failure is added. I still haven't seen any indication why.

Does this help?

Ben

(By the way, thanks to these testing-activities, I found and fixed serveral errors :-))

答:
After moving the file 'testthat.R' from the '/tests/testthat'-directory, to the '/tests'-directory, there were no failures detected anymore.

Ben

Body:
I want to use 'testthat' to add tests to my package.

This is my test-file:

library(RBaseX)

test_that("Credentials are accepted", {
  skip_unless_socket_available()

  expect_error(BasexClient$new("localhost", 1984L, username = "admin", password = "denied"), "Access denied")

  Session <- BasexClient$new("localhost", 1984L, username = "admin", password = "admin")
  expect_equal(class(Session)[[1]], "BasexClient")
})

skip_unless_socket_available  is defined in a separate helper.R-file:

skip_unless_socket_available <- function() {
  tryCatch({
    Socket <- socketConnection(host = "localhost", 1984,
                           open = "w+b", server = FALSE, blocking = TRUE, encoding = "utf-8")
    close(Socket)
    TRUE
  }, error = function(e) {
    skip(paste0("basexserver not available:\n'", conditionMessage(e), "'"))
  })
}

When the program is executed I get this output:

Loading RBaseX
Testing RBaseX
✓ |  OK F W S | Context
✓ |   2       | test_RbaseX [0.2 s]
⠹ |   2 1     | test_RbaseX
══ Results ═══════════════════════════════
Duration: 0.3 s

OK:       2
Failed:   1
Warnings: 0
Skipped:  0

No matter what I do, I still get 1 failure. Both exceptions, however, are handled correctly.

How should I act upon this failure?

Ben

After inserting 3 contexts() in test_RBaseX.R, I now get this output:

Loading RBaseX
Testing RBaseX
✓ |  OK F W S | Context
✓ |   2       | Access [0.1 s]
✓ |   2       | Create Session [0.1 s]
⠏ |   0       | Check setter/getter (and BasexClient$Execute())
✓ |   2       | Check setter/getter (and BasexClient$Execute())
⠏ |   0       | Intercept set/get is handled correctlyDatabase 'TestOpen' is niet gevonden.
Database 'TestOpen' is niet gevonden.
Database 'TestOpen' is niet gevonden.
✓ |   1       | Intercept set/get is handled correctly
⠙ |   1 1     | Intercept set/get is handled correctly
══ Results ════════════════════════════════════════════
Duration: 0.4 s

OK:       7
Failed:   1
Warnings: 0
Skipped:  0

All tests give the expected result but then 1 failure is added. I still haven't seen any indication why.

Does this help?

Ben

(By the way, thanks to these testing-activities, I found and fixed serveral errors :-))


来源: stackexchange

问:
Error "emit without supply or react" when tapping IO::Notifications
These nested supplies cause an error, but apparently only if the internal supply is IO::Notification. It does not seem to be a problem for any other supply:

```<code>my $supply = IO::Notification.watch-path( "/var/log/syslog" );

my $parsed = supply {
    $supply.tap: -> $v {
        emit( { Seen => $v.event }  );
        CATCH {
            default {
                $*ERR.say: .message;
            }
        }
    }
}

$parsed.tap( -> $v { say $v });

sleep 40;
</code>```

This is the error emitted:

```<code>emit without supply or react
emit without supply or react
</code>```

(when there's a event that fires the supply). I haven't been able to reproduce it in other kind of nested supplies, but this always fails. Any idea why?

答:
You must use whenever to subscribe to $supply, otherwise the subscription won't be associated with the supply block (and so, aside from emit not working, also won't get concurrency control, subscription management, and so forth).

```<code>my $supply = IO::Notification.watch-path( "foo" );

my $parsed = supply {
    # Solution: use `whenever` here
    whenever $supply -> $v {
        emit( { Seen => $v.event }  );
        CATCH {
            default {
                $*ERR.say: .message;
            }
        }
    }
}

$parsed.tap( -> $v { say $v });

sleep 40;
</code>```

(About it perhaps sometimes working out: if you subscribe to something that produces values synchronously after tapping, the emit handler would be in dynamic scope of the setup phase of the supply block, so in that case it may appear to work.)

ContentLicense: CC BY-SA 4.0

Body:
These nested supplies cause an error, but apparently only if the internal supply is IO::Notification. It does not seem to be a problem for any other supply:

my $supply = IO::Notification.watch-path( "/var/log/syslog" );

my $parsed = supply {
    $supply.tap: -> $v {
        emit( { Seen => $v.event }  );
        CATCH {
            default {
                $*ERR.say: .message;
            }
        }
    }
}

$parsed.tap( -> $v { say $v });

sleep 40;

This is the error emitted:

emit without supply or react
emit without supply or react

(when there's a event that fires the supply). I haven't been able to reproduce it in other kind of nested supplies, but this always fails. Any idea why?

Body:
You must use whenever to subscribe to $supply, otherwise the subscription won't be associated with the supply block (and so, aside from emit not working, also won't get concurrency control, subscription management, and so forth).

my $supply = IO::Notification.watch-path( "foo" );

my $parsed = supply {
    # Solution: use `whenever` here
    whenever $supply -> $v {
        emit( { Seen => $v.event }  );
        CATCH {
            default {
                $*ERR.say: .message;
            }
        }
    }
}

$parsed.tap( -> $v { say $v });

sleep 40;

(About it perhaps sometimes working out: if you subscribe to something that produces values synchronously after tapping, the emit handler would be in dynamic scope of the setup phase of the supply block, so in that case it may appear to work.)


问:
Reduce map to string in terraform
I have a map variable that I would like to reduce to a single string.

My variable looks like:

```<code>my_map = {
  key1 = "value1"
  key2 = "value2"
  key3 = "value3"
}
</code>```

And I am hoping to reduce this to key1:value1,key2:value2,key3:value3.

Checking terraform documentation I could not find any function to reduce a map but probably I am missing something.

Any help would be appreciated.

答:
You can get a list of the keys and another list of the values from the map by using the keys and values respectively.

You can then format those lists into a list of strings of those lists joined together by a colon by using the formatlist function.

And then finally you can get a single string of those elements of that list joined together by commas by using the join function.

```<code>variable "my_map" {
  default = {
    key1 = "value1"
    key2 = "value2"
    key3 = "value3"
  }
}

locals {
  my_list = formatlist("%s:%s", keys(var.my_map), values(var.my_map))
}

output "my_string" {
  value = join(",", local.my_list)
}
</code>```

Title: Reduce map to string in terraform

Body:
I have a map variable that I would like to reduce to a single string.

My variable looks like:

my_map = {
  key1 = "value1"
  key2 = "value2"
  key3 = "value3"
}

And I am hoping to reduce this to key1:value1,key2:value2,key3:value3.

Checking terraform documentation I could not find any function to reduce a map but probably I am missing something.

Any help would be appreciated.

Body:
You can get a list of the keys and another list of the values from the map by using the keys and values respectively.

You can then format those lists into a list of strings of those lists joined together by a colon by using the formatlist function.

And then finally you can get a single string of those elements of that list joined together by commas by using the join function.

variable "my_map" {
  default = {
    key1 = "value1"
    key2 = "value2"
    key3 = "value3"
  }
}

locals {
  my_list = formatlist("%s:%s", keys(var.my_map), values(var.my_map))
}

output "my_string" {
  value = join(",", local.my_list)
}


问:
What does (*(int *)&(w)) mean in c programming?
I'm learning processes and in the following code snippet:

```<code>/*
 * fork10 - Synchronizing with multiple children (wait)
 * Reaps children in arbitrary order
 * WIFEXITED and WEXITSTATUS to get info about terminated children
 */
void fork10()
{
    pid_t pid[N];
    int i, child_status;

    for (i = 0; i < N; i++)
    if ((pid[i] = fork()) == 0) {
        exit(100+i); /* Child */
    }
    for (i = 0; i < N; i++) { /* Parent */
        pid_t wpid = wait(&child_status);
        if (WIFEXITED(child_status))
            printf("Child %d terminated with exit status %d\n", wpid, WEXITSTATUS(child_status));
        else
            printf("Child %d terminate abnormally\n", wpid);
    }
}
</code>```

when I trace WIFEXITED function definition this is what I've got:

```<code>#define WIFEXITED(x)    (_WSTATUS(x) == 0)
#define _WSTATUS(x) (_W_INT(x) & 0177)
#define _W_INT(w)   (*(int *)&(w))  /* convert union wait to int */
</code>```

I have two questions:

Why use mask 0177 instead of 0b1111111, I've seen it many times, what's the benefits of using octal number over other formats? Personally I find binary more intuitive.

What's the meaning of (*(int *)&(w))?

Thanks!

答:
1 Why use mask 0177 instead of 0b1111111 ... ?

(This answer only addresses this portion of your question)

Because 0b1111111 is not a C integer constant per 6.4.4.1 Integer constants:

Syntax

1

```<code>      integer-constant:
            decimal-constant integer-suffixopt
            octal-constant integer-suffixopt
            hexadecimal-constant integer-suffixopt
      decimal-constant:
            nonzero-digit
            decimal-constant digit
      octal-constant:
            0
            octal-constant octal-digit
      hexadecimal-constant:
            hexadecimal-prefix hexadecimal-digit
            hexadecimal-constant hexadecimal-digit
      hexadecimal-prefix: one of
            0x   0X
      nonzero-digit: one of
            1   2   3   4   5   6   7   8   9
      octal-digit: one of
            0   1   2   3   4   5   6   7
      hexadecimal-digit: one of
            0   1   2   3   4   5   6   7   8   9
            a   b   c   d   e   f
            A   B   C   D   E   F
      integer-suffix:
            unsigned-suffix long-suffixopt
            unsigned-suffix long-long-suffix
            long-suffix unsigned-suffixopt
            long-long-suffix unsigned-suffixopt
      unsigned-suffix: one of
            u   U
      long-suffix: one of
            l   L
      long-long-suffix: one of
            ll   LL
</code>```

Description

2 An integer constant begins with a digit, but has no period or
  exponent part. It may have a prefix that specifies its base and a
  suffix that specifies its type.

3 A decimal constant begins with a nonzero digit and consists of a
  sequence of decimal digits. An octal constant consists of the prefix 0
  optionally followed by a sequence of the digits 0 through 7 only. A
  hexadecimal constant consists of the prefix 0x or 0X followed by a
  sequence of the decimal digits and the letters a (or A) through f (or
  F) with values 10 through 15 respectively.

By standard, C only supports decimal, octal, and hexadecimal integer constants.

Body:
I'm learning processes and in the following code snippet:

/*
 * fork10 - Synchronizing with multiple children (wait)
 * Reaps children in arbitrary order
 * WIFEXITED and WEXITSTATUS to get info about terminated children
 */
void fork10()
{
    pid_t pid[N];
    int i, child_status;

    for (i = 0; i < N; i++)
    if ((pid[i] = fork()) == 0) {
        exit(100+i); /* Child */
    }
    for (i = 0; i < N; i++) { /* Parent */
        pid_t wpid = wait(&child_status);
        if (WIFEXITED(child_status))
            printf("Child %d terminated with exit status %d\n", wpid, WEXITSTATUS(child_status));
        else
            printf("Child %d terminate abnormally\n", wpid);
    }
}

when I trace WIFEXITED function definition this is what I've got:

#define WIFEXITED(x)    (_WSTATUS(x) == 0)
#define _WSTATUS(x) (_W_INT(x) & 0177)
#define _W_INT(w)   (*(int *)&(w))  /* convert union wait to int */

I have two questions:

Why use mask 0177 instead of 0b1111111, I've seen it many times, what's the benefits of using octal number over other formats? Personally I find binary more intuitive.

What's the meaning of (*(int *)&(w))?

Thanks!

Body:
1 Why use mask 0177 instead of 0b1111111 ... ?

(This answer only addresses this portion of your question)

Because 0b1111111 is not a C integer constant per 6.4.4.1 Integer constants:

Syntax

1

      integer-constant:
            decimal-constant integer-suffixopt
            octal-constant integer-suffixopt
            hexadecimal-constant integer-suffixopt
      decimal-constant:
            nonzero-digit
            decimal-constant digit
      octal-constant:
            0
            octal-constant octal-digit
      hexadecimal-constant:
            hexadecimal-prefix hexadecimal-digit
            hexadecimal-constant hexadecimal-digit
      hexadecimal-prefix: one of
            0x   0X
      nonzero-digit: one of
            1   2   3   4   5   6   7   8   9
      octal-digit: one of
            0   1   2   3   4   5   6   7
      hexadecimal-digit: one of
            0   1   2   3   4   5   6   7   8   9
            a   b   c   d   e   f
            A   B   C   D   E   F
      integer-suffix:
            unsigned-suffix long-suffixopt
            unsigned-suffix long-long-suffix
            long-suffix unsigned-suffixopt
            long-long-suffix unsigned-suffixopt
      unsigned-suffix: one of
            u   U
      long-suffix: one of
            l   L
      long-long-suffix: one of
            ll   LL

Description

2 An integer constant begins with a digit, but has no period or
  exponent part. It may have a prefix that specifies its base and a
  suffix that specifies its type.

3 A decimal constant begins with a nonzero digit and consists of a
  sequence of decimal digits. An octal constant consists of the prefix 0
  optionally followed by a sequence of the digits 0 through 7 only. A
  hexadecimal constant consists of the prefix 0x or 0X followed by a
  sequence of the decimal digits and the letters a (or A) through f (or
  F) with values 10 through 15 respectively.

By standard, C only supports decimal, octal, and hexadecimal integer constants.


问:
MongoDb - cursor option is required after upgrade of mongodb
Since we were forced to upgrade our mongo installation, we're receiving an error during some aggregation function calls:

MongoDB.Driver.MongoCommandException: "Command 'aggregate' failed: The
  'cursor' option is required, except for aggregate with the explain
  argument (response: { "ok" : 0.0, "errmsg" : "The 'cursor' option is
  required, except for aggregate with the explain argument", "code" : 9,
  "codeName" : "FailedToParse" })"

```<code>        BsonArray arr = BsonSerializer.Deserialize<BsonArray>("[{ \"$match\" : { \"Param1\" : \"VAL\" } }, { \"$unwind\" : \"$Entries\" }, { \"$match\" : { \"PARAM\" : \"VALUE\" } }]");
        var pipeline = arr.Select(x => x.AsBsonDocument).ToList();
        // AggregateArgs aArgs = new AggregateArgs { Pipeline = bsonList };
        var cursor = collection.Aggregate(pipeline).ResultDocuments;
</code>```

I already figured out, that we have to manually add cursor configuration to the BsonDocument - but we weren't able to figure out, how the query should be configured.

Is there any work around for this exception (without changing drivers)?

答:
was finally able to fix it, by building the command by myself:</p>

```<code>        var cmd = new CommandDocument()
        {
            {"aggregate", "collection_name" },
            {"pipeline",  arr},
            {"cursor", BsonDocument.Parse("{}") }
        };

        var res = db.RunCommand(cmd);
</code>```

Body:
Since we were forced to upgrade our mongo installation, we're receiving an error during some aggregation function calls:

MongoDB.Driver.MongoCommandException: "Command 'aggregate' failed: The
  'cursor' option is required, except for aggregate with the explain
  argument (response: { "ok" : 0.0, "errmsg" : "The 'cursor' option is
  required, except for aggregate with the explain argument", "code" : 9,
  "codeName" : "FailedToParse" })"

        BsonArray arr = BsonSerializer.Deserialize<BsonArray>("[{ \"$match\" : { \"Param1\" : \"VAL\" } }, { \"$unwind\" : \"$Entries\" }, { \"$match\" : { \"PARAM\" : \"VALUE\" } }]");
        var pipeline = arr.Select(x => x.AsBsonDocument).ToList();
        // AggregateArgs aArgs = new AggregateArgs { Pipeline = bsonList };
        var cursor = collection.Aggregate(pipeline).ResultDocuments;

I already figured out, that we have to manually add cursor configuration to the BsonDocument - but we weren't able to figure out, how the query should be configured.

Is there any work around for this exception (without changing drivers)?

Body:
was finally able to fix it, by building the command by myself:

        var cmd = new CommandDocument()
        {
            {"aggregate", "collection_name" },
            {"pipeline",  arr},
            {"cursor", BsonDocument.Parse("{}") }
        };

        var res = db.RunCommand(cmd);


问:
Is it possible to make shared_ptr covariant?
I tried to make the following example.

```<code>struct BaseSPtr{};
struct DerivedSPtr : public BaseSPtr{};

class Base{
    public:
    //virtual shared_ptr<BaseSPtr> function();
    virtual BaseSPtr* function();
};

class Derived : public Base
{
    public:
    //shared_ptr<DerivedSPtr> function() override;
    DerivedSPtr* function() override;
};
</code>```

Can someone tell me if is it possible to make the example with shared_ptr valid?

答:
Unfortunately, no, covariance only applies to pointers and references in C++.

To have similar interface, you have to do something like :

```<code>class Base{
public:
    std::shared_ptr<BaseSPtr> function() { return std::shared_ptr<BaseSPtr>(function_v()); }
private:
    virtual BaseSPtr* function_v();
};

class Derived : public Base
{
public:
    std::shared_ptr<DerivedSPtr> function() // Hides Base::function
    {
        return std::shared_ptr<DerivedSPtr>(function_v());
    }
private:
    DerivedSPtr* function_v() override; // Overrides Base::function_v
};
</code>```

CRTP might help to reduce duplication.

Body:
I tried to make the following example.

struct BaseSPtr{};
struct DerivedSPtr : public BaseSPtr{};

class Base{
    public:
    //virtual shared_ptr<BaseSPtr> function();
    virtual BaseSPtr* function();
};

class Derived : public Base
{
    public:
    //shared_ptr<DerivedSPtr> function() override;
    DerivedSPtr* function() override;
};

Can someone tell me if is it possible to make the example with shared_ptr valid?

Body:
Unfortunately, no, covariance only applies to pointers and references in C++.

To have similar interface, you have to do something like :

class Base{
public:
    std::shared_ptr<BaseSPtr> function() { return std::shared_ptr<BaseSPtr>(function_v()); }
private:
    virtual BaseSPtr* function_v();
};

class Derived : public Base
{
public:
    std::shared_ptr<DerivedSPtr> function() // Hides Base::function
    {
        return std::shared_ptr<DerivedSPtr>(function_v());
    }
private:
    DerivedSPtr* function_v() override; // Overrides Base::function_v
};

CRTP might help to reduce duplication.


问:
Angular2 lazy loading module error 'cannot find module'
I was trying to find any solution for this error but nothing works for me. I have simple Angular2 App created with Angular-CLI. When I serve this app in browser I'm getting this error: EXCEPTION: Uncaught (in promise): Error: Cannot find module '/app/test.module'.  I was trying using different path in loadChildren:

```<code>'/app/test.module'
'./app/test.module'
'./test.module'
'/src/app/test.module'
</code>```

Folders

```<code>src/
  app/
    app-routing.module.ts
    app.component.ts
    app.module.ts
    test.component.ts
    test.module.ts
</code>```

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { RoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
```

<p><strong>app-routing.module.ts</strong></p>

<pre class="lang-js prettyprint-override"><code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  { path: '', loadChildren: '/app/test.module' }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: []
})
export class RoutingModule { }
</code>```

test.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { TestComponent } from './test.component';

export const routes: Routes = [
    { path: '', component: TestComponent }
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ],
  exports: [TestComponent],
  declarations: [TestComponent]
})
export default class TestModule { }
```

<p><strong>stack trace</strong></p>

<pre class="lang-js prettyprint-override"><code>        error_handler.js:45EXCEPTION: Uncaught (in promise): Error: Cannot find module '/app/test.module'.ErrorHandler.handleError @ error_handler.js:45next @ application_ref.js:273schedulerFn @ async.js:82SafeSubscriber.__tryOrUnsub @ Subscriber.js:223SafeSubscriber.next @ Subscriber.js:172Subscriber._next @ Subscriber.js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js:55EventEmitter.emit @ async.js:74onError @ ng_zone.js:120onHandleError @ ng_zone_impl.js:64ZoneDelegate.handleError @ zone.js:207Zone.runGuarded @ zone.js:113_loop_1 @ zone.js:379drainMicroTaskQueue @ zone.js:386
    2016-10-08 14:22:50.612 error_handler.js:50ORIGINAL STACKTRACE:ErrorHandler.handleError @ error_handler.js:50next @ application_ref.js:273schedulerFn @ async.js:82SafeSubscriber.__tryOrUnsub @ Subscriber.js:223SafeSubscriber.next @ Subscriber.js:172Subscriber._next @ Subscriber.js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js:55EventEmitter.emit @ async.js:74onError @ ng_zone.js:120onHandleError @ ng_zone_impl.js:64ZoneDelegate.handleError @ zone.js:207Zone.runGuarded @ zone.js:113_loop_1 @ zone.js:379drainMicroTaskQueue @ zone.js:386
    2016-10-08 14:22:50.613 error_handler.js:51Error: Uncaught (in promise): Error: Cannot find module '/app/test.module'.
        at resolvePromise (zone.js:429)
        at zone.js:406
        at ZoneDelegate.invoke (zone.js:203)
        at Object.onInvoke (ng_zone_impl.js:43)
        at ZoneDelegate.invoke (zone.js:202)
        at Zone.run (zone.js:96)
        at zone.js:462
        at ZoneDelegate.invokeTask (zone.js:236)
        at Object.onInvokeTask (ng_zone_impl.js:34)
        at ZoneDelegate.invokeTask (zone.js:235)ErrorHandler.handleError @ error_handler.js:51next @ application_ref.js:273schedulerFn @ async.js:82SafeSubscriber.__tryOrUnsub @ Subscriber.js:223SafeSubscriber.next @ Subscriber.js:172Subscriber._next @ Subscriber.js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js:55EventEmitter.emit @ async.js:74onError @ ng_zone.js:120onHandleError @ ng_zone_impl.js:64ZoneDelegate.handleError @ zone.js:207Zone.runGuarded @ zone.js:113_loop_1 @ zone.js:379drainMicroTaskQueue @ zone.js:386
    2016-10-08 14:22:50.614 zone.js:355Unhandled Promise rejection: Cannot find module '/app/test.module'. ; Zone: angular ; Task: Promise.then ; Value: Error: Cannot find module '/app/test.module'.(…) Error: Cannot find module '/app/test.module'.
        at webpackEmptyContext (http://localhost:4200/main.bundle.js:49550:8)
        at SystemJsNgModuleLoader.loadAndCompile (http://localhost:4200/main.bundle.js:57952:40)
        at SystemJsNgModuleLoader.load (http://localhost:4200/main.bundle.js:57945:60)
        at RouterConfigLoader.loadModuleFactory (http://localhost:4200/main.bundle.js:22354:128)
        at RouterConfigLoader.load (http://localhost:4200/main.bundle.js:22346:81)
        at MergeMapSubscriber.project (http://localhost:4200/main.bundle.js:61105:111)
        at MergeMapSubscriber._tryNext (http://localhost:4200/main.bundle.js:32515:27)
        at MergeMapSubscriber._next (http://localhost:4200/main.bundle.js:32505:18)
        at MergeMapSubscriber.Subscriber.next (http://localhost:4200/main.bundle.js:7085:18)
        at ScalarObservable._subscribe (http://localhost:4200/main.bundle.js:48555:24)consoleError @ zone.js:355_loop_1 @ zone.js:382drainMicroTaskQueue @ zone.js:386
    2016-10-08 14:22:50.620 zone.js:357Error: Uncaught (in promise): Error: Cannot find module '/app/test.module'.(…)consoleError @ zone.js:357_loop_1 @ zone.js:382drainMicroTaskQueue @ zone.js:386
</code>```

答:
For people who are using a recent Angular version (v9 in my case), you can setup your route with the following syntax declaration:

```<code>import { TestModule } from './modules/test.module';
const appRoutes: Routes = [
  { path: 'blogs', loadChildren: () => import('./modules/test.module').then(m => m.TestModule) },
];

// NgModule
// declarations
// imports
// providers
// bootstrap

export class AppModule { }
</code>```

Another way (without making the import at the top):

```<code>    const appRoutes: Routes = [
      { path: 'blogs', loadChildren: () => import('./modules/test.module').then(m => m.TestModule) },
    ];
</code>```

Body:
I was trying to find any solution for this error but nothing works for me. I have simple Angular2 App created with Angular-CLI. When I serve this app in browser I'm getting this error: EXCEPTION: Uncaught (in promise): Error: Cannot find module '/app/test.module'.  I was trying using different path in loadChildren:

'/app/test.module'
'./app/test.module'
'./test.module'
'/src/app/test.module'

Folders

src/
  app/
    app-routing.module.ts
    app.component.ts
    app.module.ts
    test.component.ts
    test.module.ts

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { RoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  { path: '', loadChildren: '/app/test.module' }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: []
})
export class RoutingModule { }

test.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { TestComponent } from './test.component';

export const routes: Routes = [
    { path: '', component: TestComponent }
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ],
  exports: [TestComponent],
  declarations: [TestComponent]
})
export default class TestModule { }

stack trace

        error_handler.js:45EXCEPTION: Uncaught (in promise): Error: Cannot find module '/app/test.module'.ErrorHandler.handleError @ error_handler.js:45next @ application_ref.js:273schedulerFn @ async.js:82SafeSubscriber.__tryOrUnsub @ Subscriber.js:223SafeSubscriber.next @ Subscriber.js:172Subscriber._next @ Subscriber.js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js:55EventEmitter.emit @ async.js:74onError @ ng_zone.js:120onHandleError @ ng_zone_impl.js:64ZoneDelegate.handleError @ zone.js:207Zone.runGuarded @ zone.js:113_loop_1 @ zone.js:379drainMicroTaskQueue @ zone.js:386
    2016-10-08 14:22:50.612 error_handler.js:50ORIGINAL STACKTRACE:ErrorHandler.handleError @ error_handler.js:50next @ application_ref.js:273schedulerFn @ async.js:82SafeSubscriber.__tryOrUnsub @ Subscriber.js:223SafeSubscriber.next @ Subscriber.js:172Subscriber._next @ Subscriber.js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js:55EventEmitter.emit @ async.js:74onError @ ng_zone.js:120onHandleError @ ng_zone_impl.js:64ZoneDelegate.handleError @ zone.js:207Zone.runGuarded @ zone.js:113_loop_1 @ zone.js:379drainMicroTaskQueue @ zone.js:386
    2016-10-08 14:22:50.613 error_handler.js:51Error: Uncaught (in promise): Error: Cannot find module '/app/test.module'.
        at resolvePromise (zone.js:429)
        at zone.js:406
        at ZoneDelegate.invoke (zone.js:203)
        at Object.onInvoke (ng_zone_impl.js:43)
        at ZoneDelegate.invoke (zone.js:202)
        at Zone.run (zone.js:96)
        at zone.js:462
        at ZoneDelegate.invokeTask (zone.js:236)
        at Object.onInvokeTask (ng_zone_impl.js:34)
        at ZoneDelegate.invokeTask (zone.js:235)ErrorHandler.handleError @ error_handler.js:51next @ application_ref.js:273schedulerFn @ async.js:82SafeSubscriber.__tryOrUnsub @ Subscriber.js:223SafeSubscriber.next @ Subscriber.js:172Subscriber._next @ Subscriber.js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js:55EventEmitter.emit @ async.js:74onError @ ng_zone.js:120onHandleError @ ng_zone_impl.js:64ZoneDelegate.handleError @ zone.js:207Zone.runGuarded @ zone.js:113_loop_1 @ zone.js:379drainMicroTaskQueue @ zone.js:386
    2016-10-08 14:22:50.614 zone.js:355Unhandled Promise rejection: Cannot find module '/app/test.module'. ; Zone: angular ; Task: Promise.then ; Value: Error: Cannot find module '/app/test.module'.(…) Error: Cannot find module '/app/test.module'.
        at webpackEmptyContext (http://localhost:4200/main.bundle.js:49550:8)
        at SystemJsNgModuleLoader.loadAndCompile (http://localhost:4200/main.bundle.js:57952:40)
        at SystemJsNgModuleLoader.load (http://localhost:4200/main.bundle.js:57945:60)
        at RouterConfigLoader.loadModuleFactory (http://localhost:4200/main.bundle.js:22354:128)
        at RouterConfigLoader.load (http://localhost:4200/main.bundle.js:22346:81)
        at MergeMapSubscriber.project (http://localhost:4200/main.bundle.js:61105:111)
        at MergeMapSubscriber._tryNext (http://localhost:4200/main.bundle.js:32515:27)
        at MergeMapSubscriber._next (http://localhost:4200/main.bundle.js:32505:18)
        at MergeMapSubscriber.Subscriber.next (http://localhost:4200/main.bundle.js:7085:18)
        at ScalarObservable._subscribe (http://localhost:4200/main.bundle.js:48555:24)consoleError @ zone.js:355_loop_1 @ zone.js:382drainMicroTaskQueue @ zone.js:386
    2016-10-08 14:22:50.620 zone.js:357Error: Uncaught (in promise): Error: Cannot find module '/app/test.module'.(…)consoleError @ zone.js:357_loop_1 @ zone.js:382drainMicroTaskQueue @ zone.js:386

Body:
For people who are using a recent Angular version (v9 in my case), you can setup your route with the following syntax declaration:

import { TestModule } from './modules/test.module';
const appRoutes: Routes = [
  { path: 'blogs', loadChildren: () => import('./modules/test.module').then(m => m.TestModule) },
];

// NgModule
// declarations
// imports
// providers
// bootstrap

export class AppModule { }

Another way (without making the import at the top):

    const appRoutes: Routes = [
      { path: 'blogs', loadChildren: () => import('./modules/test.module').then(m => m.TestModule) },
    ];


答:
give this a shot:

var cursor = collection.Aggregate<BsonDocument>(pipeline);

var results = cursor.ToList(); //just get a list of documents and be done with it

while (cursor.MoveNext()) // or iterate over cursor
{
    foreach (var doc in cursor.Current.ToArray())
    {
        //access your documents here
    }
}
```

Title: MongoDb - cursor option is required after upgrade of mongodb


问:
Most efficient way to remove non-numeric list entries
I'm looking to 'clean' a list by excluding any items which contain characters other than 0-9, and wondering if there's a more efficient way than e.g.

```<code>import re
invalid = re.compile('[^0-9]')
ls = ['1a', 'b3', '1']
cleaned = [i for i in ls if not invalid.search(i)]
print cleaned
>> ['1']
</code>```

As I'm going to be operating on large-ish lists (5k items) of long strings (15 chars).

答:
Anything wrong with the string method isdigit ?

```<code>>>> ls = ['1a', 'b3', '1']
>>> cleaned = [ x for x in ls if x.isdigit() ]
>>> cleaned
['1']
>>>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm looking to 'clean' a list by excluding any items which contain characters other than 0-9, and wondering if there's a more efficient way than e.g.

import re
invalid = re.compile('[^0-9]')
ls = ['1a', 'b3', '1']
cleaned = [i for i in ls if not invalid.search(i)]
print cleaned
>> ['1']

As I'm going to be operating on large-ish lists (5k items) of long strings (15 chars).

Body:
Anything wrong with the string method isdigit ?

>>> ls = ['1a', 'b3', '1']
>>> cleaned = [ x for x in ls if x.isdigit() ]
>>> cleaned
['1']
>>>


问:
How can I horizontally center an element?
How can I horizontally center a
 within another
 using CSS?

Foo foo

```

答:
I used Flexbox or CSS grid

Flexbox

#outer{
    display: flex;
    justify-content: center;
}```
</div>
</div>
</p></li>
<li><p>CSS grid</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-css lang-css prettyprint-override"><code>#outer {
    display: inline-grid;
    grid-template-rows: 100px 100px 100px;
    grid-template-columns: 100px 100px 100px;
    grid-gap: 3px;
}</code>```

You can solve the issue in many ways.

OwnerDisplayName: Lukas

Body:
I used Flexbox or CSS grid

Flexbox

#outer{
    display: flex;
    justify-content: center;
}

CSS grid

#outer {
    display: inline-grid;
    grid-template-rows: 100px 100px 100px;
    grid-template-columns: 100px 100px 100px;
    grid-gap: 3px;
}

You can solve the issue in many ways.


问:
setImage often without blocking UI thread Android
I have an ImageView. When user presses button I want to change image (it is animation-list) and run this animation. I used to use setImageResource, but it blocks UI thread and causes lags. I can't predict what image I would set befor user presses button. I tried to preload drawables but it causes OOM, because I have about 30 xmls with animation-list. How can I solve It? To sum up, I want to fastly change image in my ImageView and then start frame animation on it.</p>

答: I think you are performing a fetch operation on the UI thread for the image(either from storage or network call). That is what is causing the lag.</p>


问:
How to draw rounded rectangle in Android UI?
I need to draw a rounded rectangle in the Android UI. Having the same rounded rectangle for TextView and EditText would also be helpful.

答:
You could just define a new xml background in the drawables folder

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="enter_your_desired_color_here" />
<corners android:radius="enter_your_desired_radius_the_corners" />
</shape>
</code>```

After this just include it in your TextView or EditText
by defining it in the background.

```<code><TextView
 android:id="@+id/textView"
 android:layout_width="0dp"
 android:layout_height="80dp"
 android:background="YOUR_FILE_HERE"
 Android:layout_weight="1"
 android:gravity="center"
 android:text="TEXT_HERE"
 android:textSize="40sp" />
</code>```

Body:
You could just define a new xml background in the drawables folder

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="enter_your_desired_color_here" />
<corners android:radius="enter_your_desired_radius_the_corners" />
</shape>

After this just include it in your TextView or EditText
by defining it in the background.

<TextView
 android:id="@+id/textView"
 android:layout_width="0dp"
 android:layout_height="80dp"
 android:background="YOUR_FILE_HERE"
 Android:layout_weight="1"
 android:gravity="center"
 android:text="TEXT_HERE"
 android:textSize="40sp" />


问:
Check if array of objects key is empty and splice it
I have an array of objects, in that there is an empty key with Boolean value, if the Boolean value is false then the array of objects should be spliced.

The below is the array structure:

this.dataTobeDeleted= [{
    NotificationID: "2180",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": true
  },
  {
    NotificationID: "2182",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": false
  },
  {
    NotificationID: "2181",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": false
  }
]```
</div>
</div>
</p>

<p>In the above array there is an empty string "key" if the key value is <code>false</code> then need to splice the array of objects using index.</p>

<p>Below is the code which I have tried:</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-js lang-js prettyprint-override"><code>for (var i = 0; i < this.dataTobeDeleted.length; i++) {
    for (var val in this.dataTobeDeleted[i]) {
      if (val === "") {

        this.dataTobeDeleted[i]['isCheckedValue'] = this.dataTobeDeleted[i][""]; // insetring new key for empty key string
        delete this.dataTobeDeleted[i][""]; // Delete old key
        if (this.dataTobeDeleted[i].isCheckedValue === false) {
          this.dataTobeDeleted.splice(i, 1)
        }
      }
    }
}</code>```

The above code is correct, but I need it in shorter way as the code I tried is in lengthier and when there is too much data it will create a problem.

I tried using filter also, but I am not getting the empty key to check the boolean value.

答:
Use an array filter to remove the items you don't want:

```<code>this.dataTobeDeleted.filter(x => !!x[''])
</code>```

DEMO: https://stackblitz.com/edit/router-template-1t2xz7

This will create a new array, keeping only those where the property '' is truthy. If you wanted to be stricter, you could use a strict boolean check:

```<code>this.dataTobeDeleted.filter(x => x[''] === true)
</code>```

Body:
I have an array of objects, in that there is an empty key with Boolean value, if the Boolean value is false then the array of objects should be spliced.

The below is the array structure:

this.dataTobeDeleted= [{
    NotificationID: "2180",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": true
  },
  {
    NotificationID: "2182",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": false
  },
  {
    NotificationID: "2181",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": false
  }
]

In the above array there is an empty string "key" if the key value is false then need to splice the array of objects using index.

Below is the code which I have tried:

for (var i = 0; i < this.dataTobeDeleted.length; i++) {
    for (var val in this.dataTobeDeleted[i]) {
      if (val === "") {

        this.dataTobeDeleted[i]['isCheckedValue'] = this.dataTobeDeleted[i][""]; // insetring new key for empty key string
        delete this.dataTobeDeleted[i][""]; // Delete old key
        if (this.dataTobeDeleted[i].isCheckedValue === false) {
          this.dataTobeDeleted.splice(i, 1)
        }
      }
    }
}

The above code is correct, but I need it in shorter way as the code I tried is in lengthier and when there is too much data it will create a problem.

I tried using filter also, but I am not getting the empty key to check the boolean value.

Body:
Use an array filter to remove the items you don't want:

this.dataTobeDeleted.filter(x => !!x[''])

DEMO: https://stackblitz.com/edit/router-template-1t2xz7

This will create a new array, keeping only those where the property '' is truthy. If you wanted to be stricter, you could use a strict boolean check:

this.dataTobeDeleted.filter(x => x[''] === true)


问:
open a text area on click of a button - Jquery
Solution here: http://jsfiddle.net/kralco626/E9XVr/53/

Note: I think this is a duplicate of this question: how to show text area on button click? However, the OP of that question never followed up and I don't think any of the answers actually answer the question. I think Tomalak's comment on that question

Seems to me that, if anything, he wanted to pop up a textarea, wait for input into it, have the user press some 'OK' button then store the result in a variable.

Pretty much sums it up.

When the user clicks a button, I would like a text area to open in which the user can enter some text click an OK button and then the text area will close.

I don't want a dialog box, it's too intrusive, I want just a plain simple textarea or similar to open so that the top left of the text area is positioned at the bottom left of the button.

Thanks!

```<code><span style="width:20px;height:20px" class="remarkButton"></span>

$(".remarkButton").button({ icons: { primary: "ui-icon-pencil" }, text: false }).click(function () {
       $(...something to show text area...).data("$clickedButton",$(this));
});

//called when the OK button on the text area is clicked
function saveRemark($referenceToTextArea)
{
$referenceToTextArea.data("$clickedButton").data("remark",$referenceToTextArea.text());
}
</code>```

答:
Basically you'll want something like this:

```<code><button id="showarea" name="showarea" type="button" value="Show Textarea" />
<textarea id="textarea" name="text"></textarea>
<button id="textarea-ok" name="ok" type="button" value="Ok" />
<script type="text/javascript">
    $("#textarea, #textarea-ok").hide(); // or you can have hidden w/ CSS
    $("#showarea").click(function(){
        $("#textarea").show();
    });
    $("#textarea-ok").click(function(){
        $("#textarea").hide();
    });
</script>
</code>```

Note that you'll need to define the CSS accordingly as you prefer.

Body:
Solution here: http://jsfiddle.net/kralco626/E9XVr/53/

Note: I think this is a duplicate of this question: how to show text area on button click? However, the OP of that question never followed up and I don't think any of the answers actually answer the question. I think Tomalak's comment on that question

Seems to me that, if anything, he wanted to pop up a textarea, wait for input into it, have the user press some 'OK' button then store the result in a variable.

Pretty much sums it up.

When the user clicks a button, I would like a text area to open in which the user can enter some text click an OK button and then the text area will close.

I don't want a dialog box, it's too intrusive, I want just a plain simple textarea or similar to open so that the top left of the text area is positioned at the bottom left of the button.

Thanks!

$(".remarkButton").button({ icons: { primary: "ui-icon-pencil" }, text: false }).click(function () {
       $(...something to show text area...).data("$clickedButton",$(this));
});

//called when the OK button on the text area is clicked
function saveRemark($referenceToTextArea)
{
$referenceToTextArea.data("$clickedButton").data("remark",$referenceToTextArea.text());
}

Body:
Basically you'll want something like this:

<button id="showarea" name="showarea" type="button" value="Show Textarea" />
<textarea id="textarea" name="text"></textarea>
<button id="textarea-ok" name="ok" type="button" value="Ok" />
<script type="text/javascript">
    $("#textarea, #textarea-ok").hide(); // or you can have hidden w/ CSS
    $("#showarea").click(function(){
        $("#textarea").show();
    });
    $("#textarea-ok").click(function(){
        $("#textarea").hide();
    });
</script>

Note that you'll need to define the CSS accordingly as you prefer.


问:
C# - Return Custom Security Groups from Active Directory
I currently have the following code which successfully gets all Security Groups from AD and adds them into a Check List box:

```<code>try
{
    Logging.LogMessageToFile("Reading Security Groups from AD.");
    PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
    GroupPrincipal qbeGroup = new GroupPrincipal(ctx);
    PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);

    foreach (var found in srch.FindAll())
    {
        lstAdGroups.Items.Clear();
        lstAdGroups.Items.Add(found);
    }
}
catch (Exception ex)
{
    Logging.LogMessageToFile("Unexpected error reading Security Groups from AD: " + ex.Message);
}
</code>```

My issue is that it currently pulls every Security Group (where ideally I'd only like to only list custom created security groups (eg, exclude any from the Users or Builtin OU's). I can't see if there are any properties against groups to filter 'custom' from out the box. Is this even possible?

答:
PrincipalSearcher can only filter based on attributes that are exposed in properties of the various Principal classes. If you're looking for groups, you're limited to filtering based on the properties of the GroupPrincipal class.

That issues aside, filtering out objects in certain OUs isn't something you can do in a query at all simply because there is no AD attribute that contains the OU that you're allowed to filter on. So there is two ways you can do this:

Do what you're already doing, but in your loop, look at the DistinguishedName property of the result. If it's in an OU you don't like, then just continue;.

You can use DirectorySearcher directly (which is what PrincipalSearcher uses in the background anyway), and filter by the isCriticalSystemObject attribute. That will filter out built-in objects like the Domain Admins and Users groups, etc.

Here is a simple example using DirectorySearcher that just outputs the name of each group:

var searcher = new DirectorySearcher("(&(objectClass=group)(!isCriticalSystemObject=TRUE))");

using (var results = searcher.FindAll()) {
    foreach (SearchResult result in results) {
        Console.WriteLine(result.Properties["cn"][0]);
    }
}
```

Body:
I currently have the following code which successfully gets all Security Groups from AD and adds them into a Check List box:

try
{
    Logging.LogMessageToFile("Reading Security Groups from AD.");
    PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
    GroupPrincipal qbeGroup = new GroupPrincipal(ctx);
    PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);

    foreach (var found in srch.FindAll())
    {
        lstAdGroups.Items.Clear();
        lstAdGroups.Items.Add(found);
    }
}
catch (Exception ex)
{
    Logging.LogMessageToFile("Unexpected error reading Security Groups from AD: " + ex.Message);
}

My issue is that it currently pulls every Security Group (where ideally I'd only like to only list custom created security groups (eg, exclude any from the Users or Builtin OU's). I can't see if there are any properties against groups to filter 'custom' from out the box. Is this even possible?


问:
Create new data frame columns based on another column after group by
Initial Data Frame:

```<code>import pandas as pd
df = pd.DataFrame({'index': [0,0, 1,1, 2,2], 'Name': ['John', 'John', 'Mike', 'Mike', 'Tim', 'Tim'],
                   'Value': ['AAA', 'BBB', 'AAA', 'CCC', 'CCC', 'BBB'], 'Metric':[10, 20, 15,30, 35, 25],
                   'Direction': ['BUY', 'SELL', 'BUY', 'SELL', 'BUY', 'SELL']})

    index Name  Value  Metric Direction
      0  John   AAA      10       BUY
      0  John   BBB      20      SELL
      1  Mike   AAA      15       BUY
      1  Mike   CCC      30      SELL
      2   Tim   CCC      35       BUY
      2   Tim   BBB      25      SELL
</code>```

New Column "Value_New"

Grouped by "index", create new column "Valeu_New" equal to the counter-direction. When direction == "BUY", "Value_new" takes value of Direction == "SELL" and the other way around.
For each group, it would be like:

```<code>sell_value = df.loc[df.Direction == 'SELL', 'Value']
buy_value = df.loc[df.Direction == 'BUY', 'Value']
df.loc[df.Direction == 'BUY', "Value_New"] = sell_value
df.loc[df.Direction == 'SELL', "Value_New"] = buy_value
</code>```

Result:

```<code>index  Name Value  Metric Direction Value_New
  0  John   AAA      10       BUY       BBB
  0  John   BBB      20      SELL       AAA
  1  Mike   AAA      15       BUY       CCC
  1  Mike   CCC      30      SELL       AAA
  2   Tim   CCC      35       BUY       BBB
  2   Tim   BBB      25      SELL       CCC
</code>```

New Column "Metric_New"

Grouped by "index", create new column "Metric_New" equal to Metric value of Direction == "SELL". Ignoring the Metric value of the BUY. For each group, it would be like:

```<code>df['Metric_New'] = df.loc[df.Direction == "SELL", 'Metric']
</code>```

Result:

```<code>index  Name Value  Metric Direction  Metric_New
   0  John   AAA      10       BUY          20
   0  John   BBB      20      SELL          20
   1  Mike   AAA      15       BUY          30
   1  Mike   CCC      30      SELL          30
   2   Tim   CCC      35       BUY          25
   2   Tim   BBB      25      SELL          25
</code>```

Thanks for the help.

答:
The best solution I found so far is a for loop through indexes...</p>

```<code>for idx in df['index'].unique():
    sell_value = df.loc[(df['index'] == idx) & (df.Direction == 'SELL'), 'Value']
    buy_value = df.loc[(df['index'] == idx) & (df.Direction == 'BUY'), 'Value']
    df.loc[(df['index'] == idx) & (df.Direction == 'SELL'), 'CPBook'] = buy_value.values
    df.loc[(df['index'] == idx) & (df.Direction == 'BUY'), 'CPBook'] = sell_value.values

    sell_metric = df.loc[(df['index'] == idx) & (df.Direction == "SELL"), 'Metric']
    df.loc[(df['index'] == idx),'Metric_New'] = sell_metric.values
</code>```

Body:
Initial Data Frame:

import pandas as pd
df = pd.DataFrame({'index': [0,0, 1,1, 2,2], 'Name': ['John', 'John', 'Mike', 'Mike', 'Tim', 'Tim'],
                   'Value': ['AAA', 'BBB', 'AAA', 'CCC', 'CCC', 'BBB'], 'Metric':[10, 20, 15,30, 35, 25],
                   'Direction': ['BUY', 'SELL', 'BUY', 'SELL', 'BUY', 'SELL']})

    index Name  Value  Metric Direction
      0  John   AAA      10       BUY
      0  John   BBB      20      SELL
      1  Mike   AAA      15       BUY
      1  Mike   CCC      30      SELL
      2   Tim   CCC      35       BUY
      2   Tim   BBB      25      SELL

New Column "Value_New"

Grouped by "index", create new column "Valeu_New" equal to the counter-direction. When direction == "BUY", "Value_new" takes value of Direction == "SELL" and the other way around.
For each group, it would be like:

sell_value = df.loc[df.Direction == 'SELL', 'Value']
buy_value = df.loc[df.Direction == 'BUY', 'Value']
df.loc[df.Direction == 'BUY', "Value_New"] = sell_value
df.loc[df.Direction == 'SELL', "Value_New"] = buy_value

Result:

index  Name Value  Metric Direction Value_New
  0  John   AAA      10       BUY       BBB
  0  John   BBB      20      SELL       AAA
  1  Mike   AAA      15       BUY       CCC
  1  Mike   CCC      30      SELL       AAA
  2   Tim   CCC      35       BUY       BBB
  2   Tim   BBB      25      SELL       CCC

New Column "Metric_New"

Grouped by "index", create new column "Metric_New" equal to Metric value of Direction == "SELL". Ignoring the Metric value of the BUY. For each group, it would be like:

df['Metric_New'] = df.loc[df.Direction == "SELL", 'Metric']

Result:

index  Name Value  Metric Direction  Metric_New
   0  John   AAA      10       BUY          20
   0  John   BBB      20      SELL          20
   1  Mike   AAA      15       BUY          30
   1  Mike   CCC      30      SELL          30
   2   Tim   CCC      35       BUY          25
   2   Tim   BBB      25      SELL          25

Thanks for the help.

Body:
The best solution I found so far is a for loop through indexes...

for idx in df['index'].unique():
    sell_value = df.loc[(df['index'] == idx) & (df.Direction == 'SELL'), 'Value']
    buy_value = df.loc[(df['index'] == idx) & (df.Direction == 'BUY'), 'Value']
    df.loc[(df['index'] == idx) & (df.Direction == 'SELL'), 'CPBook'] = buy_value.values
    df.loc[(df['index'] == idx) & (df.Direction == 'BUY'), 'CPBook'] = sell_value.values

    sell_metric = df.loc[(df['index'] == idx) & (df.Direction == "SELL"), 'Metric']
    df.loc[(df['index'] == idx),'Metric_New'] = sell_metric.values


问:
How to put axios data into v-select by v-for?
I used axios to get multiple lines of data,
and then I wanted to put the data in v-select so that others could choose,
I thought of using v-for to make him print out line by line.
But the result shows no data available.

my code

```<code><template>
  <div>
     <v-select :item="desserts.name"></v-select>
  </div>
</template>

<script>
export default {
  data: () => ({
    desserts: [
      {
        id: "",
        name: ""
      }
    ]
  }),
  created() {
    this.getprotifile();
  },
  methods: {
    getprotifile() {
      this.axios
        .get("/api/admin/categories")
        .then(res => {
          //console.table(res.data);
          this.desserts = res.data;
          //console.log(this.desserts);
        })
        .catch(error => {
          console.error(error);
        })
        .finally(() => {});
    }
  }
};
</script>
</code>```

答:
I guess this one can solve the problem:</p>

```<code><v-select :item="desserts.filter(item => item.name)"></v-select>
</code>```

Body:
I used axios to get multiple lines of data,
and then I wanted to put the data in v-select so that others could choose,
I thought of using v-for to make him print out line by line.
But the result shows no data available.

my code

<template>

     <v-select :item="desserts.name"></v-select>

</template>

Body:
I guess this one can solve the problem:

<v-select :item="desserts.filter(item => item.name)"></v-select>


问:
recently i updated my expo-cli to version 3.13.1 and all of a sudden the applications are not working
after updating expo-cli to 3.13.1 , when i start the application i get errors .
on npm start

     - Some of your project's dependencies are not compatible with currently installed expo package version: - react-native-safe-area-context - expected version range: 0.6.0 - actual version installed: ^0.7.3 Your project may not work correctly until you install the correct versions of the packages.
To install the correct versions of these packages, please run: expo install [package-name ...]

if i install react-native-safe-area-context@0.6.0 , it gives the following error

Unable to resolve "./InitialWindowSafeAreaInsets" from "node_modules\react-native-safe-area-context\src\index.tsx

before updating it was working fine .

答:
Seems like you're installing it with npm. You should install it with Expo:</p>

```<code>expo install react-native-safe-area-context
</code>```

Body:
Seems like you're installing it with npm. You should install it with Expo:

expo install react-native-safe-area-context


问:
How can I preallocate a non-numeric vector in MATLAB?
I've often found myself doing something like this:

```<code>unprocessedData = fetchData();  % returns a vector of structs or objects
processedData = [];             % will be full of structs or objects

for dataIdx = 1 : length(unprocessedData)
    processedDatum = process(unprocessedData(dataIdx));
    processedData = [processedData; processedDatum];
end
</code>```

Which, whilst functional, isn't optimal - the processedData vector is growing inside the loop. Even mlint warns me that I should consider preallocating for speed.

Were data a vector of int8, I could do this:

```<code>% preallocate processed data array to prevent growth in loop
processedData = zeros(length(unprocessedData), 1, 'int8');
</code>```

and modify the loop to fill vector slots rather than concatenate.

is there a way to preallocate a vector so that it can subsequently hold structs or objects?

Update: inspired by Azim's answer, I've simply reversed the loop order. Processing the last element first forces preallocation of the entire vector in the first hit, as the debugger confirms:

```<code>unprocessedData = fetchData();

% note that processedData isn't declared outside the loop - this breaks
% it if it'll later hold non-numeric data. Instead we exploit matlab's
% odd scope rules which mean that processedData will outlive the loop
% inside which it is first referenced:

for dataIdx = length(unprocessedData) : -1 : 1
    processedData(dataIdx) = process(unprocessedData(dataIdx));
end
</code>```

This requires that any objects returned by process() have a valid zero-args constructor since MATLAB initialises processedData on the first write to it with real objects.

mlint still complains about possible array growth, but I think that's because it can't recognise the reversed loop iteration...

答:
You can pass in a cell array to struct of the appropriate size:

```<code>processedData = struct('field1', cell(nElements, 1), 'field2', []);
</code>```

This will make a structure array that is the same size as the cell array.

OwnerDisplayName: DanVinton

Body:
I've often found myself doing something like this:

unprocessedData = fetchData();  % returns a vector of structs or objects
processedData = [];             % will be full of structs or objects

for dataIdx = 1 : length(unprocessedData)
    processedDatum = process(unprocessedData(dataIdx));
    processedData = [processedData; processedDatum];
end

Which, whilst functional, isn't optimal - the processedData vector is growing inside the loop. Even mlint warns me that I should consider preallocating for speed.

Were data a vector of int8, I could do this:

% preallocate processed data array to prevent growth in loop
processedData = zeros(length(unprocessedData), 1, 'int8');

and modify the loop to fill vector slots rather than concatenate.

is there a way to preallocate a vector so that it can subsequently hold structs or objects?

Update: inspired by Azim's answer, I've simply reversed the loop order. Processing the last element first forces preallocation of the entire vector in the first hit, as the debugger confirms:

unprocessedData = fetchData();

% note that processedData isn't declared outside the loop - this breaks
% it if it'll later hold non-numeric data. Instead we exploit matlab's
% odd scope rules which mean that processedData will outlive the loop
% inside which it is first referenced:

for dataIdx = length(unprocessedData) : -1 : 1
    processedData(dataIdx) = process(unprocessedData(dataIdx));
end

This requires that any objects returned by process() have a valid zero-args constructor since MATLAB initialises processedData on the first write to it with real objects.

mlint still complains about possible array growth, but I think that's because it can't recognise the reversed loop iteration...

LastEditorDisplayName: DanVinton

Body:
You can pass in a cell array to struct of the appropriate size:

processedData = struct('field1', cell(nElements, 1), 'field2', []);

This will make a structure array that is the same size as the cell array.

OwnerDisplayName: ManWithSleeve


问:
Swift: click inside programmatically generated view inside table
Tried many things, but none of it worked.

My current views hierarchy:

TableView Cell

Vertical Stack View

Programmatically generated View - gesture recognizer not fired

```<code>let vContainer = UIView()
vContainer.translatesAutoresizingMaskIntoConstraints = false
vContainer.isUserInteractionEnabled = true
vContainer.backgroundColor = .red
//Some view generation inside box is skipped (can be seen on image)
self.vsvViewContainer.addArrangedSubview(vContainer)
var tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(showValuePicker(sender:)))
vContainer.addGestureRecognizer(tapRecognizer)
</code>```

later in class:

```<code>    @objc private func showValuePicker(sender: UITapGestureRecognizer) {
        print("showValuePicker")
    }
</code>```

Red box is View, where i want to add click.

答:
Add tapRecognizer.cancelsTouchesInView = false to your code

```<code>self.vsvViewContainer.addArrangedSubview(vContainer)
var tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(showValuePicker(sender:)))
tapRecognizer.cancelsTouchesInView = false
vContainer.addGestureRecognizer(tapRecognizer)
</code>```

Body:
Tried many things, but none of it worked.

My current views hierarchy:

TableView Cell

Vertical Stack View

Programmatically generated View - gesture recognizer not fired

let vContainer = UIView()
vContainer.translatesAutoresizingMaskIntoConstraints = false
vContainer.isUserInteractionEnabled = true
vContainer.backgroundColor = .red
//Some view generation inside box is skipped (can be seen on image)
self.vsvViewContainer.addArrangedSubview(vContainer)
var tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(showValuePicker(sender:)))
vContainer.addGestureRecognizer(tapRecognizer)

later in class:

    @objc private func showValuePicker(sender: UITapGestureRecognizer) {
        print("showValuePicker")
    }

Red box is View, where i want to add click.

Body:
Add tapRecognizer.cancelsTouchesInView = false to your code

self.vsvViewContainer.addArrangedSubview(vContainer)
var tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(showValuePicker(sender:)))
tapRecognizer.cancelsTouchesInView = false
vContainer.addGestureRecognizer(tapRecognizer)


问:
Why is my class not being toggled by this JavaScript function?
I am trying to toggle .active class when clicked on the #datePickerStart div. It only toggles when i click on the div but I want the element to be hidden when clicked outside of datepicker.

```<code>$('#datePickerStart').addEventListener('click', (e) => {
    console.log(e.path);
    if (!checkEventPathForClass(e.path, 'booking-dropdown')) {
        $('#dropDownStart').classList.toggle('active');
    }
});

function checkEventPathForClass(path, selector) {
    for (item of path) {
        if (item.classList && item.classList.contains(selector)) {
            return true;
        }
    }
    return false;
}
</code>```

```<code>.active {
    display: block;
}
</code>```

JSBin for my website.

答:
Create a separate function like shouldToggleClass and call that function from both the event listener. Also you can  directly use the click instead of addEventlistener since jquery is already used

```<code>const $ = (selector) => {
  return document.querySelector(selector);
};

$('#datePickerStart').addEventListener('click',(e) => {
  shouldToggleClass(e)

});

function shouldToggleClass(e) {
  const isEventPath = checkEventPathForClass(e.path, 'booking-dropdown');
  if (!isEventPath) {
    $('#dropDownStart').classList.toggle('active');
  }
}

function checkEventPathForClass(path, selector) {
  for (item of path) {
    if (item.classList && item.classList.contains(selector)) {
      return true;
    }
  }
  return false;
}

$('body').addEventListener('click',(e) => {
  shouldToggleClass(e)
});
</code>```

Body:
I am trying to toggle .active class when clicked on the #datePickerStart div. It only toggles when i click on the div but I want the element to be hidden when clicked outside of datepicker.

$('#datePickerStart').addEventListener('click', (e) => {
    console.log(e.path);
    if (!checkEventPathForClass(e.path, 'booking-dropdown')) {
        $('#dropDownStart').classList.toggle('active');
    }
});

function checkEventPathForClass(path, selector) {
    for (item of path) {
        if (item.classList && item.classList.contains(selector)) {
            return true;
        }
    }
    return false;
}

.active {
    display: block;
}

JSBin for my website.

Body:
Create a separate function like shouldToggleClass and call that function from both the event listener. Also you can  directly use the click instead of addEventlistener since jquery is already used

const $ = (selector) => {
  return document.querySelector(selector);
};

$('#datePickerStart').addEventListener('click',(e) => {
  shouldToggleClass(e)

});

function shouldToggleClass(e) {
  const isEventPath = checkEventPathForClass(e.path, 'booking-dropdown');
  if (!isEventPath) {
    $('#dropDownStart').classList.toggle('active');
  }
}

function checkEventPathForClass(path, selector) {
  for (item of path) {
    if (item.classList && item.classList.contains(selector)) {
      return true;
    }
  }
  return false;
}

$('body').addEventListener('click',(e) => {
  shouldToggleClass(e)
});


问:
Change Div Content with another file using jquery
how i can change div content with jquery if i click content in sidenav and 'div id="isi"' content change in another file.

```<code><div id="mySidenav" class="sidenav">
  <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
  <a href="about.html">About</a>
  <a href="#">Services</a>
  <a href="#">Clients</a>
  <a href="#">Contact</a>
</div>

<section id="main">

  <div>
    <span style="font-size:30px;cursor:pointer" onclick="openNav()">☰ </span>
  </div>

  <div class="row" id="isi">

  </div>
</code>```

sorry my English so bad

答:
Something like this should work</p>

```<code>$.ajax({
   method: 'GET',
   url: 'otherfile.html',
}).done(function(data) {
   $('#isi').html(data);
})

</code>```

Body:
how i can change div content with jquery if i click content in sidenav and 'div id="isi"' content change in another file.

  ×
  About
  Services
  Clients
  Contact

    ☰

sorry my English so bad

Body:
Something like this should work

$.ajax({
   method: 'GET',
   url: 'otherfile.html',
}).done(function(data) {
   $('#isi').html(data);
})


答:
Isn't the good synthax : </p>

```<code>`if (!checkEventPathForClass(e.path, 'booking-dropdown')) {
    $('#dropDownStart').classList.add('active');
}`
</code>```

<p>?</p>

Title: Why is my class not being toggled by this JavaScript function?

Body:
Isn't the good synthax :

`if (!checkEventPathForClass(e.path, 'booking-dropdown')) {
    $('#dropDownStart').classList.add('active');
}`

?


问:
Java Security Framework
Security always tends to take the last place in a new project. Or you use a framework like Spring where security is already build-in and can be switched on easily.
I try to find an open security framework that can be plugged-in to both Swing and Web applications (and JavaFX?), maybe easy to digest. I looked at plain JAAS, JGuard and JSecurity but its just too complicated to get started.
Any recommendations or experience to share ?
I am working with NB, Glassfish and MySQL.
Thanks
Sven</p>

答:
I have just taken a view of this http://shiro.apache.org/

Apache Shiro is a powerful and
  easy-to-use Java security framework
  that performs authentication,
  authorization, cryptography, and
  session management. With Shiro’s
  easy-to-understand API, you can
  quickly and easily secure any
  application – from the smallest mobile
  applications to the largest web and
  enterprise applications.

OwnerDisplayName: devdude

ContentLicense: CC BY-SA 2.5

Title: Java Security Framework

LastEditorDisplayName: Mr Potato Head


问:
FetchXML for SQL Join having filter
I am trying to build FetchXML equivalent of SQL query, I am quite new in using FetchXML:

```<code>SELECT o.opportunityid,c1.accountid
FROM dbo.opportunity o
LEFT JOIN dbo.account c1 on o.customerid = c1.accountid and o.customeridtype = 1
</code>```

into

```<code><fetch mapping="logical" version="1.0">
  <entity name="opportunity">
  <attribute name="opportunityid" />
    <link-entity name="account" from="accountid" to="customerid" alias="A1" link-type="outer" >
        <filter type="and" >
            <condition attribute="customeridtype" operator="eq" value="1" />
        </filter>
    <attribute name="accountid" />
    </link-entity>
</code>```

but this is throwing error saying that attribute "customeridtype" doesn't exist in entity "account". that attribute is from opportunity entity as in SQL query. How can I fix this?

答:
I just fired this in one of my Dynamics instance and gave correct result   </p>

```<code><fetch>
      <entity name="opportunity" >
        <attribute name="opportunityid" />
        <attribute name="customeridtype" />
        <filter type="and" >
          <condition attribute="customeridtype" operator="eq" value="1" />
        </filter>
        <link-entity name="account" from="accountid" to="customerid" link-type="outer" alias="Account" >
          <attribute name="accountid" alias="AccountId" />
        </link-entity>
      </entity>
    </fetch>
</code>```

Title: FetchXML for SQL Join having filter

Body:
I am trying to build FetchXML equivalent of SQL query, I am quite new in using FetchXML:

SELECT o.opportunityid,c1.accountid
FROM dbo.opportunity o
LEFT JOIN dbo.account c1 on o.customerid = c1.accountid and o.customeridtype = 1

into

<fetch mapping="logical" version="1.0">
  <entity name="opportunity">
  <attribute name="opportunityid" />
    <link-entity name="account" from="accountid" to="customerid" alias="A1" link-type="outer" >
        <filter type="and" >
            <condition attribute="customeridtype" operator="eq" value="1" />
        </filter>
    <attribute name="accountid" />
    </link-entity>

but this is throwing error saying that attribute "customeridtype" doesn't exist in entity "account". that attribute is from opportunity entity as in SQL query. How can I fix this?

Body:
I just fired this in one of my Dynamics instance and gave correct result

<fetch>
      <entity name="opportunity" >
        <attribute name="opportunityid" />
        <attribute name="customeridtype" />
        <filter type="and" >
          <condition attribute="customeridtype" operator="eq" value="1" />
        </filter>
        <link-entity name="account" from="accountid" to="customerid" link-type="outer" alias="Account" >
          <attribute name="accountid" alias="AccountId" />
        </link-entity>
      </entity>
    </fetch>


问:
How to create several buffers around points of a simple feature in a loop?
I have sample data representing 2 points (sf). I want to create buffers with the width 2, 1 and 0.5. My approach is the below. Is there any way to do this in more efficient way? How can I wrap this process up in a loop?</p>

```<code>library(sf)

g = st_sfc(c(st_point(1:2),st_point(3:2)))

g.2 <- st_buffer(g,2)
g.1 <- st_buffer(g,1)
g.05 <- st_buffer(g,0.5)

plot(st_geometry(g.2))
plot(st_geometry(g.1), add=TRUE)
plot(st_geometry(g.05), add=TRUE)
plot(st_geometry(g), add=TRUE)
</code>```

答:
I tried the following. I created a loop with map() in the purrr package and created three objects in a list. Then, I drew the first circle and added more circles in a for loop.

```<code>library(purrr)
library(sf)

g <- st_sfc(c(st_point(1:2),st_point(3:2)))

purrr::map(.x = c(0.5, 1, 2),
           .f = function(x){st_buffer(g, x)}) -> foo

plot(st_geometry(foo[[1]]), xlim = c(0, 4), ylim = c(0, 4))

for(i in 2:length(foo)) {plot(st_geometry(foo[[i]]), add = TRUE)}
</code>```

Body:
I have sample data representing 2 points (sf). I want to create buffers with the width 2, 1 and 0.5. My approach is the below. Is there any way to do this in more efficient way? How can I wrap this process up in a loop?

library(sf)

g = st_sfc(c(st_point(1:2),st_point(3:2)))

g.2 <- st_buffer(g,2)
g.1 <- st_buffer(g,1)
g.05 <- st_buffer(g,0.5)

plot(st_geometry(g.2))
plot(st_geometry(g.1), add=TRUE)
plot(st_geometry(g.05), add=TRUE)
plot(st_geometry(g), add=TRUE)

Body:
I tried the following. I created a loop with map() in the purrr package and created three objects in a list. Then, I drew the first circle and added more circles in a for loop.

library(purrr)
library(sf)

g <- st_sfc(c(st_point(1:2),st_point(3:2)))

purrr::map(.x = c(0.5, 1, 2),
           .f = function(x){st_buffer(g, x)}) -> foo

plot(st_geometry(foo[[1]]), xlim = c(0, 4), ylim = c(0, 4))

for(i in 2:length(foo)) {plot(st_geometry(foo[[i]]), add = TRUE)}


问:
PHP 7.4.2 [extension] build errors on Windows
I am using a package (SAP RFC Connector) for some time now that is retrieved from here https://github.com/gkralik/php7-sapnwrfc

The package is working as expected on all PHP versions until 7.4.2 with source build.

I've built the php_sapnwrfc.dll from source with both VS2015 and VS2019 but I am unable to get it working due to these errors, that I am unable to solve.

For building, I've used this procedure:

https://gkralik.github.io/php7-sapnwrfc/building.html#building-on-windows

https://wiki.php.net/internals/windows/stepbystepbuild_sdk_2

Is there someone out there that knows how to solve this?

With VS2019 I got this error but no one knows what it means, especially the warning with the core number.

Warning: PHP Startup:

Can't load module 'C:/ownprograms/wamp/bin/php/php7.4.2/ext/php_sapnwrfc.dll' as it's linked with 14.24, but the core is linked with 14.16 in Unknown on line 0

With VS2015 I got this error but this is due to compiler.

[17-Feb-2020 10:48:43 UTC] PHP Warning:  PHP Startup: sapnwrfc: Unable to initialize module

Module compiled with build ID=API20190902,TS,VS16

PHP    compiled with build ID=API20190902,TS,VC15

These options need to match

PHP version: 7.4.2 TS

Any help would be appreciated.

答:
Someone got my problem solved, here is his reply.

Try with the attached DLLs. I've built it for both 7.4.2 and 7.4.3
  with extension version 1.3.0, vc15, ts and x64. It should work.
  php_sapnwrfc.zip

For any PHP version > 7.2 except master branch you need to use
  VC15(Visual Studio 2017). I saw in your trace that you were using VC16
  (Visual Studio 2019).

I can confirm that I tried building it with VS2015 and VS2019, not with VS2017.

Thank you, the issue is solved.


问:
How to optimize the query to update a table column with a column in another table in oracle
I have 2 tables. One table is cr_archive which has around 9000000 records. It has a column called v_sales_person which does not have values. I have another table called table_2 which has the same column called v_sales_person in which there are values. Both tables have columns called product_label,account_num. I want to select data from table _2 which has the same product_labels and account_num as in cr_archive and update the column v_sales_person in cr_archive with the values in table_2 which fulfill the above conditions(using oracle). I tried the following query.

```<code>update cr_archive a
set a.v_sales_person = (select distinct b.v_sales_person from table_2 b where a.account_num = b.account_num and A.PRODUCT_LABEL=b.PRODUCT_LABEL )
/
commit
/
</code>```

But the query is taking more than 6 hours to process and don't know whether it gives the output. I have 2 questions.
1. Is the above query correct?
2. Is there any method to optimize the above query.

答:
You can use MERGE statement as follows:

```<code>MERGE INTO CR_ARCHIVE A
USING (
          SELECT
              MAX(B.V_SALES_PERSON) AS V_SALES_PERSON,
              B.ACCOUNT_NUM,
              B.PRODUCT_LABEL
          FROM
              TABLE_2 B
          GROUP BY
              B.ACCOUNT_NUM,
              B.PRODUCT_LABEL
      )
B ON ( A.ACCOUNT_NUM = B.ACCOUNT_NUM
       AND A.PRODUCT_LABEL = B.PRODUCT_LABEL )
WHEN MATCHED THEN
UPDATE SET A.V_SALES_PERSON = B.V_SALES_PERSON;
/
</code>```

Cheers!!

Body:
I have 2 tables. One table is cr_archive which has around 9000000 records. It has a column called v_sales_person which does not have values. I have another table called table_2 which has the same column called v_sales_person in which there are values. Both tables have columns called product_label,account_num. I want to select data from table _2 which has the same product_labels and account_num as in cr_archive and update the column v_sales_person in cr_archive with the values in table_2 which fulfill the above conditions(using oracle). I tried the following query.

update cr_archive a
set a.v_sales_person = (select distinct b.v_sales_person from table_2 b where a.account_num = b.account_num and A.PRODUCT_LABEL=b.PRODUCT_LABEL )
/
commit
/

But the query is taking more than 6 hours to process and don't know whether it gives the output. I have 2 questions.
1. Is the above query correct?
2. Is there any method to optimize the above query.

Body:
You can use MERGE statement as follows:

MERGE INTO CR_ARCHIVE A
USING (
          SELECT
              MAX(B.V_SALES_PERSON) AS V_SALES_PERSON,
              B.ACCOUNT_NUM,
              B.PRODUCT_LABEL
          FROM
              TABLE_2 B
          GROUP BY
              B.ACCOUNT_NUM,
              B.PRODUCT_LABEL
      )
B ON ( A.ACCOUNT_NUM = B.ACCOUNT_NUM
       AND A.PRODUCT_LABEL = B.PRODUCT_LABEL )
WHEN MATCHED THEN
UPDATE SET A.V_SALES_PERSON = B.V_SALES_PERSON;
/

Cheers!!


问:
Mysql do not fetch multiple rows with same field value
I have two tables: categories and models. For now, categories table is important.

```<code>| id | nazwa | desc_s1 | photo | active | id_user |
|  1 | Audi  |   test  |  url  |   1    |    2    |
|  2 | BMW   |   test  |  url  |   1    |    2    |
|  3 | Ford  |   test  |  url  |   1    |    2    |
|  4 | BMW   |   test  |  url  |   1    |    2    |
</code>```

And I have php:

```<code>$query_categories = "SELECT * FROM `categories` WHERE nazwa='$selected_category' AND active=1 AND id_user=".$_SESSION['id_user'].";";
$query_model = "SELECT * FROM models WHERE active=1";

$result_categories = mysqli_query($con, $query_categories);
$result_model = mysqli_query($con, $query_model);

if (mysqli_num_rows($result_categories) > 0 && mysqli_num_rows($result_model) > 0) {

    $row_categories = mysqli_fetch_assoc($result_categories);
    $selected_category =  $row_categories['nazwa'];
    $_SESSION['selected_category'] = $selected_category;
    $_SESSION['title_content'] = $title_content;
    $_SESSION['price'] = $price;
    $category =  $row_categories['nazwa'];
    $desc_s1 =  $row_categories['desc_s1'];
    $photo =  $row_categories['photo'];

    $row_model = mysqli_fetch_assoc($result_model);
    $selected_model =  $row_model['model'];
    $stan =  $row_model['stan'];
    $przeznaczenie =  $row_model['przeznaczenie'];
    $kolor =  $row_model['kolor'];
    $typ =  $row_model['typ'];

    $table = array();
    do
    {
        array_push($table, '
            <tr>
            <td class="text-left">353</td>
            <td class="text-left">Stan|' . $row_model['stan'] . '<br />Przeznaczenie|' . $row_model['przeznaczenie'] . '<br />Kolor|' . $row_model['kolor'] . '<br />Typ|' . $row_model['typ'] . '<br /></td>
            <td class="text-left">' . str_replace(' ', '_', $row_model['model']) . '<br /></td>
            <td class="text-left">' . $title_content . ' ' . $selected_category . ' ' . $row_model['model'] . '</td>
            <td class="text-left">' . $price . '</td>
            <td class="text-left">' . nl2br($row_categories['photo']) . '</td>
            <td class="text-left">' . nl2br(htmlspecialchars($row_categories['desc_s1'])) . '</td>
            </tr>');
    } while ($row_model = mysqli_fetch_array($result_model));
} else {
    array_push($errors, '<span class="badge badge-warning">Error</span>');
}
</code>```

Its working but, the output table gives me 3 results, missing is the last one. I know the reason is the same name name like row id=2 but how to get all of the rows in result? I have tried with while inside while but it doesn't work as I thought.

答:
It is because you're fetching twice;

```<code>$row_model = mysqli_fetch_assoc($result_model);
</code>```

and

```<code>while ($row_model = mysqli_fetch_array($result_model));
</code>```

The first time gets one row, the second gets the rest. Refactor your code to use the fetch only one time. It is likely you can remove this entire block of code:

```<code>$row_model = mysqli_fetch_assoc($result_model);
$selected_model =  $row_model['model'];
$stan =  $row_model['stan'];
$przeznaczenie =  $row_model['przeznaczenie'];
$kolor =  $row_model['kolor'];
$typ =  $row_model['typ'];
</code>```

Instead of do...while like you have here:

```<code>do
    {
        array_push($table, '
            <tr>
            <td class="text-left">353</td>
            <td class="text-left">Stan|' . $row_model['stan'] . '<br />Przeznaczenie|' . $row_model['przeznaczenie'] . '<br />Kolor|' . $row_model['kolor'] . '<br />Typ|' . $row_model['typ'] . '<br /></td>
            <td class="text-left">' . str_replace(' ', '_', $row_model['model']) . '<br /></td>
            <td class="text-left">' . $title_content . ' ' . $selected_category . ' ' . $row_model['model'] . '</td>
            <td class="text-left">' . $price . '</td>
            <td class="text-left">' . nl2br($row_categories['photo']) . '</td>
            <td class="text-left">' . nl2br(htmlspecialchars($row_categories['desc_s1'])) . '</td>
            </tr>');
    } while ($row_model = mysqli_fetch_array($result_model));
</code>```

Change it to a while loop:

```<code>while ($row_model = mysqli_fetch_array($result_model))
{
    array_push($table, '
        <tr>
        <td class="text-left">353</td>
        <td class="text-left">Stan|' . $row_model['stan'] . '<br />Przeznaczenie|' . $row_model['przeznaczenie'] . '<br />Kolor|' . $row_model['kolor'] . '<br />Typ|' . $row_model['typ'] . '<br /></td>
        <td class="text-left">' . str_replace(' ', '_', $row_model['model']) . '<br /></td>
        <td class="text-left">' . $title_content . ' ' . $selected_category . ' ' . $row_model['model'] . '</td>
        <td class="text-left">' . $price . '</td>
        <td class="text-left">' . nl2br($row_categories['photo']) . '</td>
        <td class="text-left">' . nl2br(htmlspecialchars($row_categories['desc_s1'])) . '</td>
        </tr>');
}
</code>```

Warning!

Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!

Body:
I have two tables: categories and models. For now, categories table is important.

| id | nazwa | desc_s1 | photo | active | id_user |
|  1 | Audi  |   test  |  url  |   1    |    2    |
|  2 | BMW   |   test  |  url  |   1    |    2    |
|  3 | Ford  |   test  |  url  |   1    |    2    |
|  4 | BMW   |   test  |  url  |   1    |    2    |

And I have php:

$query_categories = "SELECT * FROM `categories` WHERE nazwa='$selected_category' AND active=1 AND id_user=".$_SESSION['id_user'].";";
$query_model = "SELECT * FROM models WHERE active=1";

$result_categories = mysqli_query($con, $query_categories);
$result_model = mysqli_query($con, $query_model);

if (mysqli_num_rows($result_categories) > 0 && mysqli_num_rows($result_model) > 0) {

    $row_categories = mysqli_fetch_assoc($result_categories);
    $selected_category =  $row_categories['nazwa'];
    $_SESSION['selected_category'] = $selected_category;
    $_SESSION['title_content'] = $title_content;
    $_SESSION['price'] = $price;
    $category =  $row_categories['nazwa'];
    $desc_s1 =  $row_categories['desc_s1'];
    $photo =  $row_categories['photo'];

    $row_model = mysqli_fetch_assoc($result_model);
    $selected_model =  $row_model['model'];
    $stan =  $row_model['stan'];
    $przeznaczenie =  $row_model['przeznaczenie'];
    $kolor =  $row_model['kolor'];
    $typ =  $row_model['typ'];

    $table = array();
    do
    {
        array_push($table, '

            353
            Stan|' . $row_model['stan'] . '
Przeznaczenie|' . $row_model['przeznaczenie'] . '
Kolor|' . $row_model['kolor'] . '
Typ|' . $row_model['typ'] . '

            ' . str_replace(' ', '_', $row_model['model']) . '

            ' . $title_content . ' ' . $selected_category . ' ' . $row_model['model'] . '
            ' . $price . '
            ' . nl2br($row_categories['photo']) . '
            ' . nl2br(htmlspecialchars($row_categories['desc_s1'])) . '

');
    } while ($row_model = mysqli_fetch_array($result_model));
} else {
    array_push($errors, 'Error');
}

Its working but, the output table gives me 3 results, missing is the last one. I know the reason is the same name name like row id=2 but how to get all of the rows in result? I have tried with while inside while but it doesn't work as I thought.

Body:
It is because you're fetching twice;

$row_model = mysqli_fetch_assoc($result_model);

and

while ($row_model = mysqli_fetch_array($result_model));

The first time gets one row, the second gets the rest. Refactor your code to use the fetch only one time. It is likely you can remove this entire block of code:

$row_model = mysqli_fetch_assoc($result_model);
$selected_model =  $row_model['model'];
$stan =  $row_model['stan'];
$przeznaczenie =  $row_model['przeznaczenie'];
$kolor =  $row_model['kolor'];
$typ =  $row_model['typ'];

Instead of do...while like you have here:

do
    {
        array_push($table, '
            <tr>
            <td class="text-left">353</td>
            <td class="text-left">Stan|' . $row_model['stan'] . '<br />Przeznaczenie|' . $row_model['przeznaczenie'] . '<br />Kolor|' . $row_model['kolor'] . '<br />Typ|' . $row_model['typ'] . '<br /></td>
            <td class="text-left">' . str_replace(' ', '_', $row_model['model']) . '<br /></td>
            <td class="text-left">' . $title_content . ' ' . $selected_category . ' ' . $row_model['model'] . '</td>
            <td class="text-left">' . $price . '</td>
            <td class="text-left">' . nl2br($row_categories['photo']) . '</td>
            <td class="text-left">' . nl2br(htmlspecialchars($row_categories['desc_s1'])) . '</td>
            </tr>');
    } while ($row_model = mysqli_fetch_array($result_model));

Change it to a while loop:

while ($row_model = mysqli_fetch_array($result_model))
{
    array_push($table, '
        <tr>
        <td class="text-left">353</td>
        <td class="text-left">Stan|' . $row_model['stan'] . '<br />Przeznaczenie|' . $row_model['przeznaczenie'] . '<br />Kolor|' . $row_model['kolor'] . '<br />Typ|' . $row_model['typ'] . '<br /></td>
        <td class="text-left">' . str_replace(' ', '_', $row_model['model']) . '<br /></td>
        <td class="text-left">' . $title_content . ' ' . $selected_category . ' ' . $row_model['model'] . '</td>
        <td class="text-left">' . $price . '</td>
        <td class="text-left">' . nl2br($row_categories['photo']) . '</td>
        <td class="text-left">' . nl2br(htmlspecialchars($row_categories['desc_s1'])) . '</td>
        </tr>');
}

Warning!

Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!


问:
C# - Finding a string between two strings
I have a string that looks like this: Value->Value2->Value3->ImportantValue->val.

I would like to extract ImportantValue. I have read other posts concerning this question but none of them works for me. I tried this:

```<code>int pFrom = path.IndexOf("->") + "->".Length;
int pTo = path.LastIndexOf("->val");
String result = path.Substring(pFrom, pTo - pFrom);
</code>```

It returns Value2->Value3->ImportantValue->val because it gives out the string between the first -> and ->val. Any ideas on how I would change the above code so that it returns ImportantValue? Thanks in advance.

EDIT

Sorry, I forgot to specify that ImportantValue is always different. The entire string also changes, meaning it will have more three Values. But the ImportantValue is always the second to last element so I will mark the answer from Paul Kertscher as the right one and upvote the other similar answers.

答:
Provided that the string has always the same format, you could use just the Split method, and fetch the previous from the last element of the array returned from Split.

```<code>var values = path.Split(new []{"->"}, StringSplitOptions.None);
var importantValue = values[values.Length-2];
</code>```

Pls check .NET Fiddle

Body:
I have a string that looks like this: Value->Value2->Value3->ImportantValue->val.

I would like to extract ImportantValue. I have read other posts concerning this question but none of them works for me. I tried this:

int pFrom = path.IndexOf("->") + "->".Length;
int pTo = path.LastIndexOf("->val");
String result = path.Substring(pFrom, pTo - pFrom);

It returns Value2->Value3->ImportantValue->val because it gives out the string between the first -> and ->val. Any ideas on how I would change the above code so that it returns ImportantValue? Thanks in advance.

EDIT

Sorry, I forgot to specify that ImportantValue is always different. The entire string also changes, meaning it will have more three Values. But the ImportantValue is always the second to last element so I will mark the answer from Paul Kertscher as the right one and upvote the other similar answers.

Body:
Provided that the string has always the same format, you could use just the Split method, and fetch the previous from the last element of the array returned from Split.

var values = path.Split(new []{"->"}, StringSplitOptions.None);
var importantValue = values[values.Length-2];

Pls check .NET Fiddle


问:
Finding average length of strings in a list
I have a large list containing a lot of data which is read from a csv file.
For simplicity I will give you a dummy list which will have far less data in it.

```<code>list1 = ['foo', 'bar', 'bob', 'jess', 'google', 'alphabet']
</code>```

I want to find the average length of strings within the list. I am currently doing it like this:

```<code>all_lengths = []
num_of_strings = len(list1)

for item in list1:
    string_size = len(item)
    all_lengths.append(string_size)
    total_size = sum(all_lengths)
ave_size = float(total_size) / float(num_of_strings)
</code>```

The problem is that because the real list is so large it is taking an incredibly long time to perform this.

Is there a more optimal or elegant way to perform this.

Also, for what it's worth, using Python2.7

答:
I guess you can concat the strings in a loop into one big string to check the length of all the items.

list1 = ['foo', 'bar', 'bob', 'jess', 'google', 'alphabet']

combined_string = ''
for item in list1:
    combined_string += item

print(float(len(combined_string)) / float(len(list1)))
```

Body:
I have a large list containing a lot of data which is read from a csv file.
For simplicity I will give you a dummy list which will have far less data in it.

list1 = ['foo', 'bar', 'bob', 'jess', 'google', 'alphabet']

I want to find the average length of strings within the list. I am currently doing it like this:

all_lengths = []
num_of_strings = len(list1)

for item in list1:
    string_size = len(item)
    all_lengths.append(string_size)
    total_size = sum(all_lengths)
ave_size = float(total_size) / float(num_of_strings)

The problem is that because the real list is so large it is taking an incredibly long time to perform this.

Is there a more optimal or elegant way to perform this.

Also, for what it's worth, using Python2.7


问:
Confusion about the scope and visibility of variable and argument in a function
I don't understand why do the test1 and test2 will return 2 different output when they are the same.</p>

```<code>   python3.7.4

   fin=open('D:\Python\Think Python\words.txt')

   def build_list_append(file):
       word_list=[]
       for line in fin:
           word=line.strip()
           word_list.append(word)
       return word_list

   def test1(worklist1=build_list_append(fin)):
       print("This is test1,It will return a non-empty list")
       print(len(worklist1))

   def test2(worklist2=build_list_append(fin)):
       print("This is test2,It will return an empty list")
       print(len(worklist2))

</code>```

答:
Short Answer: That's because once test1() is called, read pointer will move to end of file. Once test2() is called there are no lines left to read, hence 0 length.

Long Answer:

At fin = open('D:\Python\Think Python\words.txt') the read pointer will point at the beginning of the file.

Once file1() is called, it will call build_list_append(fin) which will iterate through the file line-by-line. Because of this all lines will be store in word_list and length will be returned.

Now, the pointer is pointing at the end of the file.

After calling test2(), program again calls build_list_append(fin) which want to iterate through whole file line-by-line, but since pointer is already at end of the file it doesn't have any content to go through. Hence, length 0 is returned.

If you try closing the file and pass a fresh file object, test2() will return same value as test1().

Body:
I don't understand why do the test1 and test2 will return 2 different output when they are the same.

   python3.7.4

   fin=open('D:\Python\Think Python\words.txt')

   def build_list_append(file):
       word_list=[]
       for line in fin:
           word=line.strip()
           word_list.append(word)
       return word_list

   def test1(worklist1=build_list_append(fin)):
       print("This is test1,It will return a non-empty list")
       print(len(worklist1))

   def test2(worklist2=build_list_append(fin)):
       print("This is test2,It will return an empty list")
       print(len(worklist2))


答:
If the ImportantValue is always the second to last element, you could do the following

var stringParts = path.Split(new[]{ "->" }, StringSplitOptions.None);
if(stringParts.Length >= 2)
{
    var importantValue = stringParts[stringParts.Length - 2];
}
else
{
    throw new ArgumentException("Input did not match the expected value");
}
```

<p>You could also use <code>IEnumerable</code> extensions</p>

```var importantValue = path.Split(new[]{ "->" }, StringSplitOptions.None)
                         .Reverse() // reverse the enumerable
                         .Skip(1)   // discard "val"
                         .First();  // return the "ImportantValue"
```

Title: C# - Finding a string between two strings

Body:
If the ImportantValue is always the second to last element, you could do the following

var stringParts = path.Split(new[]{ "->" }, StringSplitOptions.None);
if(stringParts.Length >= 2)
{
    var importantValue = stringParts[stringParts.Length - 2];
}
else
{
    throw new ArgumentException("Input did not match the expected value");
}

You could also use IEnumerable extensions

var importantValue = path.Split(new[]{ "->" }, StringSplitOptions.None)
                         .Reverse() // reverse the enumerable
                         .Skip(1)   // discard "val"
                         .First();  // return the "ImportantValue"