问:
Helm Rocket.Chat: Error in /app/bundle/programs/server/node_modules/fibers/future.js
I just created a kubernetes cluster in AWS. What I am trying to do is create multiple deployments of Rocket.Chat for each customer (each customer needs their own server). I'm using helm to deploy Rocket.Chat (using the official chart). When I make my first deployment, I'm able to port-forward it to localhost and see the Rocket.Chat server just fine. When I make a second deployment, however, the pods go into a crashloopbackoff state. Even after deleting all the deployments and trying to start from scratch, I still get the same errors. The errors I get are:

```<code>/app/bundle/programs/server/node_modules/fibers/future.js:280
                                                throw(ex);
                                                ^

MongoParseError: Unescaped slash in userinfo section
    at parseConnectionString (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/uri_parser.js:538:21)
    at connect (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb/lib/operations/mongo_client_ops.js:195:3)
    at connectOp (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb/lib/operations/mongo_client_ops.js:284:3)
    at executeOperation (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb/lib/utils.js:416:24)
    at MongoClient.connect (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb/lib/mongo_client.js:175:10)
    at Function.MongoClient.connect (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb/lib/mongo_client.js:341:22)
    at new MongoConnection (packages/mongo/mongo_driver.js:177:11)
    at new MongoInternals.RemoteCollectionDriver (packages/mongo/remote_collection_driver.js:4:16)
    at Object.<anonymous> (packages/mongo/remote_collection_driver.js:38:10)
    at Object.defaultRemoteCollectionDriver (packages/underscore.js:784:19)
    at new Collection (packages/mongo/collection.js:97:40)
    at new AccountsCommon (packages/accounts-base/accounts_common.js:23:18)
    at new AccountsServer (packages/accounts-base/accounts_server.js:23:5)
    at packages/accounts-base/server_main.js:7:12
    at server_main.js (packages/accounts-base/server_main.js:19:1)
    at fileEvaluate (packages/modules-runtime.js:336:7)
</code>```

and

```<code>/app/bundle/programs/server/node_modules/fibers/future.js:313
                                                throw(ex);
                                                ^

MongoNetworkError: failed to connect to server [fc-mongodb:27017] on first connect [MongoError: Authentication failed.]
    at Pool.<anonymous> (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/topologies/server.js:431:11)
    at emitOne (events.js:116:13)
    at Pool.emit (events.js:211:7)
    at connect (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/connection/pool.js:557:14)
    at callback (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/connection/connect.js:109:5)
    at provider.auth.err (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/connection/connect.js:352:21)
    at _authenticateSingleConnection (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/auth/auth_provider.js:66:11)
    at sendAuthCommand (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/auth/scram.js:215:18)
    at Connection.messageHandler (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/connection/connect.js:334:5)
    at emitTwo (events.js:126:13)
    at Connection.emit (events.js:214:7)
    at processMessage (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/connection/connection.js:364:10)
    at Socket.<anonymous> (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/connection/connection.js:533:15)
    at emitOne (events.js:116:13)
    at Socket.emit (events.js:211:7)
    at addChunk (_stream_readable.js:263:12)
</code>```

I do notice, however, that when I run helm delete fc that the persistent volumes stay in place and it seems to take forever to delete them (I have always cancelled deleting so I'm not sure if they would ever be able to). I'm guessing that the fact that the persistent volumes are still in place is the reason for why "starting from scratch" doesn't work after I've already deployed. Anyway, has anyone seen these errors before in a similar context? What did you do to fix it?

答:
The issue is with the suggested way to generate passwords on rocket chat's helm chart. They tell you to run:

```<code>helm install stable/rocketchat --set mongodb.mongodbPassword=$(echo -n $(openssl rand -base64 32)),mongodb.mongodbRootPassword=$(echo -n $(openssl rand -base64 32))
</code>```

I was able to fix this error when I switched from using openssl like the documentation recommends to pwgen. I'm the way the documentation recommended to create passwords added some illegal characters. This is what I ran instead:

```<code>helm install <installation-name> stable/rocketchat --set mongodb.mongodbPassword="$(pwgen 20 1)",mongodb.mongodbRootPassword="$(pwgen 20 1)" -f values.yaml
</code>```

And it worked!

Body:
I just created a kubernetes cluster in AWS. What I am trying to do is create multiple deployments of Rocket.Chat for each customer (each customer needs their own server). I'm using helm to deploy Rocket.Chat (using the official chart). When I make my first deployment, I'm able to port-forward it to localhost and see the Rocket.Chat server just fine. When I make a second deployment, however, the pods go into a crashloopbackoff state. Even after deleting all the deployments and trying to start from scratch, I still get the same errors. The errors I get are:

/app/bundle/programs/server/node_modules/fibers/future.js:280
                                                throw(ex);
                                                ^

MongoParseError: Unescaped slash in userinfo section
    at parseConnectionString (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/uri_parser.js:538:21)
    at connect (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb/lib/operations/mongo_client_ops.js:195:3)
    at connectOp (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb/lib/operations/mongo_client_ops.js:284:3)
    at executeOperation (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb/lib/utils.js:416:24)
    at MongoClient.connect (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb/lib/mongo_client.js:175:10)
    at Function.MongoClient.connect (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb/lib/mongo_client.js:341:22)
    at new MongoConnection (packages/mongo/mongo_driver.js:177:11)
    at new MongoInternals.RemoteCollectionDriver (packages/mongo/remote_collection_driver.js:4:16)
    at Object.<anonymous> (packages/mongo/remote_collection_driver.js:38:10)
    at Object.defaultRemoteCollectionDriver (packages/underscore.js:784:19)
    at new Collection (packages/mongo/collection.js:97:40)
    at new AccountsCommon (packages/accounts-base/accounts_common.js:23:18)
    at new AccountsServer (packages/accounts-base/accounts_server.js:23:5)
    at packages/accounts-base/server_main.js:7:12
    at server_main.js (packages/accounts-base/server_main.js:19:1)
    at fileEvaluate (packages/modules-runtime.js:336:7)

and

/app/bundle/programs/server/node_modules/fibers/future.js:313
                                                throw(ex);
                                                ^

MongoNetworkError: failed to connect to server [fc-mongodb:27017] on first connect [MongoError: Authentication failed.]
    at Pool.<anonymous> (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/topologies/server.js:431:11)
    at emitOne (events.js:116:13)
    at Pool.emit (events.js:211:7)
    at connect (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/connection/pool.js:557:14)
    at callback (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/connection/connect.js:109:5)
    at provider.auth.err (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/connection/connect.js:352:21)
    at _authenticateSingleConnection (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/auth/auth_provider.js:66:11)
    at sendAuthCommand (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/auth/scram.js:215:18)
    at Connection.messageHandler (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/connection/connect.js:334:5)
    at emitTwo (events.js:126:13)
    at Connection.emit (events.js:214:7)
    at processMessage (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/connection/connection.js:364:10)
    at Socket.<anonymous> (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/connection/connection.js:533:15)
    at emitOne (events.js:116:13)
    at Socket.emit (events.js:211:7)
    at addChunk (_stream_readable.js:263:12)

I do notice, however, that when I run helm delete fc that the persistent volumes stay in place and it seems to take forever to delete them (I have always cancelled deleting so I'm not sure if they would ever be able to). I'm guessing that the fact that the persistent volumes are still in place is the reason for why "starting from scratch" doesn't work after I've already deployed. Anyway, has anyone seen these errors before in a similar context? What did you do to fix it?

Body:
The issue is with the suggested way to generate passwords on rocket chat's helm chart. They tell you to run:

helm install stable/rocketchat --set mongodb.mongodbPassword=$(echo -n $(openssl rand -base64 32)),mongodb.mongodbRootPassword=$(echo -n $(openssl rand -base64 32))

I was able to fix this error when I switched from using openssl like the documentation recommends to pwgen. I'm the way the documentation recommended to create passwords added some illegal characters. This is what I ran instead:

helm install <installation-name> stable/rocketchat --set mongodb.mongodbPassword="$(pwgen 20 1)",mongodb.mongodbRootPassword="$(pwgen 20 1)" -f values.yaml

And it worked!


来源: stackexchange

问:
Is there any sed like utility for cmd.exe?
I want to programmatically edit file content using windows command line (cmd.exe). In *nix there is sed for this tasks. Are there any useful native equivalents (cmd or ps) in windows?</p>

答:
Today powershell saved me.

For grep there is:

```<code>get-content somefile.txt | where { $_ -match "expression"}
</code>```

or

```<code>select-string somefile.txt -pattern "expression"
</code>```

and for sed there is:

```<code>get-content somefile.txt | %{$_ -replace "expression","replace"}
</code>```

For more detail about replace PowerShell function see this Microsoft article.

OwnerDisplayName: Jakub Šturc

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Jakub Šturc

Body:
Today powershell saved me.

For grep there is:

get-content somefile.txt | where { $_ -match "expression"}

or

select-string somefile.txt -pattern "expression"

and for sed there is:

get-content somefile.txt | %{$_ -replace "expression","replace"}

For more detail about replace PowerShell function see this Microsoft article.


问:
Create dynamic library using MSVC command line
I've read a lot of posts and yet I don't understand how to create a simple dynamic library on windows using MSVC in command line. What I'm doing is:

1º) Code the DLL

dynamic.h

#pragma once

__declspec(dllexport) void HelloWorld();
```

<p><strong>dynamic.c</strong></p>

<pre class="lang-c prettyprint-override"><code>#include "dynamic.h"
#include <stdio.h>

void HelloWorld(){
    printf("Hello World");
}
</code>```

2º) Compile it

```<code>cl /LD dynamic.c
</code>```

(it compiles correctly and without errors generating dynamic.dll and dynamic.lib)

3º) Try to test it

main.c

#include<stdio.h>
#include"dynamic.h"
int main(){

    HelloWorld();

    return 0;
}
```

```cl main.c dynamic.lib
```

<p><strong>ERROR</strong> (by cl.exe x64)</p>

```main.cpp
Microsoft (R) Incremental Linker Version 14.16.27034.0
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:main.exe
main.obj
.\dynamic.lib
main.obj : error LNK2019: unresolved external symbol "void __cdecl HelloWorld(void)" (?HelloWorld@@YAXXZ) referred in main
main.exe : fatal error LNK1120: unresolved externals
```

Please teach me how dynamic libraries compilation really work because I can't understand

答:
In main.c it needs to see the function declaration like this:

```<code>__declspec(dllimport) void HelloWorld();
</code>```

So you cannot use the same dynamic.h as you currently have, for both building the DLL and building main.c  .

Normally people will use a preprocessor setup so the same header file has a different declspec depending who is including it, for example:

```<code>// dynamic.h
#ifndef DLL_FUNCTION
#define DLL_FUNCTION __declspec(dllimport)
#endif

DLL_FUNCTION void HelloWorld();
</code>```

dynamic.c (in the DLL):

```<code>#define DLL_FUNCTION __declspec(dllexport)
#include "dynamic.h"
</code>```

Body:
I've read a lot of posts and yet I don't understand how to create a simple dynamic library on windows using MSVC in command line. What I'm doing is:

1º) Code the DLL

dynamic.h

#pragma once

__declspec(dllexport) void HelloWorld();

dynamic.c

#include "dynamic.h"
#include <stdio.h>

void HelloWorld(){
    printf("Hello World");
}

2º) Compile it

cl /LD dynamic.c

(it compiles correctly and without errors generating dynamic.dll and dynamic.lib)

3º) Try to test it

main.c

#include<stdio.h>
#include"dynamic.h"
int main(){

    HelloWorld();

    return 0;
}

cl main.c dynamic.lib

ERROR (by cl.exe x64)

main.cpp
Microsoft (R) Incremental Linker Version 14.16.27034.0
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:main.exe
main.obj
.\dynamic.lib
main.obj : error LNK2019: unresolved external symbol "void __cdecl HelloWorld(void)" (?HelloWorld@@YAXXZ) referred in main
main.exe : fatal error LNK1120: unresolved externals

Please teach me how dynamic libraries compilation really work because I can't understand

Body:
In main.c it needs to see the function declaration like this:

__declspec(dllimport) void HelloWorld();

So you cannot use the same dynamic.h as you currently have, for both building the DLL and building main.c  .

Normally people will use a preprocessor setup so the same header file has a different declspec depending who is including it, for example:

// dynamic.h
#ifndef DLL_FUNCTION
#define DLL_FUNCTION __declspec(dllimport)
#endif

DLL_FUNCTION void HelloWorld();

dynamic.c (in the DLL):

#define DLL_FUNCTION __declspec(dllexport)
#include "dynamic.h"


问:
ODBC-ODBC bridge
I have a mysql db running on one linux server.
With an odbc connection for a web server on another linux box.

I would like to be able to use the/an odbc connection to the web server, to access mysql. This would be for an external app that is running on client machines.

I have done some googling, and there might be something called an ODBC-ODBC bridge.

I would like to just get a correct direction to go. So I don't head in the wrong direction.

If someone could point me at a specific bridge software. Or a tutorial. Or if this is even possible, and bridge is the correct thing to look for.  etc...

thanks

答: your webserver should have odbc connection to connect to MySQL database, and yes that you have. and when you do have that connectivity, I guess you won't really need your clients to connect to the MySQL database directly. because whatever query you want to run (an insert, or query operation), you just submit it to the webserver and it'll give fetch the query results for you. </p>

ContentLicense: CC BY-SA 3.0

Title: ODBC-ODBC bridge


问:
How to return matches and non matches when comparing two ranges/arrays
I'm attempting to return a count of the total number of matching and non-matching entries in a set of two ranges.

I'm trying to avoid looping over the array twice like this:

```<code>#expected output:
#inside: 421 | outside: 55

constant_range = 240..960
sample_range   = 540..1015
sample_range_a = sample_range.to_a

def generate_range
  inside = sample_range_a.select { |val| constant_range.include?(val) }.count
  outside = sample_range_a.select { |val| !constant_range.include?(val) }.count
end

# I was thinking of a counter, but thought that would be even more ineffective
def generate_range
  a = 0
  b = 0
  sample_range_a.select { |val| constant_range.include?(val) ? a++ : b++ }
end
</code>```

答:
I don't know if this is entirely your case, but if they're always number ranges with an interval of 1 and not any arbitrary array, the solution can be optimized to O(1), unlike the other methods using to_a that are at least O(n). In other words, if you have a BIG range, those array solutions would choke badly.

Assuming that you'll always use an ascending range of numbers with interval of 1, it means you can count them just by using size (count would be our enemy in this situation).

With that said, using simple math you can first check if the ranges may intersect, if not, just return 0. Otherwise, you can finally calculate the new range interval and get its size.

```<code>def range_intersection_count(x, y)
  return 0 if x.last < y.first || y.last < x.first
  ([x.begin, y.begin].max..[x.max, y.max].min).size
end
</code>```

This will count the number of elements that intersect in two ranges in O(1). You can test this code with something like

```<code>range_intersection_count(5000000..10000000000, 3000..1000000000000)
</code>```

and then try the same input with the other methods and watch your program hang.

The final solution would look something like this:

```<code>constant_range = (240..960)
sample_range   = (540..1015)

inside_count   = range_intersection_count(constant_range, sample_range) # = 421
outside_count  = sample_range.size - inside_count                       # = 55
</code>```

Body:
I'm attempting to return a count of the total number of matching and non-matching entries in a set of two ranges.

I'm trying to avoid looping over the array twice like this:

#expected output:
#inside: 421 | outside: 55

constant_range = 240..960
sample_range   = 540..1015
sample_range_a = sample_range.to_a

def generate_range
  inside = sample_range_a.select { |val| constant_range.include?(val) }.count
  outside = sample_range_a.select { |val| !constant_range.include?(val) }.count
end

# I was thinking of a counter, but thought that would be even more ineffective
def generate_range
  a = 0
  b = 0
  sample_range_a.select { |val| constant_range.include?(val) ? a++ : b++ }
end

Body:
I don't know if this is entirely your case, but if they're always number ranges with an interval of 1 and not any arbitrary array, the solution can be optimized to O(1), unlike the other methods using to_a that are at least O(n). In other words, if you have a BIG range, those array solutions would choke badly.

Assuming that you'll always use an ascending range of numbers with interval of 1, it means you can count them just by using size (count would be our enemy in this situation).

With that said, using simple math you can first check if the ranges may intersect, if not, just return 0. Otherwise, you can finally calculate the new range interval and get its size.

def range_intersection_count(x, y)
  return 0 if x.last < y.first || y.last < x.first
  ([x.begin, y.begin].max..[x.max, y.max].min).size
end

This will count the number of elements that intersect in two ranges in O(1). You can test this code with something like

range_intersection_count(5000000..10000000000, 3000..1000000000000)

and then try the same input with the other methods and watch your program hang.

The final solution would look something like this:

constant_range = (240..960)
sample_range   = (540..1015)

inside_count   = range_intersection_count(constant_range, sample_range) # = 421
outside_count  = sample_range.size - inside_count                       # = 55


问:
How to reference function property within an inner scope
Is it possible do this kind of assignment in Kotlin somehow?

```<code>data class MyData(var v: Int?)

fun myFunction(v: Int) {
    val myData = MyData(null).apply {
        v = @myFunction.v   //does not work
    }

}
</code>```

PS: the example is unreal is just for the purpose of demonstrating the idea

答: this.v = v instead of v = @myFunction.v

Body:
Is it possible do this kind of assignment in Kotlin somehow?

data class MyData(var v: Int?)

fun myFunction(v: Int) {
    val myData = MyData(null).apply {
        v = @myFunction.v   //does not work
    }

}

PS: the example is unreal is just for the purpose of demonstrating the idea

Body: this.v = v instead of v = @myFunction.v


问:
How do I change the UIPageViewController from WITHIN one of the UIViewControllers that is part of the UIPageViewController?
I have been trying to figure this out for hours, and I must be misunderstanding how UIPageViewController works.

I have 5 setup screens (separate view controllers that are loaded into the UIPageViewController) that I can swipe right + left to see.

BUT! I want to be able to programmatically show the next view controller in line after they dismiss an alert on one of those view controllers.

And so far, the only solution that I've found that gets close, is this solution here ( https://github.com/jeffaburt/UIPageViewController-Post ) that allows a "next" button, but the button isn't on the view controller that's showing, it's on the root view controller that holds the UIPageViewController.

I have the UIPageViewController set up to show 5 different view controllers, with this code.

```<code>private(set) lazy var orderedViewControllers: [UIViewController] = {
    return [self.newColoredViewController("setup1"),
            self.newColoredViewController("setup2"),
            self.newColoredViewController("setup3"),
            self.newColoredViewController("setup4"),
            self.newColoredViewController("setup5")]
}()
</code>```

Then the newColoredViewController function does this:

```<code>private func newColoredViewController(color: String) -> UIViewController {
    return UIStoryboard(name: "Main", bundle: nil) .
        instantiateViewControllerWithIdentifier("\(color)")
}
</code>```

and here's my viewDidLoad:

```<code> override func viewDidLoad() {
    super.viewDidLoad()

    dataSource = self

    if let SetupViewController = orderedViewControllers.first {
        setViewControllers([SetupViewController],
                           direction: .Forward,
                           animated: true,
                           completion: nil)
    }

}
</code>```

I must be missing some fundamental understanding, because I've tried so many different ways to change the page programmatically, and nothing happens.

I've tried doing this, but it does nothing:

```<code>setViewControllers([orderedViewControllers[3]],
                           direction: .Forward,
                           animated: true,
                           completion: nil)
</code>```

I've tried doing this, but it does nothing:

```<code>func scrollToNextViewController() {
    if let visibleViewController = viewControllers?.first,
        let nextViewController = pageViewController(self,
                                                    viewControllerAfterViewController: visibleViewController) {
        scrollToViewController(nextViewController)
    }
}
</code>```

Please point me in the right direction!! I can research all day and usually can figure it out thanks to previous stackoverflow questions that are already answered, but here I'm stumped.

Thanks in advance!!

答:
First, we need to access parent class as PageViewController

Swift 5 :

```<code>   if let controller = self.parent as? yourPageViewController
          controller.goToNextPage()
   }
</code>```

PageViewController Extension can be used like that

```<code>extension UIPageViewController {

    func goToNextPage(animated: Bool = true) {
        guard let currentViewController = self.viewControllers?.first else { return }
        guard let nextViewController = dataSource?.pageViewController(self, viewControllerAfter: currentViewController) else { return }
        setViewControllers([nextViewController], direction: .forward, animated: animated, completion: nil)
    }

    func goToPreviousPage(animated: Bool = true) {
        guard let currentViewController = self.viewControllers?.first else { return }
        guard let previousViewController = dataSource?.pageViewController(self, viewControllerBefore: currentViewController) else { return }
        setViewControllers([previousViewController], direction: .reverse, animated: animated, completion: nil)
    }
}
</code>```

Body:
I have been trying to figure this out for hours, and I must be misunderstanding how UIPageViewController works.

I have 5 setup screens (separate view controllers that are loaded into the UIPageViewController) that I can swipe right + left to see.

BUT! I want to be able to programmatically show the next view controller in line after they dismiss an alert on one of those view controllers.

And so far, the only solution that I've found that gets close, is this solution here ( https://github.com/jeffaburt/UIPageViewController-Post ) that allows a "next" button, but the button isn't on the view controller that's showing, it's on the root view controller that holds the UIPageViewController.

I have the UIPageViewController set up to show 5 different view controllers, with this code.

private(set) lazy var orderedViewControllers: [UIViewController] = {
    return [self.newColoredViewController("setup1"),
            self.newColoredViewController("setup2"),
            self.newColoredViewController("setup3"),
            self.newColoredViewController("setup4"),
            self.newColoredViewController("setup5")]
}()

Then the newColoredViewController function does this:

private func newColoredViewController(color: String) -> UIViewController {
    return UIStoryboard(name: "Main", bundle: nil) .
        instantiateViewControllerWithIdentifier("\(color)")
}

and here's my viewDidLoad:

 override func viewDidLoad() {
    super.viewDidLoad()

    dataSource = self

    if let SetupViewController = orderedViewControllers.first {
        setViewControllers([SetupViewController],
                           direction: .Forward,
                           animated: true,
                           completion: nil)
    }

}

I must be missing some fundamental understanding, because I've tried so many different ways to change the page programmatically, and nothing happens.

I've tried doing this, but it does nothing:

setViewControllers([orderedViewControllers[3]],
                           direction: .Forward,
                           animated: true,
                           completion: nil)

I've tried doing this, but it does nothing:

func scrollToNextViewController() {
    if let visibleViewController = viewControllers?.first,
        let nextViewController = pageViewController(self,
                                                    viewControllerAfterViewController: visibleViewController) {
        scrollToViewController(nextViewController)
    }
}

Please point me in the right direction!! I can research all day and usually can figure it out thanks to previous stackoverflow questions that are already answered, but here I'm stumped.

Thanks in advance!!

Body:
First, we need to access parent class as PageViewController

Swift 5 :

   if let controller = self.parent as? yourPageViewController
          controller.goToNextPage()
   }

PageViewController Extension can be used like that

extension UIPageViewController {

    func goToNextPage(animated: Bool = true) {
        guard let currentViewController = self.viewControllers?.first else { return }
        guard let nextViewController = dataSource?.pageViewController(self, viewControllerAfter: currentViewController) else { return }
        setViewControllers([nextViewController], direction: .forward, animated: animated, completion: nil)
    }

    func goToPreviousPage(animated: Bool = true) {
        guard let currentViewController = self.viewControllers?.first else { return }
        guard let previousViewController = dataSource?.pageViewController(self, viewControllerBefore: currentViewController) else { return }
        setViewControllers([previousViewController], direction: .reverse, animated: animated, completion: nil)
    }
}


问:
React Click Counter: Updating State of just one element
This should be pretty simple, but I can't figure out how to do it.

I have a component with multiple buttons, each with a "count" value, set with state. When a user clicks, the count goes up.

Right now, when I click one of the buttons, both counters change. How can I make it so only the div that was clicked updates, using the same state?

Edit: I don't want to have different counts, as I'd like for this component to render buttons dynamically. What if I don't know how many buttons I'll have at first?

```<code>class Block extends React.Component {
  state = {
    count: 0
  };

  handleClick = e => {
    const count = this.state.count;
    this.setState({ count: count + 1 });
  };

  render() {
    return (
      <div>
        <button className="block" onClick={this.handleClick}>
          <div className="counter">{this.state.count}</div>
        </button>
        <button className="block" onClick={this.handleClick}>
          <div className="counter">{this.state.count}</div>
        </button>
      </div>
    );
  }
}
</code>```

答:
This is more of an issue of learning how to think in react.

If you need to be able to reuse a piece of functionality like a counter, you can make it its own component and have it manage its own state. Then you can reuse it wherever you need.

Here's an example:

class Counter extends React.Component {
  state = {
    count: 0
  };

  handleClick = () => {
    // Use updater function when new state is derived from old
    this.setState(prev => ({ count: prev.count + 1 }));
  };

  render() {
    return (
      <button className="block" onClick={this.handleClick}>

{this.state.count}

      </button>
    );
  }
}

// Now you can use it dynamically like this:
class Block extends React.Component {
  render() {
    return (

There are 4 counter component instances that each manage their own state.

        {[1,2,3,4].map(v => <Counter />)}

    );
  }
}

ReactDOM.render(<Block />, document.getElementById('root'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div></code>```

Body:
This should be pretty simple, but I can't figure out how to do it.

I have a component with multiple buttons, each with a "count" value, set with state. When a user clicks, the count goes up.

Right now, when I click one of the buttons, both counters change. How can I make it so only the div that was clicked updates, using the same state?

Edit: I don't want to have different counts, as I'd like for this component to render buttons dynamically. What if I don't know how many buttons I'll have at first?

class Block extends React.Component {
  state = {
    count: 0
  };

  handleClick = e => {
    const count = this.state.count;
    this.setState({ count: count + 1 });
  };

  render() {
    return (

        <button className="block" onClick={this.handleClick}>

{this.state.count}

        </button>
        <button className="block" onClick={this.handleClick}>

{this.state.count}

        </button>

    );
  }
}

Body:
This is more of an issue of learning how to think in react.

If you need to be able to reuse a piece of functionality like a counter, you can make it its own component and have it manage its own state. Then you can reuse it wherever you need.

Here's an example:

class Counter extends React.Component {
  state = {
    count: 0
  };

  handleClick = () => {
    // Use updater function when new state is derived from old
    this.setState(prev => ({ count: prev.count + 1 }));
  };

  render() {
    return (
      <button className="block" onClick={this.handleClick}>
        <div className="counter">{this.state.count}</div>
      </button>
    );
  }
}

// Now you can use it dynamically like this:
class Block extends React.Component {
  render() {
    return (
      <div>
        <div>There are 4 counter component instances that each manage their own state.</div>
        {[1,2,3,4].map(v => <Counter />)}
      </div>
    );
  }
}

ReactDOM.render(<Block />, document.getElementById('root'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>


问:
Split Dataframe with some conditions
Goal:

I would like to split my dataframe into 3 multiple dataframes.
My problem is, I don't know how I can get the dataframes with the more similar sum of "value" column for each one

Here is my current Code:

```<code>import pandas as pd
import math

splitter = 3

df = pd.read_csv('account.csv')
q_rows = df.shape[0]                                # Number of rows
q_rows_x_dataframe = math.ceil(q_rows / splitter)   # Quantity of rows for splitter

for index, row in df.iterrows():
    row.shift(q_rows_x_dataframe + 1)

>>> df
   network  value
0        A   1400
1        B   1300
2        C   1200
3        D   1100
4        E   1000
5        F    900
6        G    800
7        H    700
8        I    600
9        J    500
10       K    400
11       L    300
12       M    200
13       N    100
</code>```

This is my desired output:

```<code>A   1400
D   1100
G   800
J   500
M   200

B   1300
E   1000
H   700
K   400
N   100

C   1200
F   900
I   600
L   300
</code>```

答:
Use this to create a dictionary of dataframes:

```<code>splitter = 3
dict(tuple(df.groupby(df.index % splitter)))
</code>```

Output:

```<code>{0:    network  value
 0        A   1400
 3        D   1100
 6        G    800
 9        J    500
 12       M    200, 1:    network  value
 1        B   1300
 4        E   1000
 7        H    700
 10       K    400
 13       N    100, 2:    network  value
 2        C   1200
 5        F    900
 8        I    600
 11       L    300}
</code>```

Title: Split Dataframe with some conditions

Body:
Goal:

I would like to split my dataframe into 3 multiple dataframes.
My problem is, I don't know how I can get the dataframes with the more similar sum of "value" column for each one

Here is my current Code:

import pandas as pd
import math

splitter = 3

df = pd.read_csv('account.csv')
q_rows = df.shape[0]                                # Number of rows
q_rows_x_dataframe = math.ceil(q_rows / splitter)   # Quantity of rows for splitter

for index, row in df.iterrows():
    row.shift(q_rows_x_dataframe + 1)

>>> df
   network  value
0        A   1400
1        B   1300
2        C   1200
3        D   1100
4        E   1000
5        F    900
6        G    800
7        H    700
8        I    600
9        J    500
10       K    400
11       L    300
12       M    200
13       N    100

This is my desired output:

A   1400
D   1100
G   800
J   500
M   200

B   1300
E   1000
H   700
K   400
N   100

C   1200
F   900
I   600
L   300

Body:
Use this to create a dictionary of dataframes:

splitter = 3
dict(tuple(df.groupby(df.index % splitter)))

Output:

{0:    network  value
 0        A   1400
 3        D   1100
 6        G    800
 9        J    500
 12       M    200, 1:    network  value
 1        B   1300
 4        E   1000
 7        H    700
 10       K    400
 13       N    100, 2:    network  value
 2        C   1200
 5        F    900
 8        I    600
 11       L    300}


问:
Render list - React - Javascript
I'm currently trying to render state

I see a few errors with declaring variables within the map loop.

Here is my attempt so far, Any help is welcomed

```<code>import React from "react";
import axios from "axios";

const transformHumanReadableDateToMessages = date => {
  let d = new Date(date);
  const days = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday"
  ];
  return {
    DayOfTheWeek: d.getDate(),
    Month: d.getMonth(),
    Day: days[d.getDay()],
    YearAtTime: d.getFullYear()
  };
};

export default class App extends React.Component {
  state = {
    messages: []
  };

  componentDidMount() {

    axios.get(`https://api.myjson.com/bins/10xva4`).then(res => {
      let result = res.data["messages"];
          result = Array.from(new Set(result.map(e => JSON.stringify(e))));
          result.reduce((accu, curr) => {
           curr.date = transformHumanReadableDateToMessages(curr["sentAt"]);
            accu.push(curr)
            return accu;
          }, []);

      this.setState({
        messages: result
      });
    });
  }

  render() {
return (
  <>
    { this.state.messages.map(message =>
       let d = new Date(date);
      const days = [
        "Sunday",
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
        "Saturday"
      ];
     <div className="container">
     <p>{message.content}<p/>
     <p>{message.senderUuid}</p>
     <p>DayOfTheWeek: {d.getDate()}
     <p>Month: {d.getMonth()}</p>
     <p>Day: {days[d.getDay()]}</p>
     <p>Year: {d.getFullYear()} </p>
     </div>
     )}
  </>
);
</code>```

}
    }

For example each element in the JSON that is returned looks like this:

```<code>{
  "sentAt":"2012-11-13T17:29:37.003Z",
  "uuid": "435453",
  "content": "1",
  "senderUuid": "2"
 }
</code>```

I want to make the date more readable then add it to the element for a output like this:

```<code>{
 "sentAt":"2012-11-13T17:29:37.003Z",
 "uuid": "435453",
 "content": "1",
 "senderUuid": "2",
 "DayOfTheWeek": 22,
  "Month": 4,
  "Day": 'Friday',
  "YearAtTime": 2015
 }
</code>```

答:
Its because you are using let and jsx interchangeably due your mismanagement of brackets. Since it was a mess, I rewrote it using codesandbox and React hooks.

https://codesandbox.io/s/trusting-nobel-vlo34

```<code>import React, { useState, useEffect } from "react";
import axios from "axios";
import "./styles.css";

const days = [
  "Sunday",
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday",
  "Saturday"
];
export default function App() {
  const [messages, setMessages] = useState([]);
  useEffect(() => {
    axios
      .get(`https://api.myjson.com/bins/10xva4`)
      .then(({ data: { messages } }) => setMessages(messages));
  }, []);
  const Display = messages.map(({ content, senderUuid, sentAt }, index) => {
    let d = new Date(sentAt);
    return (
      <div className="container" key={index}>
        <p>Content: {content}</p>
        <p>SenderUuid: {senderUuid}</p>
        <p>DayOfTheWeek: {d.getDate()}</p>
        <p>Month: {d.getMonth()}</p>
        <p>Day: {days[d.getDay()]}</p>
        <p>Year: {d.getFullYear()}</p>
      </div>
    );
  });
  // console.log({ messages });
  return <div className="App">{Display}</div>;
}
</code>```

Title: Render list - React - Javascript

Body:
I'm currently trying to render state

I see a few errors with declaring variables within the map loop.

Here is my attempt so far, Any help is welcomed

import React from "react";
import axios from "axios";

const transformHumanReadableDateToMessages = date => {
  let d = new Date(date);
  const days = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday"
  ];
  return {
    DayOfTheWeek: d.getDate(),
    Month: d.getMonth(),
    Day: days[d.getDay()],
    YearAtTime: d.getFullYear()
  };
};

export default class App extends React.Component {
  state = {
    messages: []
  };

  componentDidMount() {

    axios.get(`https://api.myjson.com/bins/10xva4`).then(res => {
      let result = res.data["messages"];
          result = Array.from(new Set(result.map(e => JSON.stringify(e))));
          result.reduce((accu, curr) => {
           curr.date = transformHumanReadableDateToMessages(curr["sentAt"]);
            accu.push(curr)
            return accu;
          }, []);

      this.setState({
        messages: result
      });
    });
  }

  render() {
return (
  <>
    { this.state.messages.map(message =>
       let d = new Date(date);
      const days = [
        "Sunday",
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
        "Saturday"
      ];

{message.content}

{message.senderUuid}

DayOfTheWeek: {d.getDate()}

Month: {d.getMonth()}

Day: {days[d.getDay()]}

Year: {d.getFullYear()}

     )}
  </>
);

}
    }

For example each element in the JSON that is returned looks like this:

{
  "sentAt":"2012-11-13T17:29:37.003Z",
  "uuid": "435453",
  "content": "1",
  "senderUuid": "2"
 }

I want to make the date more readable then add it to the element for a output like this:

{
 "sentAt":"2012-11-13T17:29:37.003Z",
 "uuid": "435453",
 "content": "1",
 "senderUuid": "2",
 "DayOfTheWeek": 22,
  "Month": 4,
  "Day": 'Friday',
  "YearAtTime": 2015
 }

Body:
Its because you are using let and jsx interchangeably due your mismanagement of brackets. Since it was a mess, I rewrote it using codesandbox and React hooks.

https://codesandbox.io/s/trusting-nobel-vlo34

import React, { useState, useEffect } from "react";
import axios from "axios";
import "./styles.css";

const days = [
  "Sunday",
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday",
  "Saturday"
];
export default function App() {
  const [messages, setMessages] = useState([]);
  useEffect(() => {
    axios
      .get(`https://api.myjson.com/bins/10xva4`)
      .then(({ data: { messages } }) => setMessages(messages));
  }, []);
  const Display = messages.map(({ content, senderUuid, sentAt }, index) => {
    let d = new Date(sentAt);
    return (
      <div className="container" key={index}>
        <p>Content: {content}</p>
        <p>SenderUuid: {senderUuid}</p>
        <p>DayOfTheWeek: {d.getDate()}</p>
        <p>Month: {d.getMonth()}</p>
        <p>Day: {days[d.getDay()]}</p>
        <p>Year: {d.getFullYear()}</p>
      </div>
    );
  });
  // console.log({ messages });
  return <div className="App">{Display}</div>;
}


问:
Using PySpark to efficiently combine many small csv files (130,000 with 2 columns in each) into one large frame
This is another follow up to an earlier question I posted How can I merge these many csv files (around 130,000) using PySpark into one large dataset efficiently?

I have the following dataset https://fred.stlouisfed.org/categories/32263/downloaddata/INTRNTL_csv_2.zip

In it, there's a list of files (around 130,000). In the main directory with their sub-directories listed, so in there the first cell might be A/AAAAA, and the file would be located at /data/A/AAAAA.csv

The files are all with a similar format, the first column is called DATE and the second column is a series which are all named VALUE. So first of all, the VALUE column name needs to be renamed to the file name in each csv file. Second, the frames need to be full outer joined with each other with the DATE as the main index. Third, I want to save the file and be able to load and manipulate it. The file should be around N rows (number of dates) X 130,001 roughly.

I am trying to full outer join all the files into a single dataframe, I previously tried pandas but ran out of memory when trying to concat the list of files and someone recommended that I try to use PySpark instead.

In a previous post I was told that I could do this:

```<code>df = spark.read.csv("/kaggle/input/bf-csv-2/BF_csv_2/data/**/*.csv", "date DATE, value DOUBLE")
</code>```

But all the columns are named value and the frame just becomes two columns, the first column is DATE and second column is VALUE, it loads quite fast, around 38 seconds and around 3.8 million values by 2 columns, so I know that it's not doing the full outer join, it's appending the files row wise.

So I tried the following code:

```<code>import pandas as pd
import time
import os

from pyspark.sql import SparkSession

spark = SparkSession.builder.appName('spark-dataframe-demo').getOrCreate()
from pyspark.sql import *
from pyspark.sql.functions import col
from pyspark.sql import DataFrame
from pyspark.sql.types import *

filelist = pd.read_excel("/kaggle/input/list/BF_csv_2.xlsx") #list of filenames

firstname = min(filelist.File)
length = len(filelist.File)

dff = spark.read.csv(f"/kaggle/input/bf-csv-2/BF_csv_2/data/" + firstname, inferSchema = True, header = True).withColumnRenamed("VALUE",firstname) #read file and changes name of column to filename

for row in filelist.File.items():
    if row == firstname:
        continue

    print (row[1],length,end='', flush=True)
    df = spark.read.csv(f"/kaggle/input/bf-csv-2/BF_csv_2/data/" + row[1], inferSchema = True, header = True).withColumnRenamed("VALUE",row[1][:-4])
    #df = df.select(col("DATE").alias("DATE"),col("VALUE").alias(row[1][:-4]))

    dff = dff.join(df, ['DATE'], how='full')

    length -= 1

dff.write.save('/kaggle/working/whatever', format='parquet', mode='overwrite')
</code>```

So to test it, I try to load the the df.show() function after 3 columns are merged and it's quite fast. But, when I try around 25 columns, it takes around 2 minutes. When I try 500 columns it's next to impossible.

I don't think I'm doing it right. The formatting and everything is correct. But why is it taking so long? How can I use PySpark properly? Are there any better libraries to achieve what I need?

答:
Spark doesn't do anything magical compared to other software. The strength of spark is parallel processing. Most of the times that means you can use multiple machines to do the work. If you are running spark locally you may have the same issues you did when using pandas.

That being said, there might be a way for you to run it locally using Spark because it can spill to disk under certain conditions and does not need to have everything in memory.

I'm not verse in PySpark, but the approach I'd take is:

load all the files using like you did /kaggle/input/bf-csv-2/BF_csv_2/data/**/*.csv

Use the function from pyspark.sql.functions import input_file_name that allows you to get the path for each record in your DF (df.select("date", "value", input_file_name().as("filename")) or similar)

Parse the path into a format that I'd like to have as a column (eg. extract filename)

the schema should look like date, value, filename at this step

use the PySpark equivalent of df.groupBy("date").pivot("filename").agg(first("value")). Note: I used first() because I think you have 1 or 0 records possible

Also try: setting the number of partitions to be equal to number of dates you got

If you want output as a single file, do not forget to repartition(1) before df.write. This step might be problematic depending on data size. You do not need to do this if you plan to keep using Spark for your work as you could load the data using the same approach as in step 1 (/new_result_data/*.csv)

Body:
This is another follow up to an earlier question I posted How can I merge these many csv files (around 130,000) using PySpark into one large dataset efficiently?

I have the following dataset https://fred.stlouisfed.org/categories/32263/downloaddata/INTRNTL_csv_2.zip

In it, there's a list of files (around 130,000). In the main directory with their sub-directories listed, so in there the first cell might be A/AAAAA, and the file would be located at /data/A/AAAAA.csv

The files are all with a similar format, the first column is called DATE and the second column is a series which are all named VALUE. So first of all, the VALUE column name needs to be renamed to the file name in each csv file. Second, the frames need to be full outer joined with each other with the DATE as the main index. Third, I want to save the file and be able to load and manipulate it. The file should be around N rows (number of dates) X 130,001 roughly.

I am trying to full outer join all the files into a single dataframe, I previously tried pandas but ran out of memory when trying to concat the list of files and someone recommended that I try to use PySpark instead.

In a previous post I was told that I could do this:

df = spark.read.csv("/kaggle/input/bf-csv-2/BF_csv_2/data/**/*.csv", "date DATE, value DOUBLE")

But all the columns are named value and the frame just becomes two columns, the first column is DATE and second column is VALUE, it loads quite fast, around 38 seconds and around 3.8 million values by 2 columns, so I know that it's not doing the full outer join, it's appending the files row wise.

So I tried the following code:

import pandas as pd
import time
import os

from pyspark.sql import SparkSession

spark = SparkSession.builder.appName('spark-dataframe-demo').getOrCreate()
from pyspark.sql import *
from pyspark.sql.functions import col
from pyspark.sql import DataFrame
from pyspark.sql.types import *

filelist = pd.read_excel("/kaggle/input/list/BF_csv_2.xlsx") #list of filenames

firstname = min(filelist.File)
length = len(filelist.File)

dff = spark.read.csv(f"/kaggle/input/bf-csv-2/BF_csv_2/data/" + firstname, inferSchema = True, header = True).withColumnRenamed("VALUE",firstname) #read file and changes name of column to filename

for row in filelist.File.items():
    if row == firstname:
        continue

    print (row[1],length,end='', flush=True)
    df = spark.read.csv(f"/kaggle/input/bf-csv-2/BF_csv_2/data/" + row[1], inferSchema = True, header = True).withColumnRenamed("VALUE",row[1][:-4])
    #df = df.select(col("DATE").alias("DATE"),col("VALUE").alias(row[1][:-4]))

    dff = dff.join(df, ['DATE'], how='full')

    length -= 1

dff.write.save('/kaggle/working/whatever', format='parquet', mode='overwrite')

So to test it, I try to load the the df.show() function after 3 columns are merged and it's quite fast. But, when I try around 25 columns, it takes around 2 minutes. When I try 500 columns it's next to impossible.

I don't think I'm doing it right. The formatting and everything is correct. But why is it taking so long? How can I use PySpark properly? Are there any better libraries to achieve what I need?


问:
NHibernate Restrictions.In with hundreds of value
Should I be concerned about IN expressions with hundreds of values in the array? For example:

```<code>myCriteria.Add(Restrictions.In("Id", myArrayOfHundredsOfItems);
</code>```

Which results in the sql:

```<code>select * from MyTable where Id in (1,2,3,4, ...etc .. 900)
</code>```

MSDN says "Including an extremely large number of values (many thousands) in an IN clause can consume resources and return errors 8623 or 8632."

OK, so 'many thousands' is out of the question. Is there any reason to avoid an array of maybe a few hundred item?

答:
There is another limit. The values in the IN clause are passed as single parameters. There is a limit of parameters. It is probably the same as for stored procedures which is 2100.

I have a similar situation where I pass a large amount of Guids. I split it up in several queries, each of them getting up to 1000 parameters. The queries are executed as multi criteria in a batch, so there is only a single database roundtrip.

Performance may suffer when using IN compared to joins. In my scenario I don't have any performance issues because of that. If you don't have that many parameters, it most probably won't be an issue for you.

By the way, getting objects by id could also be implemented by:

Get<Entit>(id), which requires a single query, but only when the entity isn't in the cache yet.

Load<Entity>(id), which creates a proxy if the entity isn't in cache and only loads in when accessing properties. It most probably makes us of batch-size and loads several instances at once (pre-fetching).

Unfortunately, there isn't a future-get.

Body:
Should I be concerned about IN expressions with hundreds of values in the array? For example:

myCriteria.Add(Restrictions.In("Id", myArrayOfHundredsOfItems);

Which results in the sql:

select * from MyTable where Id in (1,2,3,4, ...etc .. 900)

MSDN says "Including an extremely large number of values (many thousands) in an IN clause can consume resources and return errors 8623 or 8632."

OK, so 'many thousands' is out of the question. Is there any reason to avoid an array of maybe a few hundred item?


问:
How to display a div/element on mouse hover using external JavaScript?
My divs are nested so i understand i cant display an element if its already hidden. I want the information(p1 inside my html code)to display once the mouse hovers over another element(h1 in my html. I have already made my paragraph 1 style to none in JavaScript, now i need it to re-appear, i have tried the following code to attempt to make it re-appear document.getElementById("1").onmouseover.style.display = "block"; but with no success.

This is My HTML code, ignore the order im new to web dev lol

This is the code i have tried but it doesnt seem to work

This is the end result i want, the circled text on hover display the paragraph

答:
```<code> document.getByElementId("myH1").onmouseover = function(){
    displayH1("myP");
}
document.getByElementId("myH1").onmouseout = function(){
    displayH1("myP");
}

function displayH1(myId){
    if(document.getByElementId(myId).style.display == "block"){
        document.getByElementId(myId).style.display = "none";
    }else{
        document.getByElementId(myId).style.display = "block";
    }

}
</code>```

<p>This invokes a function that toggles the paragraph's style when the mouse enters and leaves the element. It assumes that you have an id on both your h1 and p tags, in my example myH1 and myP respectively. </p>

Body:
 document.getByElementId("myH1").onmouseover = function(){
    displayH1("myP");
}
document.getByElementId("myH1").onmouseout = function(){
    displayH1("myP");
}

function displayH1(myId){
    if(document.getByElementId(myId).style.display == "block"){
        document.getByElementId(myId).style.display = "none";
    }else{
        document.getByElementId(myId).style.display = "block";
    }

}

This invokes a function that toggles the paragraph's style when the mouse enters and leaves the element. It assumes that you have an id on both your h1 and p tags, in my example myH1 and myP respectively.


问:
How to get rid of this error message from Firebase?
I want to get rid of the following warning message apparently Firebase is sending to my console.

I've search for "firebase" in my console and got "690 results in 49 files."

I'm confused about why this is showing up and what I can do about it.

What, exactly, is triggering it? Is it possible to get rid of the warning message or not? If so, how, exactly?

It looks like you're using the development build of the Firebase JS SDK.
  When deploying Firebase apps to production, it is advisable to only import
  the individual SDK components you intend to use.

For the module builds, these are available in the following manner
  (replace  with the name of a component - i.e. auth, database, etc):

CommonJS Modules:
const firebase = require('firebase/app');
require('firebase/<PACKAGE>');

ES Modules:
import firebase from 'firebase/app';
import 'firebase/<PACKAGE>';

Typescript:
import * as firebase from 'firebase/app';
import 'firebase/<PACKAGE>';

答:
only import what you need

```<code>import Firebase from 'firebase/app' //firebase-app
import 'firebase/firestore' //
import { firebase } from 'firebase/storage' //firebase-storage
</code>```

Body:
only import what you need

import Firebase from 'firebase/app' //firebase-app
import 'firebase/firestore' //
import { firebase } from 'firebase/storage' //firebase-storage


问:
I can't get past a few do-while loops even though their conditions have not been met
I'm just doing an exercise where I'm supposed to be finding all even numbers between two certain integers. However, each time I enter any numbers I get held up on one of the first two do-while loops. I assume I'm making a simple error. Does anybody see what I'm doing wrong?
Thank you!

The input should be x and y, the output should be b. x must be smaller than y, and they both must be between 1-99 (I'll fix that, it should be 0-100.)

```<code>#include <iostream>

int main()
{
    int x, y, b;

    std::cout << "This program will show all even numbers between a certain range.\n\nEnter two integers >0 and <100. The first integer must be smaller than the second integer.\n ";
    std::cin >> x >> y;

    do
    {
        std::cout << "The first integer must be smaller than the second integer. Please enter two integers.\n ";
        std::cin >> x >> y;

    } while (x > y);

    do
    {
        std::cout << "The first smaller integer must be greater than 0, the second larger integer must be less than 100.\n ";
        std::cin >> x >> y;

    } while (((x < 0 || y > 100 || x > y)));

    b = x;

    if ((b % 2) == 0)
    {
        do
        {
            std::cout << b;
            b++;
        } while (b < y);
    }
}
</code>```

答:
You are telling the user that they entered wrong input and ask them the enter input again before you check the condition:

```<code>do
{
    std::cout<<"The first integer must be smaller than the second integer. Please enter two integers.\n";
    std::cin>>x>>y;

} while (x>y);
</code>```

Better would be to use a while loop:

```<code>int x = 0;   // important !! initialize your variables !! always !!
int y = 0;   // important !! initialize your variables !! always !!
while ( x > y)
{
    std::cout<<"The first integer must be smaller than the second integer. Please enter two integers.\n";
    std::cin>>x>>y;

}
</code>```

This will only ask the user to enter numbers again if the entered numbers do not fulfill the condition.

If it is a requirement to use a do-while you need to restructure you code a bit. Something along the line of:

```<code>// do not read any input from user before this loop
do {
   std::cout << "please enter two numbers x,y such that 0<x<y<100";
   std::cin >> x >> y;
} while ( x > y || x < 0 || y > 100);
</code>```

Note that I did not add any more validation than what you have in your code. Typically you should check if the user entered a number not something else.

Once you got that straight I hope you can also fix the final loop for the computation (Spoiler: You got the if and the loop inside out. You only check if x is even once.)

Body:
I'm just doing an exercise where I'm supposed to be finding all even numbers between two certain integers. However, each time I enter any numbers I get held up on one of the first two do-while loops. I assume I'm making a simple error. Does anybody see what I'm doing wrong?
Thank you!

The input should be x and y, the output should be b. x must be smaller than y, and they both must be between 1-99 (I'll fix that, it should be 0-100.)

#include <iostream>

int main()
{
    int x, y, b;

    std::cout << "This program will show all even numbers between a certain range.\n\nEnter two integers >0 and <100. The first integer must be smaller than the second integer.\n ";
    std::cin >> x >> y;

    do
    {
        std::cout << "The first integer must be smaller than the second integer. Please enter two integers.\n ";
        std::cin >> x >> y;

    } while (x > y);

    do
    {
        std::cout << "The first smaller integer must be greater than 0, the second larger integer must be less than 100.\n ";
        std::cin >> x >> y;

    } while (((x < 0 || y > 100 || x > y)));

    b = x;

    if ((b % 2) == 0)
    {
        do
        {
            std::cout << b;
            b++;
        } while (b < y);
    }
}

Body:
You are telling the user that they entered wrong input and ask them the enter input again before you check the condition:

do
{
    std::cout<<"The first integer must be smaller than the second integer. Please enter two integers.\n";
    std::cin>>x>>y;

} while (x>y);

Better would be to use a while loop:

int x = 0;   // important !! initialize your variables !! always !!
int y = 0;   // important !! initialize your variables !! always !!
while ( x > y)
{
    std::cout<<"The first integer must be smaller than the second integer. Please enter two integers.\n";
    std::cin>>x>>y;

}

This will only ask the user to enter numbers again if the entered numbers do not fulfill the condition.

If it is a requirement to use a do-while you need to restructure you code a bit. Something along the line of:

// do not read any input from user before this loop
do {
   std::cout << "please enter two numbers x,y such that 0<x<y<100";
   std::cin >> x >> y;
} while ( x > y || x < 0 || y > 100);

Note that I did not add any more validation than what you have in your code. Typically you should check if the user entered a number not something else.

Once you got that straight I hope you can also fix the final loop for the computation (Spoiler: You got the if and the loop inside out. You only check if x is even once.)


问:
How to get relative path of an exe in Java
I have a config class that references a chromedriver.exe file via a String path like so

```<code>public static final String CHROMEDRIVER_DIRECTORY = "C:\\Users\\asdf\\Desktop\\Testing\\drivers\\chromedriver.exe";
</code>```

That code is located in the src folder while the chromedriver.exe is located in a separate drivers folder. The project layout looks something like this.

Testing

src -> constants package -> config

drivers -> chromedriver.exe

How can I edit the string so that it can find the chromedriver without having to type the absolute path? Thanks

答: Try "drivers\\chromedriver.exe".</p>

Body:
I have a config class that references a chromedriver.exe file via a String path like so

public static final String CHROMEDRIVER_DIRECTORY = "C:\\Users\\asdf\\Desktop\\Testing\\drivers\\chromedriver.exe";

That code is located in the src folder while the chromedriver.exe is located in a separate drivers folder. The project layout looks something like this.

Testing

src -> constants package -> config

drivers -> chromedriver.exe

How can I edit the string so that it can find the chromedriver without having to type the absolute path? Thanks

Body: Try "drivers\\chromedriver.exe".


问:
How to find the longest chain of consecutively recurring character groupings in file
I'm new to this site (and programming) but would really appreciate some help with a challenge I'm having.

I'm trying to write a program to search through a provided long .txt file and look for instances where a particular grouping of characters is repeating consecutively, then calculate the highest example of that and compare it with another file (this isn't important right now).

So with a file with the following long line:

'dtcdtcdtcuiouiouiodtcdtcdtcdtcdtcuiouioiodtcdtc'

I would want to find the highest instance of 'dtc' repeated consecutively. At the start of the line, it does so three times. Then around the middle it does so four times. Then at the end it does so twice. So I would want my stored information to be 4.

I'm struggling to implement this, however. As I said, I am new and have been trying to search for the best way to achieve this. I have so far started to consider options like:

```<code>read = textfile.read()
counter = 0

for i in range(len(read)):
        if (read[i:i + 2]) == 'dtc':
           counter += 1
</code>```

But yeah, I'm struggling to figure out the best way to implement the required algorithm. If you could even point me in the right direction, I would be grateful.

Many thanks

答:
This should work:

```<code>read = "dtcdtcdtcuiouiouiodtcdtcdtcdtcdtcuiouioiodtcdtc"

maxIter=len(read)
maxCounter=0
i=0
counter = 0
while (1):
    if i==maxIter:
        break
    if(read[i:i+3]=="dtc"):
        counter+=1
        if counter>maxCounter:
            maxCounter=counter
        i+=3
    else:
        counter=0
        i+=1

</code>```

p.s. in your sample string, "dtc" is repeated 5 times in the middle

Body:
I'm new to this site (and programming) but would really appreciate some help with a challenge I'm having.

I'm trying to write a program to search through a provided long .txt file and look for instances where a particular grouping of characters is repeating consecutively, then calculate the highest example of that and compare it with another file (this isn't important right now).

So with a file with the following long line:

'dtcdtcdtcuiouiouiodtcdtcdtcdtcdtcuiouioiodtcdtc'

I would want to find the highest instance of 'dtc' repeated consecutively. At the start of the line, it does so three times. Then around the middle it does so four times. Then at the end it does so twice. So I would want my stored information to be 4.

I'm struggling to implement this, however. As I said, I am new and have been trying to search for the best way to achieve this. I have so far started to consider options like:

read = textfile.read()
counter = 0

for i in range(len(read)):
        if (read[i:i + 2]) == 'dtc':
           counter += 1

But yeah, I'm struggling to figure out the best way to implement the required algorithm. If you could even point me in the right direction, I would be grateful.

Many thanks

Body:
This should work:

read = "dtcdtcdtcuiouiouiodtcdtcdtcdtcdtcuiouioiodtcdtc"

maxIter=len(read)
maxCounter=0
i=0
counter = 0
while (1):
    if i==maxIter:
        break
    if(read[i:i+3]=="dtc"):
        counter+=1
        if counter>maxCounter:
            maxCounter=counter
        i+=3
    else:
        counter=0
        i+=1

p.s. in your sample string, "dtc" is repeated 5 times in the middle


问:
Can I use the dot character (.) for a field name in Mongo DB?
I'm using MongoDb to store JSON data. One of the documents I have contains a deeply nested JSON with values such as the following:

......

```<code>"value-3.4": {
                  "submit-message": {
                     "enabled": "false"
                  },
                  "dlr-tlvs": {
                     "parse-value": "true",

                  }
               }
            }

</code>```

...

I've got a node.js application using "mongodb": "^3.5.3" which connects to my DB reads, the json data and try to push it to the database using something like the following. Note that datito is the json object that comes from an external file.

```<code> try {
                                                     db.collection('config').insertOne(
                                                         datito
                                                     ).then(function(err) {
                                                      console.log(err);
                                                      // expected output: "Success!"
                                                    })
                                                  } catch (e) {
                                                     console.log(e);
                                                  }
</code>```

The problem is that when I try to push the data, I get an error because the field name contains a "."
I've read that since Mongo 3.6, https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names this shouldn't be a problem. However, it seems that the latest version published in npm is 3.5.3.

I've also followed these instructions to update Mongo to 3.6 https://docs.mongodb.com/v3.6/installation/ but it seems that it will make no difference as I'm pushing the data from my nodejs application rather than the Mongo shell. Does it make sense?

Could you please advise if I'm getting confused between my mongodb version in my nodejs application vs the Mongo DB version I have 4.2.3?

When I run mongo --version in my CLI I've got:

MongoDB shell version v4.2.3

But my nodejs application seems to be using 3.5.3. Is this assumption correct and hence I should rename the field of my json to not contain "."?

I appreciate your help.

Thanks

答:
While it is stated in the docs that MongoDB(version 3.6 upwards) works well with field names containing dots(.), it is not recommended:

IMPORTANT

The MongoDB Query Language cannot always meaningfully express queries
  over documents whose field names contain these characters (see
  SERVER-30575).

Until support is added in the query language, the use of $ and . in
  field names is not recommended and is not supported by the official MongoDB drivers.

Source

Notice it also stated that using field names containing dots(.) is not supported by official MongoDB drivers, one of which is what you are using, most likely this is why you are having error on DB insertion.

Body:
I'm using MongoDb to store JSON data. One of the documents I have contains a deeply nested JSON with values such as the following:

......

"value-3.4": {
                  "submit-message": {
                     "enabled": "false"
                  },
                  "dlr-tlvs": {
                     "parse-value": "true",

                  }
               }
            }

...

I've got a node.js application using "mongodb": "^3.5.3" which connects to my DB reads, the json data and try to push it to the database using something like the following. Note that datito is the json object that comes from an external file.

 try {
                                                     db.collection('config').insertOne(
                                                         datito
                                                     ).then(function(err) {
                                                      console.log(err);
                                                      // expected output: "Success!"
                                                    })
                                                  } catch (e) {
                                                     console.log(e);
                                                  }

The problem is that when I try to push the data, I get an error because the field name contains a "."
I've read that since Mongo 3.6, https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names this shouldn't be a problem. However, it seems that the latest version published in npm is 3.5.3.

I've also followed these instructions to update Mongo to 3.6 https://docs.mongodb.com/v3.6/installation/ but it seems that it will make no difference as I'm pushing the data from my nodejs application rather than the Mongo shell. Does it make sense?

Could you please advise if I'm getting confused between my mongodb version in my nodejs application vs the Mongo DB version I have 4.2.3?

When I run mongo --version in my CLI I've got:

MongoDB shell version v4.2.3

But my nodejs application seems to be using 3.5.3. Is this assumption correct and hence I should rename the field of my json to not contain "."?

I appreciate your help.

Thanks


问:
How to extract a variable(username,ID) from Jenkins output
This is the output I got:

"Successfully created scratch org: oopopoooppooop, username: test+color@example.com"

when I run the following script:

echo "1. Creating Scratch Org"
def orgStatus = bat returnStdout: true, script: "sfdx force:org:create --definitionfile ${PROJECT_SCRATCH_PATH} --durationdays 30 --setalias ${SCRATCH_ORG_NAME} -v DevHub "

if (!orgStatus.contains("Successfully created scratch org")) {
    error "Scratch Org creation failed"
} else {
    echo orgStatus
}
```

Now I need to extract scratch org ID and username from the output separately and store it.

答:
You can use a regular expression:

def regEx = 'Successfully created scratch org: (.*?), username: (.*)'
def match = orgStatus =~ regEx

if( match ) {
    println "ID: " + match[0][1]
    println "username: " + match[0][2]
}
```

Here the operator =~ applies the regular expression to the input and the result is stored in match.

Live Demo

Body:
This is the output I got:

"Successfully created scratch org: oopopoooppooop, username: test+color@example.com"

when I run the following script:

echo "1. Creating Scratch Org"
def orgStatus = bat returnStdout: true, script: "sfdx force:org:create --definitionfile ${PROJECT_SCRATCH_PATH} --durationdays 30 --setalias ${SCRATCH_ORG_NAME} -v DevHub "

if (!orgStatus.contains("Successfully created scratch org")) {
    error "Scratch Org creation failed"
} else {
    echo orgStatus
}

Now I need to extract scratch org ID and username from the output separately and store it.

Body:
You can use a regular expression:

def regEx = 'Successfully created scratch org: (.*?), username: (.*)'
def match = orgStatus =~ regEx

if( match ) {
    println "ID: " + match[0][1]
    println "username: " + match[0][2]
}

Here the operator =~ applies the regular expression to the input and the result is stored in match.

Live Demo


问:
Getting Parsing error: Unexpected token, expected "," in Vue
I am trying to do an axios request but whatever I do I get the same error message.

The message is:

Parsing error: Unexpected token, expected ",". The error points at axios.get  (it points at the dot between "axios" and "get" in the error message). It gives the same message if I put something like console.log in the code.

I am basically just using a regular default vue project and the only thing I have done is to add the following code in HelloWorld.vue.

```<code><script type="text/javascript">
   import axios from 'axios';
 //  const axios = require('axios');

  export default {
    name: 'HelloWorld',  //  console.log("hi"),
    props: {
      msg: String //response
    },
    methods: {
      axios.get('https://swapi.co/api/people/1')
        .then(function(response){
            console.log(response)
        })
    }
  }

</script>
</code>```

Can someone please tell me why this error keeps coming up, I am guessing this is pretty simple but I am losing my mind at this point. Thank you

答:
You won't be able to access your axios method, since it isn't actually being declared as a function. You can write vue methods in two ways, both equivalent (to my knowledge).

```<code>export default {
  data() {
    item: []
  },
  methods: {
    getStarWarsCharacters() {
      // axios call goes here
    }
  }
}
</code>```

Other way is like this:

```<code>export default {
  data() {
    item: []
  },
  methods: {
    getStarWarsCharacters: () => {
      // axios call goes here
    }
  }
}
</code>```

I suspect that if you write it in the first way, Vue is actually converting to the second.

Body:
I am trying to do an axios request but whatever I do I get the same error message.

The message is:

Parsing error: Unexpected token, expected ",". The error points at axios.get  (it points at the dot between "axios" and "get" in the error message). It gives the same message if I put something like console.log in the code.

I am basically just using a regular default vue project and the only thing I have done is to add the following code in HelloWorld.vue.

Can someone please tell me why this error keeps coming up, I am guessing this is pretty simple but I am losing my mind at this point. Thank you

Body:
You won't be able to access your axios method, since it isn't actually being declared as a function. You can write vue methods in two ways, both equivalent (to my knowledge).

export default {
  data() {
    item: []
  },
  methods: {
    getStarWarsCharacters() {
      // axios call goes here
    }
  }
}

Other way is like this:

export default {
  data() {
    item: []
  },
  methods: {
    getStarWarsCharacters: () => {
      // axios call goes here
    }
  }
}

I suspect that if you write it in the first way, Vue is actually converting to the second.


问:
Why are Rust documentation tests not executed in Docker when cross-compiling to musl?
My documentation tests are silently not executed in my Docker environment while everything works on both Windows and Ubuntu/Debian hosts.

I created a minimal Github Repository to demonstrate the issue. I tried two different versions of Rust nightly and Rust stable, debug/release, all without success. See my Dockerfile and complete build output.

Example code:

```<code>/// Fixes string arrays which can also be objects into string arrays
/// # Examples
///
/// ```
/// assert_eq!(cargo_test_doc_docker::add(1, 2), 3);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}
</code>```

Result when executing on Debian:

arturh@host:~/projects/cargo-test-doc-docker$ cargo test
   Compiling cargo-test-doc-docker v0.1.0 (/home/arturh/projects/cargo-test-doc-docker)
    Finished test [unoptimized + debuginfo] target(s) in 2.39s
     Running target/debug/deps/cargo_test_doc_docker-9d5ae146cd4c3628

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/cargo_test_doc_docker-2a696d2579128ce1

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests cargo-test-doc-docker

running 1 test
test src/lib.rs - add (line 4) ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
```

<p>The problem occurs when executing the build on Docker. This is a minimal Dockerfile that reproduces the problem:</p>

```FROM ekidd/rust-musl-builder:nightly-2020-01-26-openssl11 as build
COPY --chown=rust:rust . .
RUN cargo test; echo $?
```

<p>Result for every Rust toolchain I tried:</p>

<pre class="lang-none prettyprint-override"><code>Step 6/17 : RUN cargo test; echo $?
 ---> Running in b266fc72f3c1
   Compiling cargo-test-doc-docker v0.1.0 (/home/rust/src)
    Finished test [unoptimized + debuginfo] target(s) in 0.32s
     Running target/x86_64-unknown-linux-musl/debug/deps/cargo_test_doc_docker-7b40e7e5b47f49eb

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/x86_64-unknown-linux-musl/debug/deps/cargo_test_doc_docker-0bfec9752a7bec14

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

0
</code>```

It does not even try to execute any doc tests and exits with zero so it's not easily noticed. I guess it must be something the Docker base image does, but what could that be?

答:
Shepmaster was right, when I target the x86_64-unknown-linux-musl it also does not work locally on Debian:

arturh@host:~/projects/cargo-test-doc-docker$ cargo test --target=x86_64-unknown-linux-musl; echo $?
   Compiling cargo-test-doc-docker v0.1.0 (/home/arturh/projects/cargo-test-doc-docker)
    Finished test [unoptimized + debuginfo] target(s) in 0.28s
     Running target/x86_64-unknown-linux-musl/debug/deps/cargo_test_doc_docker-8dfff5631875d404

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/x86_64-unknown-linux-musl/debug/deps/cargo_test_doc_docker-eb877250b708174b

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

0
```

I guess I must have a separate build step for testing the doc tests with the target x86_64-unknown-linux-gnu.

Body:
My documentation tests are silently not executed in my Docker environment while everything works on both Windows and Ubuntu/Debian hosts.

I created a minimal Github Repository to demonstrate the issue. I tried two different versions of Rust nightly and Rust stable, debug/release, all without success. See my Dockerfile and complete build output.

Example code:

/// Fixes string arrays which can also be objects into string arrays
/// # Examples
///
/// ```
/// assert_eq!(cargo_test_doc_docker::add(1, 2), 3);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

Result when executing on Debian:

arturh@host:~/projects/cargo-test-doc-docker$ cargo test
   Compiling cargo-test-doc-docker v0.1.0 (/home/arturh/projects/cargo-test-doc-docker)
    Finished test [unoptimized + debuginfo] target(s) in 2.39s
     Running target/debug/deps/cargo_test_doc_docker-9d5ae146cd4c3628

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/cargo_test_doc_docker-2a696d2579128ce1

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests cargo-test-doc-docker

running 1 test
test src/lib.rs - add (line 4) ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

The problem occurs when executing the build on Docker. This is a minimal Dockerfile that reproduces the problem:

FROM ekidd/rust-musl-builder:nightly-2020-01-26-openssl11 as build
COPY --chown=rust:rust . .
RUN cargo test; echo $?

Result for every Rust toolchain I tried:

Step 6/17 : RUN cargo test; echo $?
 ---> Running in b266fc72f3c1
   Compiling cargo-test-doc-docker v0.1.0 (/home/rust/src)
    Finished test [unoptimized + debuginfo] target(s) in 0.32s
     Running target/x86_64-unknown-linux-musl/debug/deps/cargo_test_doc_docker-7b40e7e5b47f49eb

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/x86_64-unknown-linux-musl/debug/deps/cargo_test_doc_docker-0bfec9752a7bec14

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

0

It does not even try to execute any doc tests and exits with zero so it's not easily noticed. I guess it must be something the Docker base image does, but what could that be?

Body:
Shepmaster was right, when I target the x86_64-unknown-linux-musl it also does not work locally on Debian:

arturh@host:~/projects/cargo-test-doc-docker$ cargo test --target=x86_64-unknown-linux-musl; echo $?
   Compiling cargo-test-doc-docker v0.1.0 (/home/arturh/projects/cargo-test-doc-docker)
    Finished test [unoptimized + debuginfo] target(s) in 0.28s
     Running target/x86_64-unknown-linux-musl/debug/deps/cargo_test_doc_docker-8dfff5631875d404

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/x86_64-unknown-linux-musl/debug/deps/cargo_test_doc_docker-eb877250b708174b

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

0

I guess I must have a separate build step for testing the doc tests with the target x86_64-unknown-linux-gnu.


答: Invert the second boolean as do { } while ( !(x >= 0 && y <=100 && x < y) ). It's just easier to read and understand. Write your boolean in the form of what you want to achieve and invert it. As for modulo, it has to be put within the do-loop if(b % 2 == 0) std::cout << b++

Title: I can't get past a few do-while loops even though their conditions have not been met


问:
Regex to get total price with space as separator
I need to build a regex that would catch the total price, here some exemple:

```<code>Total:   145.01 $
Total:   1 145.01 $
Total:   00.01 $
Total:   12 345.01 $
</code>```

It's need to get any price that follow 'Total: ', without the '$'.

That what I got so far : (?<=\bTotal:\s*)(\d+.\d+)

RegExr

答:
I assume:

each string must begin 'Total:   ' (three spaces), the prefix;

the last digit in the string must be followed by ' $' (one space), the suffix, which is at the end of the string;

the substring between the prefix and suffix must end '.dd', where 'd' presents any digit, the cents;

the substring between the prefix and cents must match one of the following patterns, where 'd' represents any digit: 'd', 'dd', 'ddd', 'd ddd', 'dd ddd', 'ddd ddd', 'd ddd ddd', 'dd ddd ddd', 'ddd ddd ddd', 'd ddd ddd ddd' and so on;

the return value is the substring between the prefix and suffix that meets the above requirements; and

spaces will be removed from the substring returned as a separate step at the end.

We can use the following regular expression.

```<code>r = /\ATotal: {3}(\d{1,3}(?: \d{3})*\.\d{2}) \$\z/
</code>```

In Ruby (but if you don't know Ruby you'll get the idea):

```<code>arr = <<~_.split(/\n/)
Total:   145.01 $
Total:   1 145.01 $
Total:   00.01 $
Total:   12 345.01 $
Total:   1 241 345.01 $
Total:  1.00 $
Total:   1.00$
Total:   1.00 $x
My Total:  1.00 $
Total:   12 34.01 $
_
</code>```

The following matches each string in the array arr and extracts the contents of capture group 1, which is shown on the right side of each line.

```<code>arr.each do |s|
  puts "\"#{(s + '"[r,1]').ljust(30)}: #{s[r,1] || 'no match'}"
end
</code>```

```<code>"Total:   145.01 $"[r,1]       : 145.01
"Total:   1 145.01 $"[r,1]     : 1 145.01
"Total:   00.01 $"[r,1]        : 00.01
"Total:   12 345.01 $"[r,1]    : 12 345.01
"Total:   1 241 345.01 $"[r,1] : 1 241 345.01
"Total:  1.00 $"[r,1]          : no match
"Total:   1.00$"[r,1]          : no match
"Total:   1.00 $x"[r,1]        : no match
"My Total:  1.00 $"[r,1]       : no match
"Total:   12 34.01 $"[r,1]     : no match
</code>```

The regular expression can be written in free-spacing mode to make it self-documenting.

```<code>r = /
    \A             # match the beginning of the string
    Total:\ {3}    # match 'Total:' followed by 3 digits
    (              # begin capture group 1
      \d{1,3}      # match 1, 2 or 3 digits
      (?:\ \d{3})  # match a space followed by 3 digits
      *            # perform the previous match zero or more times
      \.\d{2}      # match a period followed by 2 digits
    )              # end capture group 1
    \ \$           # match a space followed by a dollar sign
    \z             # match end of string
    /x             # free-spacing regex definition mode
</code>```

The regex can be seen in action here.

Body:
I need to build a regex that would catch the total price, here some exemple:

Total:   145.01 $
Total:   1 145.01 $
Total:   00.01 $
Total:   12 345.01 $

It's need to get any price that follow 'Total: ', without the '$'.

That what I got so far : (?<=\bTotal:\s*)(\d+.\d+)

RegExr

Body:
I assume:

each string must begin 'Total:   ' (three spaces), the prefix;

the last digit in the string must be followed by ' $' (one space), the suffix, which is at the end of the string;

the substring between the prefix and suffix must end '.dd', where 'd' presents any digit, the cents;

the substring between the prefix and cents must match one of the following patterns, where 'd' represents any digit: 'd', 'dd', 'ddd', 'd ddd', 'dd ddd', 'ddd ddd', 'd ddd ddd', 'dd ddd ddd', 'ddd ddd ddd', 'd ddd ddd ddd' and so on;

the return value is the substring between the prefix and suffix that meets the above requirements; and

spaces will be removed from the substring returned as a separate step at the end.

We can use the following regular expression.

r = /\ATotal: {3}(\d{1,3}(?: \d{3})*\.\d{2}) \$\z/

In Ruby (but if you don't know Ruby you'll get the idea):

arr = <<~_.split(/\n/)
Total:   145.01 $
Total:   1 145.01 $
Total:   00.01 $
Total:   12 345.01 $
Total:   1 241 345.01 $
Total:  1.00 $
Total:   1.00$
Total:   1.00 $x
My Total:  1.00 $
Total:   12 34.01 $
_

The following matches each string in the array arr and extracts the contents of capture group 1, which is shown on the right side of each line.

arr.each do |s|
  puts "\"#{(s + '"[r,1]').ljust(30)}: #{s[r,1] || 'no match'}"
end

"Total:   145.01 $"[r,1]       : 145.01
"Total:   1 145.01 $"[r,1]     : 1 145.01
"Total:   00.01 $"[r,1]        : 00.01
"Total:   12 345.01 $"[r,1]    : 12 345.01
"Total:   1 241 345.01 $"[r,1] : 1 241 345.01
"Total:  1.00 $"[r,1]          : no match
"Total:   1.00$"[r,1]          : no match
"Total:   1.00 $x"[r,1]        : no match
"My Total:  1.00 $"[r,1]       : no match
"Total:   12 34.01 $"[r,1]     : no match

The regular expression can be written in free-spacing mode to make it self-documenting.

r = /
    \A             # match the beginning of the string
    Total:\ {3}    # match 'Total:' followed by 3 digits
    (              # begin capture group 1
      \d{1,3}      # match 1, 2 or 3 digits
      (?:\ \d{3})  # match a space followed by 3 digits
      *            # perform the previous match zero or more times
      \.\d{2}      # match a period followed by 2 digits
    )              # end capture group 1
    \ \$           # match a space followed by a dollar sign
    \z             # match end of string
    /x             # free-spacing regex definition mode

The regex can be seen in action here.


问:
How do I detect whether or not an input with type=time has any values entered
I have a javascript script that's supposed to detect whenever an html form input with type="time" has any value entered.

However, whenever I enter a partial value (for instance, type one number, instead of a full time with AM/PM), it doesn't detect the input as having a value.

In the below example, timeSelector is the input with type="time".

```<code>if (timeSelector.value == "") {
    timeSelector.classList.add("empty");
} else {
    timeSelector.classList.remove("empty");
}
</code>```

Is there any way to detect this type of thing?

To clarify, since apparently I didn't ask my question clearly enough, I need to detect when a time input has something entered, even if that something is an invalid or incomplete input.

答:
Well the problem with html5 inputs is they do not give the text in the input if it is not valid. So you can use checkValidity when the user removes focus from the element.

var checkInput = function() {
  var value = this.value
  var isValid = this.checkValidity()
  if (!this.value.length && isValid) {
    console.log('empty');
  } else if (!this.value.length && !isValid) {
    console.log('invalid time entered')
  } else {
    console.log('valid time entered')
  }
}

var input = document.querySelector("input")

input.addEventListener("input", checkInput)
input.addEventListener("blur", checkInput)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="time" /></code>```

Body:
I have a javascript script that's supposed to detect whenever an html form input with type="time" has any value entered.

However, whenever I enter a partial value (for instance, type one number, instead of a full time with AM/PM), it doesn't detect the input as having a value.

In the below example, timeSelector is the input with type="time".

if (timeSelector.value == "") {
    timeSelector.classList.add("empty");
} else {
    timeSelector.classList.remove("empty");
}

Is there any way to detect this type of thing?

To clarify, since apparently I didn't ask my question clearly enough, I need to detect when a time input has something entered, even if that something is an invalid or incomplete input.

Body:
Well the problem with html5 inputs is they do not give the text in the input if it is not valid. So you can use checkValidity when the user removes focus from the element.

var checkInput = function() {
  var value = this.value
  var isValid = this.checkValidity()
  if (!this.value.length && isValid) {
    console.log('empty');
  } else if (!this.value.length && !isValid) {
    console.log('invalid time entered')
  } else {
    console.log('valid time entered')
  }
}

var input = document.querySelector("input")

input.addEventListener("input", checkInput)
input.addEventListener("blur", checkInput)

<input type="time" />