问:
TinyMCE Paths, How to specify where to load things like editor_plugin.js
I installed TinyMCE, everything was working great. I then used Google Closure to package my site's JavaScript along with TinyMCE_src

The problem I'm having is that TinyMCE is now making calls to:

```<code>plugins/paste/editor_plugin.js
themes/advanced/editor_template.js
langs/en.js
</code>```

And that paths that are being used are invalid, they are 404'ing

How can I tell TinyMCE where to go to get these files?

I tried:

```<code>relative_urls : false,
document_base_url : "http://www.site.com/path1/",
</code>```

But they have no effect on the files above.

Advise? Thanks

答:
If you're using the TinyMCE jQuery plugin, you can load everything from a remote location, just add the script_url parameter into your init code. It will load everything from there, including any scripts/images/etc.

```<code>$('textarea').tinymce({
    script_url: 'http://tinymce.moxiecode.com/js/tinymce/jscripts/tiny_mce/tiny_mce.js'
});
</code>```

Check out this fiddle, it's including the whole thing remotely from the TinyMCE website: http://jsfiddle.net/xgPzS/22/

Body:
I installed TinyMCE, everything was working great. I then used Google Closure to package my site's JavaScript along with TinyMCE_src

The problem I'm having is that TinyMCE is now making calls to:

plugins/paste/editor_plugin.js
themes/advanced/editor_template.js
langs/en.js

And that paths that are being used are invalid, they are 404'ing

How can I tell TinyMCE where to go to get these files?

I tried:

relative_urls : false,
document_base_url : "http://www.site.com/path1/",

But they have no effect on the files above.

Advise? Thanks

Body:
If you're using the TinyMCE jQuery plugin, you can load everything from a remote location, just add the script_url parameter into your init code. It will load everything from there, including any scripts/images/etc.

$('textarea').tinymce({
    script_url: 'http://tinymce.moxiecode.com/js/tinymce/jscripts/tiny_mce/tiny_mce.js'
});

Check out this fiddle, it's including the whole thing remotely from the TinyMCE website: http://jsfiddle.net/xgPzS/22/


来源: stackexchange

问:
Regular expression which matches a domain with only two ending characters?
I'm trying to stop spammers who are using short domains bit.ly etc. The domains they post seem to all be only two characters (not .com, etc).
I've used this:

```<code>\.[a-z][a-z]$
</code>```

But, it has two problems:
it matches .co.uk
If anything is after the domain, it doesn't match (a space or slash, example: bit.ly/2231)

Could someone assist me with a regex that would accomplish this, please?

答:
Whole URL matching.  Depends on domain being before the first forward slash past protocol.  First one uses if it only has one dot in the url and ends with two character primary TLD.  Second one uses negative lookbehind to make sure it's not something like .co.uk.

https://regex101.com/r/5acu56/2

```<code>^(https?:\/\/)?[^\/.]+\.[a-z][a-z](\/|\s*$)
</code>```

https://regex101.com/r/p8Ajw9/2

```<code>^(https?:\/\/)?[^\/]+(?<!\.[a-z][a-z])\.[a-z][a-z](\/\s*|\s*$)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to stop spammers who are using short domains bit.ly etc. The domains they post seem to all be only two characters (not .com, etc).
I've used this:

\.[a-z][a-z]$

But, it has two problems:
it matches .co.uk
If anything is after the domain, it doesn't match (a space or slash, example: bit.ly/2231)

Could someone assist me with a regex that would accomplish this, please?

Body:
Whole URL matching.  Depends on domain being before the first forward slash past protocol.  First one uses if it only has one dot in the url and ends with two character primary TLD.  Second one uses negative lookbehind to make sure it's not something like .co.uk.

https://regex101.com/r/5acu56/2

^(https?:\/\/)?[^\/.]+\.[a-z][a-z](\/|\s*$)

https://regex101.com/r/p8Ajw9/2

^(https?:\/\/)?[^\/]+(?<!\.[a-z][a-z])\.[a-z][a-z](\/\s*|\s*$)


问:
How to decode Base64 String to Image file with flutter
I am actually trying to convert an Image file to Base64 and decode Base64 String to Image file in Dart/Flutter. Indeed, my application takes pictures with the camera plugin and then, saves it in a database as a Base64 String (because I don't know any other way but may be there is more relevant ways to store several images?).

I encode with this code :

```<code>            final path = join(
              (await getTemporaryDirectory()).path,
              '${DateTime.now()}.png',
            );
            await _controller.takePicture(path);
            final bytes = File(path).readAsBytesSync();
            String img64 = base64Encode(bytes);

            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => DisplayPictureScreen(imageAnalysed: img64),
              ),
            );

</code>```

And decode with this one :

```<code>class DisplayPictureScreen extends StatelessWidget {
  final String imageAnalysed;
  const DisplayPictureScreen({Key key, this.imageAnalysed}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final decodedBytes = base64Decode(imageAnalysed);
    var fileImg= File("testImage.png");
    fileImg..writeAsBytesSync(decodedBytes);

    return Scaffold(
      appBar: AppBar(title: Text('Display the Picture')),
      body: Image.file(fileImg),
    );
  }
}
</code>```

But there is this error :

```<code>The following FileSystemException was thrown building DisplayPictureScreen(dirty):
Cannot open file, path = 'testImage.png' (OS Error: Read-only file system, errno = 30)
</code>```

How can I solve my problem and get an image from the Base64 String ?

Thank you for your help !

答:
You can copy paste run full code below

You can use path_provider to get getApplicationDocumentsDirectory and use bool isLoading to control show image when write file finish

code snippet

```<code> void writeFile() async {
    final decodedBytes = base64Decode(widget.imageAnalysed);
    final directory = await getApplicationDocumentsDirectory();
    fileImg = File('${directory.path}/testImage.png');
    print(fileImg.path);
    fileImg.writeAsBytesSync(List.from(decodedBytes));

    setState(() {
      isLoading = false;
    });
  }

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_){
      writeFile();
    });

 ...
 @override
  Widget build(BuildContext context) {
    return isLoading ? CircularProgressIndicator() : Image.file(fileImg);
  }
</code>```

working demo

full code

```<code>import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/material.dart';

class DisplayPictureScreen extends StatefulWidget {
  final String imageAnalysed;
  const DisplayPictureScreen({Key key, this.imageAnalysed}) : super(key: key);

  @override
  _DisplayPictureScreenState createState() => _DisplayPictureScreenState();
}

class _DisplayPictureScreenState extends State<DisplayPictureScreen> {
  File fileImg;
  bool isLoading = true;

  void writeFile() async {
    final decodedBytes = base64Decode(widget.imageAnalysed);
    final directory = await getApplicationDocumentsDirectory();
    fileImg = File('${directory.path}/testImage.png');
    print(fileImg.path);
    fileImg.writeAsBytesSync(List.from(decodedBytes));

    setState(() {
      isLoading = false;
    });
  }

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_){
      writeFile();
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return isLoading ? CircularProgressIndicator() : Image.file(fileImg);
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  String base64String =
      '''[encoded data, 5612 characters]''';
  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            DisplayPictureScreen(imageAnalysed: base64String),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}
</code>```

Body:
I am actually trying to convert an Image file to Base64 and decode Base64 String to Image file in Dart/Flutter. Indeed, my application takes pictures with the camera plugin and then, saves it in a database as a Base64 String (because I don't know any other way but may be there is more relevant ways to store several images?).

I encode with this code :

            final path = join(
              (await getTemporaryDirectory()).path,
              '${DateTime.now()}.png',
            );
            await _controller.takePicture(path);
            final bytes = File(path).readAsBytesSync();
            String img64 = base64Encode(bytes);

            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => DisplayPictureScreen(imageAnalysed: img64),
              ),
            );

And decode with this one :

class DisplayPictureScreen extends StatelessWidget {
  final String imageAnalysed;
  const DisplayPictureScreen({Key key, this.imageAnalysed}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final decodedBytes = base64Decode(imageAnalysed);
    var fileImg= File("testImage.png");
    fileImg..writeAsBytesSync(decodedBytes);

    return Scaffold(
      appBar: AppBar(title: Text('Display the Picture')),
      body: Image.file(fileImg),
    );
  }
}

But there is this error :

The following FileSystemException was thrown building DisplayPictureScreen(dirty):
Cannot open file, path = 'testImage.png' (OS Error: Read-only file system, errno = 30)

How can I solve my problem and get an image from the Base64 String ?

Thank you for your help !

Body:
You can copy paste run full code below

You can use path_provider to get getApplicationDocumentsDirectory and use bool isLoading to control show image when write file finish

code snippet

 void writeFile() async {
    final decodedBytes = base64Decode(widget.imageAnalysed);
    final directory = await getApplicationDocumentsDirectory();
    fileImg = File('${directory.path}/testImage.png');
    print(fileImg.path);
    fileImg.writeAsBytesSync(List.from(decodedBytes));

    setState(() {
      isLoading = false;
    });
  }

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_){
      writeFile();
    });

 ...
 @override
  Widget build(BuildContext context) {
    return isLoading ? CircularProgressIndicator() : Image.file(fileImg);
  }

working demo

full code

import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/material.dart';

class DisplayPictureScreen extends StatefulWidget {
  final String imageAnalysed;
  const DisplayPictureScreen({Key key, this.imageAnalysed}) : super(key: key);

  @override
  _DisplayPictureScreenState createState() => _DisplayPictureScreenState();
}

class _DisplayPictureScreenState extends State<DisplayPictureScreen> {
  File fileImg;
  bool isLoading = true;

  void writeFile() async {
    final decodedBytes = base64Decode(widget.imageAnalysed);
    final directory = await getApplicationDocumentsDirectory();
    fileImg = File('${directory.path}/testImage.png');
    print(fileImg.path);
    fileImg.writeAsBytesSync(List.from(decodedBytes));

    setState(() {
      isLoading = false;
    });
  }

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_){
      writeFile();
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return isLoading ? CircularProgressIndicator() : Image.file(fileImg);
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  String base64String =
      '''[encoded data, 5612 characters]''';
  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            DisplayPictureScreen(imageAnalysed: base64String),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}


问:
HomeBrew: Error- /usr/local/Cellar is not writable
When I run the following command in my terminal:

usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

I get an error:

```<code>/usr/local/Cellar is not writable. You should change the
ownership and permissions of /usr/local/Cellar back to your
user account:
sudo chown -R $(whoami) /usr/local/Cellar
</code>```

Failed during: /usr/local/bin/brew update --force

I went through similar posts on S.O and all of them had the following commands as answer,so I ran the following commands in the terminal:

sudo chown -R $tejas /usr/local/Cellar

sudo chown -R $tejas:admin /usr/local/Cellar

sudo chown -R $tejas /usr/local

sudo chown -R $tejas:admin /usr/local

I ran the installation command after all above four command but it still gives me the error. Can someone please help me fix this. Thank you.

答:
I got the same issue on MacOS when install GoAccess:

```<code>Error: /usr/local/Cellar is not writable. You should change the
ownership and permissions of /usr/local/Cellar back to your
user account:
  sudo chown -R $(whoami) /usr/local/Cellar
Error: The following directories are not writable by your user:
/usr/local/Cellar
/usr/local/share/zsh
/usr/local/share/zsh/site-functions
</code>```

I fixed it by run following command:

```<code> sudo chown -R $(whoami) /usr/local/Cellar /usr/local/share/zsh /usr/local/share/zsh/site-functions
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When I run the following command in my terminal:

usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

I get an error:

/usr/local/Cellar is not writable. You should change the
ownership and permissions of /usr/local/Cellar back to your
user account:
sudo chown -R $(whoami) /usr/local/Cellar

Failed during: /usr/local/bin/brew update --force

I went through similar posts on S.O and all of them had the following commands as answer,so I ran the following commands in the terminal:

sudo chown -R $tejas /usr/local/Cellar

sudo chown -R $tejas:admin /usr/local/Cellar

sudo chown -R $tejas /usr/local

sudo chown -R $tejas:admin /usr/local

I ran the installation command after all above four command but it still gives me the error. Can someone please help me fix this. Thank you.

Body:
I got the same issue on MacOS when install GoAccess:

Error: /usr/local/Cellar is not writable. You should change the
ownership and permissions of /usr/local/Cellar back to your
user account:
  sudo chown -R $(whoami) /usr/local/Cellar
Error: The following directories are not writable by your user:
/usr/local/Cellar
/usr/local/share/zsh
/usr/local/share/zsh/site-functions

I fixed it by run following command:

 sudo chown -R $(whoami) /usr/local/Cellar /usr/local/share/zsh /usr/local/share/zsh/site-functions


问:
How can i remove a specific part of a variable value using perl
we have a variable values
value is : /abc/cde/efg/sanj/Sent//abc/cde/efg/sanj/sample sample1.pdf

I want to remove the middle part of this value '/abc/cde/efg/sanj/'.
Is it possible to remove this part.

答:
Since we're talking paths,

use Path::Tiny qw( path );

my $qfn = '/abc/cde/efg/sanj/Sent//abc/cde/efg/sanj/sample sample1.pdf';
my $base_qfn = '/abc/cde/efg/sanj';

say path($qfn)->relative($base_qfn);
```

<p>Output:</p>

<pre class="lang-none prettyprint-override"><code>Sent/abc/cde/efg/sanj/sample sample1.pdf
</code>```

Body:
Since we're talking paths,

use Path::Tiny qw( path );

my $qfn = '/abc/cde/efg/sanj/Sent//abc/cde/efg/sanj/sample sample1.pdf';
my $base_qfn = '/abc/cde/efg/sanj';

say path($qfn)->relative($base_qfn);

Output:

Sent/abc/cde/efg/sanj/sample sample1.pdf


问:
Python and random keys of 21 char max
I am using an api which takes a name of 21 char max to represent an internal session which has a lifetime of around "two days". I would like the name not to be meaningfull using some kind of hasing ? md5 generates 40 chars, is there something else i could use ?

For now i use 'userid[:10]' + creation time: ddhhmmss + random 3 chars.

Thanks,

答: Why not take first 21 chars from md5 or SHA1 hash?</p>

OwnerDisplayName: coulix

ContentLicense: CC BY-SA 2.5

Title: Python and random keys of 21 char max

OwnerDisplayName: Alex Lebedev


问:
ORA-00984 column not allowed here
I am getting error
"Execute-984 ORA-00984: column not allowed here"
while I am inserting values in my table Registred_Customer using Pro*C

Registred_Customer is defined as

```<code>CREATE TABLE Registred_Customer (
    Cust_id NUMBER(6) PRIMARY KEY,
    Name VARCHAR2(20) NOT NULL,
    Age NUMBER,
    Sex CHAR,
    Addr VARCHAR2(50),
    Contact NUMBER(10)
);
</code>```

Inserting values using a pro*c method

```<code>addCustomer(i, name,age, gender, address,contectNo);
</code>```

in Pro*C method I use following code to insert

```<code>EXEC SQL INSERT INTO REGISTRED_CUSTOMER VALUES
(cust_id, cust_name, age, sex, addr,   contact);
</code>```

here cust_name and addr are char *; and sex is char rest as int;

It reports error while using variable but works fine using direct values
like EXEC SQL INSERT INTO REGISTRED_CUSTOMER VALUES (10, 'Pankaj', 23, 'M', 'asdfs', 45875);

I tried changing few lines but in vain.

Thanks in advance.

答:
Your Pro*C code is basically missing the colons (assuming that your formal parameters are called cust_id, cust_name, age etc.):

```<code>EXEC SQL INSERT INTO REGISTRED_CUSTOMER VALUES
    (:cust_id, :cust_name, :age, :sex, :addr, :contact);
</code>```

And it would be more robust to explicitly specify the columns name. Otherwise a change to the table schema can result in difficult to find bugs:

```<code>EXEC SQL INSERT INTO REGISTRED_CUSTOMER (Cust_Id, Name, Ag, Sex, Addr, Contact)
    VALUES (:cust_id, :cust_name, :age, :sex, :addr, :contact);
</code>```

Title: ORA-00984 column not allowed here

Body:
I am getting error
"Execute-984 ORA-00984: column not allowed here"
while I am inserting values in my table Registred_Customer using Pro*C

Registred_Customer is defined as

CREATE TABLE Registred_Customer (
    Cust_id NUMBER(6) PRIMARY KEY,
    Name VARCHAR2(20) NOT NULL,
    Age NUMBER,
    Sex CHAR,
    Addr VARCHAR2(50),
    Contact NUMBER(10)
);

Inserting values using a pro*c method

addCustomer(i, name,age, gender, address,contectNo);

in Pro*C method I use following code to insert

EXEC SQL INSERT INTO REGISTRED_CUSTOMER VALUES
(cust_id, cust_name, age, sex, addr,   contact);

here cust_name and addr are char *; and sex is char rest as int;

It reports error while using variable but works fine using direct values
like EXEC SQL INSERT INTO REGISTRED_CUSTOMER VALUES (10, 'Pankaj', 23, 'M', 'asdfs', 45875);

I tried changing few lines but in vain.

Thanks in advance.

Body:
Your Pro*C code is basically missing the colons (assuming that your formal parameters are called cust_id, cust_name, age etc.):

EXEC SQL INSERT INTO REGISTRED_CUSTOMER VALUES
    (:cust_id, :cust_name, :age, :sex, :addr, :contact);

And it would be more robust to explicitly specify the columns name. Otherwise a change to the table schema can result in difficult to find bugs:

EXEC SQL INSERT INTO REGISTRED_CUSTOMER (Cust_Id, Name, Ag, Sex, Addr, Contact)
    VALUES (:cust_id, :cust_name, :age, :sex, :addr, :contact);


问:
Errors when running "network.sh up" with Hyperledger Fabric Samples in test-network
I met errors when setting up blockchain network(test network) using Hyperledger Fabric Sample.
Actually, when I run the scripts ./network.sh up, the docker images start but immediately shut down. And I check the logs found some errors reported.
And here are my errors shown:

1. when setting orderer：

2020-06-01 06:43:02.784 UTC [orderer.common.server] loadLocalMSP -> PANI 004 Failed to setup local msp with config: KeyMaterial not found in SigningIdentityInfo

panic: Failed to setup local msp with config: KeyMaterial not found in SigningIdentityInfo

goroutine 1 [running]:

github.com/hyperledger/fabric/vendor/go.uber.org/zap/zapcore.(*CheckedEntry).Write(0xc000254dc0, 0x0, 0x0, 0x0)

/go/src/github.com/hyperledger/fabric/vendor/go.uber.org/zap/zapcore/entry.go:229 +0x546

github.com/hyperledger/fabric/vendor/go.uber.org/zap.(*SugaredLogger).log(0xc00010e338, 0xc000094904, 0x1066d69, 0x29, 0xc00029f610, 0x1, 0x1, 0x0, 0x0, 0x0)

/go/src/github.com/hyperledger/fabric/vendor/go.uber.org/zap/sugar.go:234 +0x100

github.com/hyperledger/fabric/vendor/go.uber.org/zap.(*SugaredLogger).Panicf(...)

/go/src/github.com/hyperledger/fabric/vendor/go.uber.org/zap/sugar.go:159

github.com/hyperledger/fabric/common/flogging.(*FabricLogger).Panicf(...)

/go/src/github.com/hyperledger/fabric/common/flogging/zap.go:74

github.com/hyperledger/fabric/orderer/common/server.loadLocalMSP(0xc00019a480, 0xc00026fe50, 0x0)

/go/src/github.com/hyperledger/fabric/orderer/common/server/main.go:677 +0x314

github.com/hyperledger/fabric/orderer/common/server.Main()

/go/src/github.com/hyperledger/fabric/orderer/common/server/main.go:91 +0x232

main.main()

/go/src/github.com/hyperledger/fabric/cmd/orderer/main.go:15 +0x20

2. when setting up peers:

2020-06-01 06:43:02.778 UTC [main] InitCmd -> ERRO 001 Cannot run peer because error when setting up MSP of type bccsp from directory /etc/hyperledger/fabric/msp: KeyMaterial not found in SigningIdentityInfo

is there anyone that may be able to help solve the problems?

best regards

答:
I think the peer cannot read (or find) valid keystore/signcert in MSP folder. Can you show MSP directory tree structure of error peer. Example:

organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com
├── msp
│   ├── IssuerPublicKey
│   ├── IssuerRevocationPublicKey
│   ├── cacerts
│   │   └── localhost-7054-ca-org1.pem
│   ├── config.yaml
│   ├── keystore
│   │   └── d57bc7fae634a1e29b95d5c218272f0b504774667f49d568c67c132b7b368684_sk
│   ├── signcerts
│   │   └── cert.pem
│   └── user
└── tls
    ├── IssuerPublicKey
    ├── IssuerRevocationPublicKey
    ├── ca.crt
    ├── cacerts
    ├── keystore
    │   └── a123ac3f8767a1a5b7a6238d1043e20edd7834f31e2e9352d8b8009b9c8005cf_sk
    ├── server.crt
    ├── server.key
    ├── signcerts
    │   └── cert.pem
    ├── tlscacerts
    │   └── tls-localhost-7054-ca-org1.pem
    └── user
```


问:
Observer pattern in NET Core
I have a domain entity called Transaction and I want to receive notifications in my application services when some event occurs, like new transaction, updated transaction...

So, I readed this article from MSDN https://learn.microsoft.com/en-us/dotnet/standard/events/observer-design-pattern, but I don't know if the observer pattern is the best aproach in NET Core.

Do I need to implement the IObservable in my domain entities?

Any suggestions?

答:
If you want to receive others' events, you should implement the IObservable interface.

IObserver should be provides by the publisher.

I want to receive notifications in my application services when some event ocurss,

In your case, the "my application services".

Title: Observer pattern in NET Core


问:
How to identify a nullable reference type for generic type?
In C# 8 with nullable enabled, is there a way to identify a nullable reference type for generic type?

For nullable value type, there is a section dedicated to it.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types#how-to-identify-a-nullable-value-type

We are trying to do optional null check according to the generic type

#nullable enable
public static Result<T> Create<T>(T value)
{
   if (!typeof(T).IsNullable() && value is null)
      throw new ArgumentNullException(nameof(value));

   // Do something
}

public static bool IsNullable(this Type type)
{
   // If type is SomeClass, return false
   // If type is SomeClass?, return true
   // If type is SomeEnum, return false
   // If type is SomeEnum?, return true
   // If type is string, return false
   // If type is string?, return true
   // If type is int, return false
   // If type is int?, return true
   // etc
}
```

<p>So the following will throw <code>ArgumentNullException</code> when <code>T</code> is not nullable
But allow value to be null with no exception when <code>T</code> is nullable, e.g.</p>

```Create<Anything>(null); // throw ArgumentNullException

Create<Anything?>(null); // No excception
```

答:
You can't use nullable in the constraint, but you can use it in the method signature. This effectively constraints it to be a nullable type. Example:

```<code>static Result<Nullable<T>> Create<T>(Nullable<T> value) where T  : struct
{
    //Do something
}
</code>```

Note that you can use this side by side with your existing method, as an overload, which allows you to execute a different logic path if it's nullable versus if it is not.

```<code>static Result<Nullable<T>> Create<T>(Nullable<T> value) where T  : struct
{
    Log("It's nullable!");
    Foo(value);
}

public static Result<T> Create<T>(T value)
{
    Log("It's not nullable!");
    Foo(value);
}
</code>```

Body:
In C# 8 with nullable enabled, is there a way to identify a nullable reference type for generic type?

For nullable value type, there is a section dedicated to it.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types#how-to-identify-a-nullable-value-type

We are trying to do optional null check according to the generic type

#nullable enable
public static Result<T> Create<T>(T value)
{
   if (!typeof(T).IsNullable() && value is null)
      throw new ArgumentNullException(nameof(value));

   // Do something
}

public static bool IsNullable(this Type type)
{
   // If type is SomeClass, return false
   // If type is SomeClass?, return true
   // If type is SomeEnum, return false
   // If type is SomeEnum?, return true
   // If type is string, return false
   // If type is string?, return true
   // If type is int, return false
   // If type is int?, return true
   // etc
}

So the following will throw ArgumentNullException when T is not nullable
But allow value to be null with no exception when T is nullable, e.g.

Create<Anything>(null); // throw ArgumentNullException

Create<Anything?>(null); // No excception

Body:
You can't use nullable in the constraint, but you can use it in the method signature. This effectively constraints it to be a nullable type. Example:

static Result<Nullable<T>> Create<T>(Nullable<T> value) where T  : struct
{
    //Do something
}

Note that you can use this side by side with your existing method, as an overload, which allows you to execute a different logic path if it's nullable versus if it is not.

static Result<Nullable<T>> Create<T>(Nullable<T> value) where T  : struct
{
    Log("It's nullable!");
    Foo(value);
}

public static Result<T> Create<T>(T value)
{
    Log("It's not nullable!");
    Foo(value);
}


问:
Null Pointer on Hibernate's createQuery()
I'm struggling to get to the bottom of a null pointer exception that happens when I try to run a HQL query with createQuery().

The code to run the query is pretty simple. Originally I had a named query that I was calling, but just to make things more simple and eliminate any complications I'm doing this (springwildlife is the package and Species is the class/entity):

```<code>Query q = session.createQuery("SELECT s FROM springwildlife.Species s");
</code>```

(BTW: I've also tried it with and without the package name in there. And I've also tried doing a simpler "FROM springwildlife.Species" query)

I've created an XML mapping (species.hbm.xml) like so:

```<code><?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="springwildlife.Species" table="species">
      <id name="id" type="java.lang.Long" column="id" >
          <generator class="native">
              <param name="sequence">species_id_seq</param>
          </generator>

  </id>

  <!-- in the actual file I have one these for each item I want to be mapped -->

  <property name="propertyFromClass" type="java.lang.String">
   <column name="sql_table_column_name" />
  </property>

</hibernate-mapping>
</code>```

In my hibernate.cfg.xml file I pull in the mapping like so:

My class/entity looks like this:

```<code>package springwildlife;

public class Species
{
    // properties here

    public Species()
    {
    }

    // sets, gets, etc.

}
</code>```

Does anyone have any idea as to what is happening? I've spent a lot of time trying to track it down and I'm stymied.

(I'm not sure it is relevant, but just in case, I'm using Resin as my server and IntelliJ as my IDE)

This is the stack trace (line 68 in SpeciesFactory.java is the call to createQuery):

```[11-06-02 11:19:26.726] {http://*:8080-2} org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:119)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:96)
    at com.caucho.server.dispatch.ServletFilterChain.doFilter(ServletFilterChain.java:109)
    at com.caucho.server.webapp.WebAppFilterChain.doFilter(WebAppFilterChain.java:156)
    at com.caucho.server.webapp.AccessLogFilterChain.doFilter(AccessLogFilterChain.java:95)
    at com.caucho.server.dispatch.ServletInvocation.service(ServletInvocation.java:287)
    at com.caucho.server.http.HttpRequest.handleRequest(HttpRequest.java:792)
    at com.caucho.network.listen.TcpSocketLink.dispatchRequest(TcpSocketLink.java:730)
    at com.caucho.network.listen.TcpSocketLink.handleRequest(TcpSocketLink.java:689)
    at com.caucho.network.listen.TcpSocketLink.handleRequestsImpl(TcpSocketLink.java:669)
    at com.caucho.network.listen.TcpSocketLink.handleRequests(TcpSocketLink.java:617)
    at com.caucho.network.listen.AcceptTask.doTask(AcceptTask.java:104)
    at com.caucho.network.listen.ConnectionReadTask.runThread(ConnectionReadTask.java:98)
    at com.caucho.network.listen.ConnectionReadTask.run(ConnectionReadTask.java:81)
    at com.caucho.network.listen.AcceptTask.run(AcceptTask.java:67)
    at com.caucho.env.thread.ResinThread.runTasks(ResinThread.java:164)
    at com.caucho.env.thread.ResinThread.run(ResinThread.java:130)
Caused by: java.lang.NullPointerException
    at springwildlife.SpeciesFactory.getSpeciesLister(SpeciesFactory.java:68)
    at springwildlife.LifelistController.handleRequestInternal(LifelistController.java:26)
    at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153)
    at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    ... 18 more
```

答: Since NullPointerException is thrown at the line with createQuery(), the only possible cause is that session is null.

Body:
I'm struggling to get to the bottom of a null pointer exception that happens when I try to run a HQL query with createQuery().

The code to run the query is pretty simple. Originally I had a named query that I was calling, but just to make things more simple and eliminate any complications I'm doing this (springwildlife is the package and Species is the class/entity):

Query q = session.createQuery("SELECT s FROM springwildlife.Species s");

(BTW: I've also tried it with and without the package name in there. And I've also tried doing a simpler "FROM springwildlife.Species" query)

I've created an XML mapping (species.hbm.xml) like so:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="springwildlife.Species" table="species">
      <id name="id" type="java.lang.Long" column="id" >
          <generator class="native">
              <param name="sequence">species_id_seq</param>
          </generator>

  </id>

  <property name="propertyFromClass" type="java.lang.String">
   <column name="sql_table_column_name" />
  </property>

</hibernate-mapping>

In my hibernate.cfg.xml file I pull in the mapping like so:

My class/entity looks like this:

package springwildlife;

public class Species
{
    // properties here

    public Species()
    {
    }

    // sets, gets, etc.

}

Does anyone have any idea as to what is happening? I've spent a lot of time trying to track it down and I'm stymied.

(I'm not sure it is relevant, but just in case, I'm using Resin as my server and IntelliJ as my IDE)

This is the stack trace (line 68 in SpeciesFactory.java is the call to createQuery):

[11-06-02 11:19:26.726] {http://*:8080-2} org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:119)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:96)
    at com.caucho.server.dispatch.ServletFilterChain.doFilter(ServletFilterChain.java:109)
    at com.caucho.server.webapp.WebAppFilterChain.doFilter(WebAppFilterChain.java:156)
    at com.caucho.server.webapp.AccessLogFilterChain.doFilter(AccessLogFilterChain.java:95)
    at com.caucho.server.dispatch.ServletInvocation.service(ServletInvocation.java:287)
    at com.caucho.server.http.HttpRequest.handleRequest(HttpRequest.java:792)
    at com.caucho.network.listen.TcpSocketLink.dispatchRequest(TcpSocketLink.java:730)
    at com.caucho.network.listen.TcpSocketLink.handleRequest(TcpSocketLink.java:689)
    at com.caucho.network.listen.TcpSocketLink.handleRequestsImpl(TcpSocketLink.java:669)
    at com.caucho.network.listen.TcpSocketLink.handleRequests(TcpSocketLink.java:617)
    at com.caucho.network.listen.AcceptTask.doTask(AcceptTask.java:104)
    at com.caucho.network.listen.ConnectionReadTask.runThread(ConnectionReadTask.java:98)
    at com.caucho.network.listen.ConnectionReadTask.run(ConnectionReadTask.java:81)
    at com.caucho.network.listen.AcceptTask.run(AcceptTask.java:67)
    at com.caucho.env.thread.ResinThread.runTasks(ResinThread.java:164)
    at com.caucho.env.thread.ResinThread.run(ResinThread.java:130)
Caused by: java.lang.NullPointerException
    at springwildlife.SpeciesFactory.getSpeciesLister(SpeciesFactory.java:68)
    at springwildlife.LifelistController.handleRequestInternal(LifelistController.java:26)
    at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153)
    at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    ... 18 more


问:
Angular catch errors in a central place or component
I have an Angular 9 project that works with a .NET Core WEB API.
The site features user authentication that is role based. The API returns two types of errors: 401 and 403 depending on the authorization rules for a controller method.

My goal is to display a message in my layout component when the API returns any of these errors, for example:

401: 'Session has expired, please log in.'

403: 'You do not have access to this feature.'

Is there any way to catch these errors in Angular and know which one was thrown?

答:
You can use interceptors to catch every http requests. In your case you need to catch response. To do it;

At the module which you provided HttpClientModule
(app/core).module.ts

```<code>import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { HttpErrorInterceptor } from '<path of interceptor>';

@NgModule({
imports: [HttpClientModule],
providers: [
     {
      provide: HTTP_INTERCEPTORS,
      useClass: HttpErrorInterceptor,
      multi: true,
    },
  ]
});
</code>```

error.interceptor.ts

```<code>export class HttpErrorInterceptor implements HttpInterceptor {
  constructor(
      // your injections if you need
  ) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      catchError((err: HttpErrorResponse) => {
        switch (err.status) {
          case 401: {
            this.handle401();
          }
          case 403: {
            this.handle403();
          }
        }
        return throwError(err);
      }),
    );
  }
</code>```

Body:
You can use interceptors to catch every http requests. In your case you need to catch response. To do it;

At the module which you provided HttpClientModule
(app/core).module.ts

import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { HttpErrorInterceptor } from '<path of interceptor>';

@NgModule({
imports: [HttpClientModule],
providers: [
     {
      provide: HTTP_INTERCEPTORS,
      useClass: HttpErrorInterceptor,
      multi: true,
    },
  ]
});

error.interceptor.ts

export class HttpErrorInterceptor implements HttpInterceptor {
  constructor(
      // your injections if you need
  ) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      catchError((err: HttpErrorResponse) => {
        switch (err.status) {
          case 401: {
            this.handle401();
          }
          case 403: {
            this.handle403();
          }
        }
        return throwError(err);
      }),
    );
  }


问:
Is it possible to play audio without the user interact with the web before? how would I do that?
I need my webpage to play an audio clip without the user interact with the page, I know is poor UX and shouldn't be done that way, but that's what my clients are asking for.

I also know browsers have blocked this feature, so I would appreciate if someone can give me an advice of how to 'hack' this rule (something with events for example)

答:
Chrome and Firefox disabled autoplay features, and it's not currently possible AFAIK:

https://hacks.mozilla.org/2019/02/firefox-66-to-block-automatically-playing-audible-video-and-audio/


问:
CommandError: /code/manage.py already exists, overlaying a project or app into an existing directory won't replace conflicting files
I'm trying to run linux docker on windows and getting this error.

build was fine.

```<code>'''
$ docker-compose build
Building web
Step 1/11 : FROM python:3
 ---> 42d620af35be
Step 2/11 : ENV PYTHONUNBUFFERED 1
 ---> Using cache
 ---> b43065732d6e
Step 3/11 : RUN apt-get update -y
 ---> Using cache
 ---> 6f65e0da9e14
Step 4/11 : RUN apt-get install -y unixodbc unixodbc-dev
 ---> Using cache
 ---> 2a9d7445a991
Step 5/11 : RUN easy_install pip
 ---> Using cache
 ---> 5994e6452e09
Step 6/11 : RUN mkdir /code
 ---> Using cache
 ---> d0eaa870fb98
Step 7/11 : WORKDIR /code
 ---> Using cache
 ---> af78d4b35f26
Step 8/11 : RUN pip uninstall django
 ---> Using cache
 ---> 92f983bfef88
Step 9/11 : COPY requirements.txt /code/
 ---> Using cache
 ---> 3c0031987286
Step 10/11 : RUN pip install -r requirements.txt
 ---> Using cache
 ---> 3915127d3d58
Step 11/11 : COPY . /code/
 ---> Using cache
 ---> de872685c733
Successfully built de872685c733
Successfully tagged djangoproject_web:latest
'''
</code>```

but when i run compose up.. i see below error.

```<code>'''
$ docker-compose up
Creating djangoproject_web_1 ... done
Attaching to djangoproject_web_1
web_1  | Watching for file changes with StatReloader
web_1  | Performing system checks...
web_1  |
web_1  | System check identified no issues (0 silenced).
web_1  |
web_1  | You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
web_1  | Run 'python manage.py migrate' to apply them.
web_1  | July 23, 2019 - 03:21:21
web_1  | Django version 2.2.3, using settings 'composeexample.settings'
web_1  | Starting development server at http://case.xxxxxx.com:8000/
web_1  | Quit the server with CONTROL-C.
web_1  | Error: [Errno -2] Name or service not known
djangoproject_web_1 exited with code 1
'''
</code>```

and if i try this

```<code>'''
docker-compose run web django-admin startproject composeexample .
'''
</code>```

it says

```<code>'''
CommandError: /code/manage.py already exists, overlaying a project or app into an existing directory won't replace conflicting files
'''
</code>```

my Dockerfile is

```<code>'''
FROM python:3
ENV PYTHONUNBUFFERED 1
RUN apt-get update -y
RUN apt-get install -y unixodbc unixodbc-dev
RUN easy_install pip
RUN mkdir /code
WORKDIR /code
RUN pip uninstall django
COPY requirements.txt /code/
RUN pip install -r requirements.txt
COPY . /code/
'''
</code>```

my docker-compose.yml is
'''
    version: '3'

```<code>services:
  web:
    build: .
    command: python manage.py runserver case.xxxxxx.com:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
</code>```

'''
How can i fix the problem with composeexample? it is not even created (cause i can't see it in the folder).. your advice please.

答:
You are probably using the docker client of Ubuntu Windows Subsystem. This gives issues with Volume feature of docker.
Run the docker run command on windows powershell and this issue will not come.

Body:
I'm trying to run linux docker on windows and getting this error.

build was fine.

'''
$ docker-compose build
Building web
Step 1/11 : FROM python:3
 ---> 42d620af35be
Step 2/11 : ENV PYTHONUNBUFFERED 1
 ---> Using cache
 ---> b43065732d6e
Step 3/11 : RUN apt-get update -y
 ---> Using cache
 ---> 6f65e0da9e14
Step 4/11 : RUN apt-get install -y unixodbc unixodbc-dev
 ---> Using cache
 ---> 2a9d7445a991
Step 5/11 : RUN easy_install pip
 ---> Using cache
 ---> 5994e6452e09
Step 6/11 : RUN mkdir /code
 ---> Using cache
 ---> d0eaa870fb98
Step 7/11 : WORKDIR /code
 ---> Using cache
 ---> af78d4b35f26
Step 8/11 : RUN pip uninstall django
 ---> Using cache
 ---> 92f983bfef88
Step 9/11 : COPY requirements.txt /code/
 ---> Using cache
 ---> 3c0031987286
Step 10/11 : RUN pip install -r requirements.txt
 ---> Using cache
 ---> 3915127d3d58
Step 11/11 : COPY . /code/
 ---> Using cache
 ---> de872685c733
Successfully built de872685c733
Successfully tagged djangoproject_web:latest
'''

but when i run compose up.. i see below error.

'''
$ docker-compose up
Creating djangoproject_web_1 ... done
Attaching to djangoproject_web_1
web_1  | Watching for file changes with StatReloader
web_1  | Performing system checks...
web_1  |
web_1  | System check identified no issues (0 silenced).
web_1  |
web_1  | You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
web_1  | Run 'python manage.py migrate' to apply them.
web_1  | July 23, 2019 - 03:21:21
web_1  | Django version 2.2.3, using settings 'composeexample.settings'
web_1  | Starting development server at http://case.xxxxxx.com:8000/
web_1  | Quit the server with CONTROL-C.
web_1  | Error: [Errno -2] Name or service not known
djangoproject_web_1 exited with code 1
'''

and if i try this

'''
docker-compose run web django-admin startproject composeexample .
'''

it says

'''
CommandError: /code/manage.py already exists, overlaying a project or app into an existing directory won't replace conflicting files
'''

my Dockerfile is

'''
FROM python:3
ENV PYTHONUNBUFFERED 1
RUN apt-get update -y
RUN apt-get install -y unixodbc unixodbc-dev
RUN easy_install pip
RUN mkdir /code
WORKDIR /code
RUN pip uninstall django
COPY requirements.txt /code/
RUN pip install -r requirements.txt
COPY . /code/
'''

my docker-compose.yml is
'''
    version: '3'

services:
  web:
    build: .
    command: python manage.py runserver case.xxxxxx.com:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"

'''
How can i fix the problem with composeexample? it is not even created (cause i can't see it in the folder).. your advice please.


问:
Pandas: Multiline data schema to single line
I have a big (huge) dataset that have the next schema:

```<code>dt | id | val_t | val
1  |  1 |     1 | 123
1  |  1 |     2 | 145
1  |  1 |     3 | 234
1  |  2 |     1 | 234
1  |  2 |     2 | 433
1  |  2 |     3 | 453
..................
N  |  X |     1 | 652
N  |  X |     2 | 543
N  |  X |     3 | 324
</code>```

and for many reasons, one of them the to reduce the size, I want to transform it to the next schema:

```<code>dt | id | val_1 | val_2 | val_3
1  |  1 |   123 |  145  |  234
1  |  2 |   234 |  433  |  453
..................
N  |  X |   652 |  543  |  324
</code>```

I tried grouping by ['dt', 'id'] and then iterating over each group to build the new rows but it is too slow. I'm not figuring out a way without iterating over every original row. Any idea?

答:
Use, the combination of df.pop, df.unstack, MultiIndex.droplevel, df.rename_axis:

```<code>df['temp'] = 'val_'
df['val_t'] = df.pop('temp') + df['val_t'].astype(str)
df = df.set_index(['dt', 'id', 'val_t']).unstack()
df.columns = df.columns.droplevel()
df = df.rename_axis(columns=None).reset_index()
</code>```

Result:

```<code># print(df)
  dt id  val_1  val_2  val_3
0  1  1    123    145    234
1  1  2    234    433    453
2  N  X    652    543    324
</code>```

Body:
I have a big (huge) dataset that have the next schema:

dt | id | val_t | val
1  |  1 |     1 | 123
1  |  1 |     2 | 145
1  |  1 |     3 | 234
1  |  2 |     1 | 234
1  |  2 |     2 | 433
1  |  2 |     3 | 453
..................
N  |  X |     1 | 652
N  |  X |     2 | 543
N  |  X |     3 | 324

and for many reasons, one of them the to reduce the size, I want to transform it to the next schema:

dt | id | val_1 | val_2 | val_3
1  |  1 |   123 |  145  |  234
1  |  2 |   234 |  433  |  453
..................
N  |  X |   652 |  543  |  324

I tried grouping by ['dt', 'id'] and then iterating over each group to build the new rows but it is too slow. I'm not figuring out a way without iterating over every original row. Any idea?

Body:
Use, the combination of df.pop, df.unstack, MultiIndex.droplevel, df.rename_axis:

df['temp'] = 'val_'
df['val_t'] = df.pop('temp') + df['val_t'].astype(str)
df = df.set_index(['dt', 'id', 'val_t']).unstack()
df.columns = df.columns.droplevel()
df = df.rename_axis(columns=None).reset_index()

Result:

# print(df)
  dt id  val_1  val_2  val_3
0  1  1    123    145    234
1  1  2    234    433    453
2  N  X    652    543    324


问:
Jenkins JUnit Test Result Report plugin states 4 test report file(s) were found with the pattern '**/unit-tests.xml'?

INFO: Starting to record.
  INFO: Processing JUnit
  INFO: [JUnit] - 4 test report file(s) were found with the pattern '**/unit-tests.xml' relative to 'E:\Jenkins-ws{foldername}' for the testing framework 'JUnit'.

I'm getting above message while processing JUnit in Jenkins. My tests are succeeded and jenkins getting failed due to this issue. Here is my karma.config file.

```<code>basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
  require('karma-jasmine'),
  require('karma-chrome-launcher'),
  require('karma-jasmine-html-reporter'),
  require('karma-coverage-istanbul-reporter'),
  require('@angular-devkit/build-angular/plugins/karma'),
  require('karma-junit-reporter')
],
client: {
  clearContext: false // leave Jasmine Spec Runner output visible in browser
},
junitReporter: {
        outputDir: "test-results",
        outputFile: "unit-tests.xml"
},
coverageIstanbulReporter: {
  dir: require('path').join(__dirname, '../coverage'),
  reports: ['html', 'lcovonly'],
  fixWebpackSourcePaths: true
},
reporters: ['progress', 'junit', 'kjhtml'],
</code>```

答:
The issue was with the pattern I have given in CI script

```<code>xunit([JUnit(deleteOutputFiles: true, failIfNotNew: true, pattern: '**/unit-tests.xml', skipNoTestFiles: false, stopProcessingIfError: true)])
</code>```

We have four different Angular projects and each project has unit-tests.xml file. I have renamed the file and updated CI script like below.

```<code> xunit([JUnit(deleteOutputFiles: true, failIfNotNew: true, pattern: '**/unit-tests-project1.xml', skipNoTestFiles: false, stopProcessingIfError: true)])
</code>```

Now, only one file is there in the folder with that name and test is successfull.

Body:
INFO: Starting to record.
  INFO: Processing JUnit
  INFO: [JUnit] - 4 test report file(s) were found with the pattern '**/unit-tests.xml' relative to 'E:\Jenkins-ws{foldername}' for the testing framework 'JUnit'.

I'm getting above message while processing JUnit in Jenkins. My tests are succeeded and jenkins getting failed due to this issue. Here is my karma.config file.

basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
  require('karma-jasmine'),
  require('karma-chrome-launcher'),
  require('karma-jasmine-html-reporter'),
  require('karma-coverage-istanbul-reporter'),
  require('@angular-devkit/build-angular/plugins/karma'),
  require('karma-junit-reporter')
],
client: {
  clearContext: false // leave Jasmine Spec Runner output visible in browser
},
junitReporter: {
        outputDir: "test-results",
        outputFile: "unit-tests.xml"
},
coverageIstanbulReporter: {
  dir: require('path').join(__dirname, '../coverage'),
  reports: ['html', 'lcovonly'],
  fixWebpackSourcePaths: true
},
reporters: ['progress', 'junit', 'kjhtml'],

Body:
The issue was with the pattern I have given in CI script

xunit([JUnit(deleteOutputFiles: true, failIfNotNew: true, pattern: '**/unit-tests.xml', skipNoTestFiles: false, stopProcessingIfError: true)])

We have four different Angular projects and each project has unit-tests.xml file. I have renamed the file and updated CI script like below.

 xunit([JUnit(deleteOutputFiles: true, failIfNotNew: true, pattern: '**/unit-tests-project1.xml', skipNoTestFiles: false, stopProcessingIfError: true)])

Now, only one file is there in the folder with that name and test is successfull.


问:
Prevent to hide showModalBottomSheet from outside touch
Is it possible to prevent ModalBottomSheet to hide from outside touch? Like in showDialog() we can use barrierDismissible property to prevent dialog from closing on outside touch

答:
you can use isDismissible: false and enableDrag: false like this

```<code>showModalBottomSheet(
      isDismissible: false,
      enableDrag: false,

      builder: (context) {
        return Container(
         height: 100.0
       )
      }
  );
</code>```

Body:
you can use isDismissible: false and enableDrag: false like this

showModalBottomSheet(
      isDismissible: false,
      enableDrag: false,

      builder: (context) {
        return Container(
         height: 100.0
       )
      }
  );


问:
Copying from one stream to another?
For work, the specification on my project is to use .Net 2.0 so I don't get the handy CopyTo function brought about later on.

I need to copy the response stream from an HttpWebResponse to another stream (most likely a MemoryStream, but it could be any subclass of Stream). My normal tactic has been something along the lines of:

```<code>BufferedStream bufferedresponse = new BufferedStream(HttpResponse.GetResponseStream());
int count = 0;
byte[] buffer = new byte[1024];
do {
    count = bufferedresponse.Read(buffer, 0, buffer.Length);
    target.Write(buffer, 0, count);
} while (count > 0);
bufferedresponse.Close();
</code>```

Are there more efficient ways to do this? Does the size of the buffer really matter? What is the best way to copy from one stream to another in .Net 2.0?

P.S. This is for downloading large, 200+ MB GIS tif images. Of course reliability is paramount.

答:
You can get rid of the BufferedStream, it's only useful if you are reading small chunks of the stream. Just get the response stream in a variable and use that:

```<code>Stream response = HttpResponse.GetResponseStream();
</code>```

A buffer that is too small will reduce the performance. You can use a larger buffer, so that at least the data from an entire IP packet fits. I looked around a bit, and 4096 bytes should be enough for that. You can really use any size up to 85 kb, after that it's allocated in the large objects heap, which you should avoid to do when there is no reason for it.

Other than that, it's about as efficient as it gets.

Title: Copying from one stream to another?

Body:
For work, the specification on my project is to use .Net 2.0 so I don't get the handy CopyTo function brought about later on.

I need to copy the response stream from an HttpWebResponse to another stream (most likely a MemoryStream, but it could be any subclass of Stream). My normal tactic has been something along the lines of:

BufferedStream bufferedresponse = new BufferedStream(HttpResponse.GetResponseStream());
int count = 0;
byte[] buffer = new byte[1024];
do {
    count = bufferedresponse.Read(buffer, 0, buffer.Length);
    target.Write(buffer, 0, count);
} while (count > 0);
bufferedresponse.Close();

Are there more efficient ways to do this? Does the size of the buffer really matter? What is the best way to copy from one stream to another in .Net 2.0?

P.S. This is for downloading large, 200+ MB GIS tif images. Of course reliability is paramount.

Body:
You can get rid of the BufferedStream, it's only useful if you are reading small chunks of the stream. Just get the response stream in a variable and use that:

Stream response = HttpResponse.GetResponseStream();

A buffer that is too small will reduce the performance. You can use a larger buffer, so that at least the data from an entire IP packet fits. I looked around a bit, and 4096 bytes should be enough for that. You can really use any size up to 85 kb, after that it's allocated in the large objects heap, which you should avoid to do when there is no reason for it.

Other than that, it's about as efficient as it gets.


问:
Is there a C# type for representing an integer Range?
I have a need to store an integer range. Is there an existing type for that in C# 4.0?

Of course, I could write my own class with int From and int To properties and build in proper logic to ensure that From <= To. But if a type already exists, I'd of course rather use that.

答:
There is a Enumerable.Range method but this one accepts start and count as its parameter. In order for it to work as what you want start and end, the end formula would be end - start + 1

Usage:

Enumerable.Range(start, end - start + 1).ToList()


问:
Oracle: Why do I have to use TO_DATE to pull my data?
When trying to filter on EXPIRE_DATE, it seems I have to use TO_DATE. Why do I have to use TO_DATE? The EXPIRE_DATE data type in the database is ALREADY set to date. Here is the code that works.

```<code>SELECT * FROM MY_TABLE
  WHERE EXPIRE_DATE >= TO_DATE('2020/01/13','yyyy/mm/dd')
  AND EXPIRE_DATE <= TO_DATE('2020/04/19','yyyy/mm/dd')
</code>```

I tried to use BETWEEN without TO_DATE and just use my dates but I received an error.

To recap, even though the data type for this is ALREADY date, it seems I have to use TO_DATE to pull my data when I want to filter. Is there something I am missing? Here is my error when I try filter my data without using TO_DATE.

答:
Apart from some good answers here, I would like to tell you that you do not need TO_DATE to pull the data from your table.

You need to_date or date literal to convert the normal string to date which can be compared to the column data in your table, As the date column must be compared with the date data type variable/constant.

To convert normal string to date, You can use the following:

```<code>TO_DATE('2020/01/13','yyyy/mm/dd')
DATE '2020-01-13'
</code>```

I would not recommend using NLS_DATE_FORMAT just for creating the date.

Body:
When trying to filter on EXPIRE_DATE, it seems I have to use TO_DATE. Why do I have to use TO_DATE? The EXPIRE_DATE data type in the database is ALREADY set to date. Here is the code that works.

SELECT * FROM MY_TABLE
  WHERE EXPIRE_DATE >= TO_DATE('2020/01/13','yyyy/mm/dd')
  AND EXPIRE_DATE <= TO_DATE('2020/04/19','yyyy/mm/dd')

I tried to use BETWEEN without TO_DATE and just use my dates but I received an error.

To recap, even though the data type for this is ALREADY date, it seems I have to use TO_DATE to pull my data when I want to filter. Is there something I am missing? Here is my error when I try filter my data without using TO_DATE.

Body:
Apart from some good answers here, I would like to tell you that you do not need TO_DATE to pull the data from your table.

You need to_date or date literal to convert the normal string to date which can be compared to the column data in your table, As the date column must be compared with the date data type variable/constant.

To convert normal string to date, You can use the following:

TO_DATE('2020/01/13','yyyy/mm/dd')
DATE '2020-01-13'

I would not recommend using NLS_DATE_FORMAT just for creating the date.


问:
Sum of an array in which the array is a property of a property in the outer object
```<code>{
    'Edsger W. Dijkstra': [ // o
      { author: 'Edsger W. Dijkstra', likes: 5 },
      { author: 'Edsger W. Dijkstra', likes: 10 }
    ],
    'Benizio Mauritez': [
      { author: 'Benizio Mauritez', likes: 12 },
      { author: 'Benizio Mauritez', likes: 8 }
    ]
  }
</code>```

I have this object which in this case, represents users from a blog in which, I am trying to merge a single author with their total likes already merged, e.g:

```<code>{
    [
        author: Edsger W. Dijkstra,
        likes: 15
    ],
    [
        author: Benizio Mauritez,
        likes: 20
    ],
}
</code>```

How can I do this? I've already trying reducing their props (Got stucked at re-assigning or creating a new prop out of that), tried lodash's sumBy function so if someone can enlight me on how to do this, I would be very much appreciating it!, many thanks
!

答:
Iterate the object with _.map(), use the key (2nd param) as the author. Get the likes by getting the sum of the likes using _.sumBy():

const obj = {"Edsger W. Dijkstra":[{"author":"Edsger W. Dijkstra","likes":5},{"author":"Edsger W. Dijkstra","likes":10}],"Benizio Mauritez":[{"author":"Benizio Mauritez","likes":12},{"author":"Benizio Mauritez","likes":8}]}

const result = _.map(obj, (v, author) => ({
  author,
  likes: _.sumBy(v, 'likes')
}))

console.log(result)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script></code>```

Body:
{
    'Edsger W. Dijkstra': [ // o
      { author: 'Edsger W. Dijkstra', likes: 5 },
      { author: 'Edsger W. Dijkstra', likes: 10 }
    ],
    'Benizio Mauritez': [
      { author: 'Benizio Mauritez', likes: 12 },
      { author: 'Benizio Mauritez', likes: 8 }
    ]
  }

I have this object which in this case, represents users from a blog in which, I am trying to merge a single author with their total likes already merged, e.g:

{
    [
        author: Edsger W. Dijkstra,
        likes: 15
    ],
    [
        author: Benizio Mauritez,
        likes: 20
    ],
}

How can I do this? I've already trying reducing their props (Got stucked at re-assigning or creating a new prop out of that), tried lodash's sumBy function so if someone can enlight me on how to do this, I would be very much appreciating it!, many thanks
!

Body:
Iterate the object with _.map(), use the key (2nd param) as the author. Get the likes by getting the sum of the likes using _.sumBy():

const obj = {"Edsger W. Dijkstra":[{"author":"Edsger W. Dijkstra","likes":5},{"author":"Edsger W. Dijkstra","likes":10}],"Benizio Mauritez":[{"author":"Benizio Mauritez","likes":12},{"author":"Benizio Mauritez","likes":8}]}

const result = _.map(obj, (v, author) => ({
  author,
  likes: _.sumBy(v, 'likes')
}))

console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>


问:
Django: Attempting to create custom 2 password confirmation in my registration form. Form is not valid?
my name is Paul, I am an early high school beginner working on my first "independent" project. "Independent" meaning without tutorial guidance. My goal is to make a calendar website, just to keep track of a list of events such as homework, meetings, and such.

Currently, I am working on the registration form. At first, I used the built in UserCreationForm but I decided to create my own HTML form. I am working on recreating this 2 password confirmation form which would take in the two inputs, make sure there aren't any forbidden keys, make sure that the two passwords are matching, and then save that password into the User model's password, along with a username, first_name, and last_name(this would happen in my view.py file).

When I first tried registering, nothing would pop up and as I checked the admin page it turns out no new Users were made. So I put up messages throughout my view if statements to see where the code was getting cut off. It turns out that the form.is_valid was returning false, and I'm not too sure why.

I want to believe it may be that my HTML form inputs do not match my forms.py fields, but I need assistance on fixing this. Any help would be greatly appreciated.

This is my form.py file.

```<code>from django import forms
from django.contrib.auth.models import User

class UserRegisterForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'password']
</code>```

This is the register.html file, the form in which the inputs of the two passwords are. This form is extended to another base template.

```<code><form method="POST">
    {% csrf_token %}
    <div>
        <label for="id_username">Username: </label>
        <div>
            <input id="id_username" type="text" name="username">
        </div>
    </div>
    <div>
        <label for="id_first_name">First Name: </label>
        <div>
            <input id="id_first_name" type="text" name="first_name">
        </div>
    </div>
    <div>
        <label for="id_last_name">Last Name: </label>
        <div>
            <input id="id_last_name" type="text" name="last_name">
        </div>
    </div>
    <div>
        <label for="id_password1">Password: </label>
        <div>
            <input id="id_password1" type="password" name="password1">
        </div>
    </div>
    <div>
        <label for="id_password2">Password Confirmation: </label>
        <div>
            <input id="id_password2" type="password" name="password2">
        </div>
    </div>
    <button type="submit">Register</button>
    <div>
        <small>Already Have An Account? <a href="{% url 'login' %}">Login</a></small>
    </div>
    {% if messages %}
    {% for message in messages %}
    <div role="alert">
        {{ message }}
    </div>
    {% endfor %}
    {% endif %}
</form>
</code>```

And this is my views.py file, where I am attempting to verify that the two passwords fit the criteria and then save it to the User model.

```<code>from django.shortcuts import render, redirect
from .forms import UserRegisterForm
from django.contrib.auth.decorators import login_required
from django.contrib import messages

def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            password1 = request.POST.get('password1')
            password2 = request.POST.get('password2')
            keys = {'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'h', 'H', 'i', 'I', 'j', 'J',
                    'k', 'K', 'l', 'L', 'm', 'M', 'n', 'N', 'o', 'O', 'p', 'P', 'q', 'Q', 'r', 'R', 's', 'S', 't', 'T',
                    'u', 'U', 'v', 'V', 'w', 'W', 'x', 'X', 'y', 'Y', 'z', 'Z', '1', '2', '3', '4', '5', '6', '7', '8',
                    '9', '0', '-', '_', '.'}
            for key in keys:
                if key not in password1:
                    if password1 == password2:
                        form.instance.password = password1
                        form.save()

                        messages.success(request, 'User has been saved.')
                        return redirect('login')
                    else:
                        messages.error(request, 'Passwords do not match.')
                        return redirect('register')
                else:
                    messages.error(request, 'Password contains illegal keys.')
                    return redirect('register')
        else:
            messages.error(request, 'Form is not valid.')
    else:
        messages.error(request, 'request method is not POST.')
        form = UserRegisterForm()

    return render(request, 'User/register.html', {'form': form})
</code>```

At the very last if statement, I'm not sure how to save the password into the form to make a User. Thank you for your time, and absolutely any help would be greatly appreciated.

答:
You need to validate and get the password in form.py.

form.py

```<code>class UserRegisterForm(forms.ModelForm):
"""
New User Form. Requires password confirmation.
"""
password1 = forms.CharField(
    label='Password', widget=forms.PasswordInput
)
password2 = forms.CharField(
    label='Confirm password', widget=forms.PasswordInput
)

class Meta:
    model = User
    fields = ['username', 'first_name', 'last_name', 'password']

# to make sure the password and the confirm password are equal
def clean_password2(self):
    # Check that the two password entries match
    password1 = self.cleaned_data.get("password1")
    password2 = self.cleaned_data.get("password2")
    if password1 and password2 and password1 != password2:
        raise forms.ValidationError("Passwords do not match")
    return password2

# to make sure the added detail of the user in form is saved in database
def save(self, commit=True):
    # Save the provided password in hashed format
    user = super().save(commit=False)
    user.set_password(self.cleaned_data["password1"])
    if commit:
        user.save()

    return user
</code>```

view.py

```<code>def register(request):
form = UserRegisterForm(request.POST)

# if the data provided in the form is valid than save the form
if form.is_valid():
    user = form.save(commit=False)
    user = form.save()
    raw_password = form.cleaned_data.get('password1')

    user = authenticate(request, email=user.email, password=raw_password)

    if user is not None:
        login(request, user)
    return redirect('login')

return render(request, 'User/register.html', {'form': form})
</code>```

Hope this gets you some idea on how the password confirmation works.

Body:
my name is Paul, I am an early high school beginner working on my first "independent" project. "Independent" meaning without tutorial guidance. My goal is to make a calendar website, just to keep track of a list of events such as homework, meetings, and such.

Currently, I am working on the registration form. At first, I used the built in UserCreationForm but I decided to create my own HTML form. I am working on recreating this 2 password confirmation form which would take in the two inputs, make sure there aren't any forbidden keys, make sure that the two passwords are matching, and then save that password into the User model's password, along with a username, first_name, and last_name(this would happen in my view.py file).

When I first tried registering, nothing would pop up and as I checked the admin page it turns out no new Users were made. So I put up messages throughout my view if statements to see where the code was getting cut off. It turns out that the form.is_valid was returning false, and I'm not too sure why.

I want to believe it may be that my HTML form inputs do not match my forms.py fields, but I need assistance on fixing this. Any help would be greatly appreciated.

This is my form.py file.

from django import forms
from django.contrib.auth.models import User

class UserRegisterForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'password']

This is the register.html file, the form in which the inputs of the two passwords are. This form is extended to another base template.

<form method="POST">
    {% csrf_token %}

        Username:

            <input id="id_username" type="text" name="username">

        First Name:

            <input id="id_first_name" type="text" name="first_name">

        Last Name:

            <input id="id_last_name" type="text" name="last_name">

        Password:

            <input id="id_password1" type="password" name="password1">

        Password Confirmation:

            <input id="id_password2" type="password" name="password2">

    <button type="submit">Register</button>

        Already Have An Account? Login

    {% if messages %}
    {% for message in messages %}

        {{ message }}

    {% endfor %}
    {% endif %}
</form>

And this is my views.py file, where I am attempting to verify that the two passwords fit the criteria and then save it to the User model.

from django.shortcuts import render, redirect
from .forms import UserRegisterForm
from django.contrib.auth.decorators import login_required
from django.contrib import messages

def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            password1 = request.POST.get('password1')
            password2 = request.POST.get('password2')
            keys = {'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'h', 'H', 'i', 'I', 'j', 'J',
                    'k', 'K', 'l', 'L', 'm', 'M', 'n', 'N', 'o', 'O', 'p', 'P', 'q', 'Q', 'r', 'R', 's', 'S', 't', 'T',
                    'u', 'U', 'v', 'V', 'w', 'W', 'x', 'X', 'y', 'Y', 'z', 'Z', '1', '2', '3', '4', '5', '6', '7', '8',
                    '9', '0', '-', '_', '.'}
            for key in keys:
                if key not in password1:
                    if password1 == password2:
                        form.instance.password = password1
                        form.save()

                        messages.success(request, 'User has been saved.')
                        return redirect('login')
                    else:
                        messages.error(request, 'Passwords do not match.')
                        return redirect('register')
                else:
                    messages.error(request, 'Password contains illegal keys.')
                    return redirect('register')
        else:
            messages.error(request, 'Form is not valid.')
    else:
        messages.error(request, 'request method is not POST.')
        form = UserRegisterForm()

    return render(request, 'User/register.html', {'form': form})

At the very last if statement, I'm not sure how to save the password into the form to make a User. Thank you for your time, and absolutely any help would be greatly appreciated.

Body:
You need to validate and get the password in form.py.

form.py

class UserRegisterForm(forms.ModelForm):
"""
New User Form. Requires password confirmation.
"""
password1 = forms.CharField(
    label='Password', widget=forms.PasswordInput
)
password2 = forms.CharField(
    label='Confirm password', widget=forms.PasswordInput
)

class Meta:
    model = User
    fields = ['username', 'first_name', 'last_name', 'password']

# to make sure the password and the confirm password are equal
def clean_password2(self):
    # Check that the two password entries match
    password1 = self.cleaned_data.get("password1")
    password2 = self.cleaned_data.get("password2")
    if password1 and password2 and password1 != password2:
        raise forms.ValidationError("Passwords do not match")
    return password2

# to make sure the added detail of the user in form is saved in database
def save(self, commit=True):
    # Save the provided password in hashed format
    user = super().save(commit=False)
    user.set_password(self.cleaned_data["password1"])
    if commit:
        user.save()

    return user

view.py

def register(request):
form = UserRegisterForm(request.POST)

# if the data provided in the form is valid than save the form
if form.is_valid():
    user = form.save(commit=False)
    user = form.save()
    raw_password = form.cleaned_data.get('password1')

    user = authenticate(request, email=user.email, password=raw_password)

    if user is not None:
        login(request, user)
    return redirect('login')

return render(request, 'User/register.html', {'form': form})

Hope this gets you some idea on how the password confirmation works.


问:
how can I balance these brackets in this recursive function?
I'm trying to write a recursive Python function to get all of the successive 1 or 2 digit orderings from a given number.  For example, given 123, the result would be: [[1, 2, 3], [12, 3], [1, 23]].

I've written a function that seems to be on the right track but I can't balance the brackets.

```<code>def gen_codes(num):

    if len(str(num)) == 1:
        return [[num]]
    result = []
    for i in range(1, 3):
        rest_str = str(num)[i:]
        path = [int(str(num)[0:i])]
        if len(rest_str):
            path = [path + x for x in gen_codes(int(rest_str))]
        result.append(path)
    return result

print(gen_codes(123))
</code>```

This outputs:

```<code>[[[1, [2, 3]], [1, 23]], [[12, 3]]]
</code>```

Expected:

```<code>[[1, 2, 3], [12, 3], [1, 23]]
</code>```

答:
There's probably far more performant ways to write this, but here is the first one I thought of:

```<code>def f(s: str) -> List[List[int]]:
    if len(s) == 1:
        return [[int(s)]]
    if len(s) == 2:
        return [[int(s[0]), int(s[1])], [int(s)]]
    return (
        [[int(s[0]), *xs] for xs in f(s[1:])] +
        [[int(s[0:2]), *xs] for xs in f(s[2:])]
    )
</code>```

Two base cases:

if s == "a", return [a]

if s == "ab", return [a, b] and [ab]

For all other strings,

if s == "ab[...]", return [a, *xs] for xs in f(b[...]) and [ab, *xs] for xs in f([...])

One key idea is to consistently operate within the correct (monadic) context. And that is always List[List[int]]. If you ever return anything else, you're doing something wrong.

Body:
I'm trying to write a recursive Python function to get all of the successive 1 or 2 digit orderings from a given number.  For example, given 123, the result would be: [[1, 2, 3], [12, 3], [1, 23]].

I've written a function that seems to be on the right track but I can't balance the brackets.

def gen_codes(num):

    if len(str(num)) == 1:
        return [[num]]
    result = []
    for i in range(1, 3):
        rest_str = str(num)[i:]
        path = [int(str(num)[0:i])]
        if len(rest_str):
            path = [path + x for x in gen_codes(int(rest_str))]
        result.append(path)
    return result

print(gen_codes(123))

This outputs:

[[[1, [2, 3]], [1, 23]], [[12, 3]]]

Expected:

[[1, 2, 3], [12, 3], [1, 23]]

Body:
There's probably far more performant ways to write this, but here is the first one I thought of:

def f(s: str) -> List[List[int]]:
    if len(s) == 1:
        return [[int(s)]]
    if len(s) == 2:
        return [[int(s[0]), int(s[1])], [int(s)]]
    return (
        [[int(s[0]), *xs] for xs in f(s[1:])] +
        [[int(s[0:2]), *xs] for xs in f(s[2:])]
    )

Two base cases:

if s == "a", return [a]

if s == "ab", return [a, b] and [ab]

For all other strings,

if s == "ab[...]", return [a, *xs] for xs in f(b[...]) and [ab, *xs] for xs in f([...])

One key idea is to consistently operate within the correct (monadic) context. And that is always List[List[int]]. If you ever return anything else, you're doing something wrong.


问:
Django Models (1054, "Unknown column in 'field list'")
No idea why this error is popping up. Here are the models I created -

```<code>from django.db import models
from django.contrib.auth.models import User

class Shows(models.Model):
    showid= models.CharField(max_length=10, unique=True, db_index=True)
    name  = models.CharField(max_length=256, db_index=True)
    aka   = models.CharField(max_length=256, db_index=True)
    score = models.FloatField()

class UserShow(models.Model):
    user  = models.ForeignKey(User)
    show  = models.ForeignKey(Shows)
</code>```

Here is the view from which I access these models -

```<code>from django.http import HttpResponse
from django.template import Context
from django.template.loader import get_template
from django.http import HttpResponse, Http404
from django.contrib.auth.models import User

def user_page(request, username):
    try:
        user = User.objects.get(username=username)
    except:
        raise Http404('Requested user not found.')

    shows     = user.usershow_set.all()
    template  = get_template('user_page.html')
    variables = Context({
        'username': username,
        'shows'   : shows})
    output = template.render(variables)
    return HttpResponse(output)
</code>```

At this point I get an error -

OperationalError: (1054, "Unknown column 'appname_usershow.show_id' in 'field list'")

As you see this column is not even present in my models? Why this error?

答:
I faced the same error like you posted above with MySQL database back-end, after long time of resolving this error, I ended up with below solution.

Manually added column to database through workbench with name exactly the same as it is shown in your error message.

After that run below command

```<code>python manage.py makemigrations
</code>```

Now migrations will be successfully created

After that run below command

```<code>python manage.py migrate --fake
</code>```

Now every thing works fine without any data lose issue

Body:
No idea why this error is popping up. Here are the models I created -

from django.db import models
from django.contrib.auth.models import User

class Shows(models.Model):
    showid= models.CharField(max_length=10, unique=True, db_index=True)
    name  = models.CharField(max_length=256, db_index=True)
    aka   = models.CharField(max_length=256, db_index=True)
    score = models.FloatField()

class UserShow(models.Model):
    user  = models.ForeignKey(User)
    show  = models.ForeignKey(Shows)

Here is the view from which I access these models -

from django.http import HttpResponse
from django.template import Context
from django.template.loader import get_template
from django.http import HttpResponse, Http404
from django.contrib.auth.models import User

def user_page(request, username):
    try:
        user = User.objects.get(username=username)
    except:
        raise Http404('Requested user not found.')

    shows     = user.usershow_set.all()
    template  = get_template('user_page.html')
    variables = Context({
        'username': username,
        'shows'   : shows})
    output = template.render(variables)
    return HttpResponse(output)

At this point I get an error -

OperationalError: (1054, "Unknown column 'appname_usershow.show_id' in 'field list'")

As you see this column is not even present in my models? Why this error?

Body:
I faced the same error like you posted above with MySQL database back-end, after long time of resolving this error, I ended up with below solution.

Manually added column to database through workbench with name exactly the same as it is shown in your error message.

After that run below command

python manage.py makemigrations

Now migrations will be successfully created

After that run below command

python manage.py migrate --fake

Now every thing works fine without any data lose issue


问:
Access LookUp table
i need to create a lookup table in Access, where all the abbreviations are related to a value, and if the abbreviation (in the main table) is null, then i want to show "Unknown"

i got the values working, but i can't seem to get the nulls to show up.

my lookup table looks like this:

```<code>REQUEST     REQUEST_TEXT
------------------------
A           Approve
D           Disapprove
NULL        N/A
</code>```

but when i do a count by request, it only shows me values for A and D, all though i know there are some blanks in there as well.

what am i doing wrong?

答:
This should be easier if you change tblLookup.

```<code>REQUEST     REQUEST_TEXT
------------------------
A           Approve
D           Disapprove
U           Unknown
</code>```

Then, in tblMain, change the REQUEST field to Required = True and Default Value = "U".  When new records are added, they will have U for REQUEST unless the user changes it to A or D.

Then a query which JOINs the 2 tables on REQUEST should get you what I think you want.

```<code>SELECT m.REQUEST, l.REQUEST_TEXT
FROM tblMain AS m
    INNER JOIN tblLookup AS l
    ON l.REQUEST = m.REQUEST;
</code>```

You should also create a relationship between the 2 tables, and select the option to enforce referential integrity in order to prevent the users from adding a spurious value such as "X" for REQUEST.

Edit:
If changing tblMain structure is off the table, and if you're doing this from within an Access session, you can use the Nz() function on a LEFT JOIN.

```<code>SELECT m.REQUEST, Nz(l.REQUEST_TEXT, "Unknown")
FROM tblMain AS m
    LEFT JOIN tblLookup AS l
    ON l.REQUEST = m.REQUEST;
</code>```

If you're doing this from outside an Access session, like from ASP, the Nz() function will not be available.  So you can substitute an IIf() expression for Nz().

```<code>SELECT m.REQUEST, IIf(l.REQUEST_TEXT Is Null, "Unknown", l.REQUEST_TEXT)
FROM tblMain AS m
    LEFT JOIN tblLookup AS l
    ON l.REQUEST = m.REQUEST;
</code>```

Edit2: You can't directly JOIN with Null values.  However with the "Unknown" row I suggested for tblLookup, you could use a JOIN which includes Nz for tblMain.REQUEST

```<code>SELECT m.id, m.request, l.request_text
FROM tblMain AS m
    INNER JOIN tblLookup AS l
    ON Nz(m.request,"U") = l.request;
</code>```

If you want to leave tblLookup REQUEST as Null for REQUEST_TEXT = Unknown,  I suppose you could use Nz on both sides of the JOIN expression.  However, this whole idea of joining Nulls makes me cringe.  I would fix the tables instead.

Title: Access LookUp table

Body:
i need to create a lookup table in Access, where all the abbreviations are related to a value, and if the abbreviation (in the main table) is null, then i want to show "Unknown"

i got the values working, but i can't seem to get the nulls to show up.

my lookup table looks like this:

REQUEST     REQUEST_TEXT
------------------------
A           Approve
D           Disapprove
NULL        N/A

but when i do a count by request, it only shows me values for A and D, all though i know there are some blanks in there as well.

what am i doing wrong?

Body:
This should be easier if you change tblLookup.

REQUEST     REQUEST_TEXT
------------------------
A           Approve
D           Disapprove
U           Unknown

Then, in tblMain, change the REQUEST field to Required = True and Default Value = "U".  When new records are added, they will have U for REQUEST unless the user changes it to A or D.

Then a query which JOINs the 2 tables on REQUEST should get you what I think you want.

SELECT m.REQUEST, l.REQUEST_TEXT
FROM tblMain AS m
    INNER JOIN tblLookup AS l
    ON l.REQUEST = m.REQUEST;

You should also create a relationship between the 2 tables, and select the option to enforce referential integrity in order to prevent the users from adding a spurious value such as "X" for REQUEST.

Edit:
If changing tblMain structure is off the table, and if you're doing this from within an Access session, you can use the Nz() function on a LEFT JOIN.

SELECT m.REQUEST, Nz(l.REQUEST_TEXT, "Unknown")
FROM tblMain AS m
    LEFT JOIN tblLookup AS l
    ON l.REQUEST = m.REQUEST;

If you're doing this from outside an Access session, like from ASP, the Nz() function will not be available.  So you can substitute an IIf() expression for Nz().

SELECT m.REQUEST, IIf(l.REQUEST_TEXT Is Null, "Unknown", l.REQUEST_TEXT)
FROM tblMain AS m
    LEFT JOIN tblLookup AS l
    ON l.REQUEST = m.REQUEST;

Edit2: You can't directly JOIN with Null values.  However with the "Unknown" row I suggested for tblLookup, you could use a JOIN which includes Nz for tblMain.REQUEST

SELECT m.id, m.request, l.request_text
FROM tblMain AS m
    INNER JOIN tblLookup AS l
    ON Nz(m.request,"U") = l.request;

If you want to leave tblLookup REQUEST as Null for REQUEST_TEXT = Unknown,  I suppose you could use Nz on both sides of the JOIN expression.  However, this whole idea of joining Nulls makes me cringe.  I would fix the tables instead.


问:
Google COLAB free version saving Keras trained model
I saved keras trained model in google colab free version

```<code> model.save("my_model.h5")
</code>```

i tried to retrieve model using below method

```<code>from keras.models import load_model
model = load_model('my_model.h5')
</code>```

But it is throwing errors

```<code>OSError: Unable to open file (unable to open file: name = 'my_model.h5', errno = 2, error message = 'No such file or directory', flags = 0, o_flags = 0)
</code>```

will i able to retrive saved model from free google colab version, can you any help on this
I checked similar question in stackoverflow, i think these answers belongs to colab pro version

Otherwise, do i have to save model in specific path to local drive while training?

答:
What is Problem

You are storing your model in runtime not in your google drive. After 12 hour runtime automatically deleted with data. So we have to save model in google drive.

How to store to Google Drive

First connect to google drive

from google.colab import drive
drive.mount('/content/drive')
```
<p>Now you will find file explorer at left side which has <code>drive</code> directory. When you go inside that directory, it will take you to google drive.</p>
<p>Suppose I want to put my data in drive <code>My Drive</code> then</p>
<pre class="lang-py prettyprint-override"><code>from keras.models import load_model

MODEL_PATH = './drive/My Drive/model.h5'

# Now save model in drive
model.save(MODEL_PATH)

# Load Model
model = load_model(MODEL_PATH)
</code>```

When you open your drive, you will find file model.h5 in drive.

Body:
I saved keras trained model in google colab free version

 model.save("my_model.h5")

i tried to retrieve model using below method

from keras.models import load_model
model = load_model('my_model.h5')

But it is throwing errors

OSError: Unable to open file (unable to open file: name = 'my_model.h5', errno = 2, error message = 'No such file or directory', flags = 0, o_flags = 0)

will i able to retrive saved model from free google colab version, can you any help on this
I checked similar question in stackoverflow, i think these answers belongs to colab pro version

Otherwise, do i have to save model in specific path to local drive while training?

Body:
What is Problem

You are storing your model in runtime not in your google drive. After 12 hour runtime automatically deleted with data. So we have to save model in google drive.

How to store to Google Drive

First connect to google drive

from google.colab import drive
drive.mount('/content/drive')

Now you will find file explorer at left side which has drive directory. When you go inside that directory, it will take you to google drive.

Suppose I want to put my data in drive My Drive then

from keras.models import load_model

MODEL_PATH = './drive/My Drive/model.h5'

# Now save model in drive
model.save(MODEL_PATH)

# Load Model
model = load_model(MODEL_PATH)

When you open your drive, you will find file model.h5 in drive.


问:
classifying multiple observations within one variable so then i can categorise them in new column . how can i make the code shorter? in R
i'm looking for a shortcut or less labour intensive way of grouping certain observations within the same variable, then output in a new column depending.

```<code>axa$type[axa$instrument_type == "CORPORATE BONDS" | axa$instrument_type == "GOVERNMENT BONDS"] <- 'BONDS'
axa$type[axa$instrument_type == "FOREIGN CURRENCY"] <- 'Cash'
axa$type[axa$instrument_type == "FUT-FIXED INCOME"] <- 'Derivatives'
axa$type[axa$instrument_type  ==  "INTEREST RATE SWAP"] <- 'Derivatives'
axa$type[axa$instrument_type == "MUTUAL FUNDS"] <- 'Funds'
axa$type[axa$instrument_type == "SHORT TERMS"] <- 'Cash Equivalent'
axa$type[axa$instrument_type == "CMO"] <- 'Other Fi'
axa$type[axa$instrument_type == "NON-SECY ASSET STOCK"] <- 'Other'
</code>```

the code searches for certain observations,then will output in column axa$type, with the desired output: "cash", "derivatives".

is there any way of making this code shorter/compact.
preferably using the Data table Package

答:
Not really shorter but using case_when from dplyr would make it cleaner and avoids writing dataframe_name$column_name every time. You can use %in% instead of | to compare multiple values in instrument_type.

```<code>library(dplyr)

axa %>%
   mutate(type = case_when(
      instrument_type %in% c("CORPORATE BONDS","GOVERNMENT BONDS") ~ "BONDS",
      instrument_type == "FOREIGN CURRENCY" ~ "Cash",
      instrument_type %in% c("FUT-FIXED INCOME", "INTEREST RATE SWAP") ~ "Derivatives",
      instrument_type == "MUTUAL FUNDS"~"Funds",
      instrument_type == "SHORT TERMS" ~ "Cash Equivalent",
      instrument_type == "CMO" ~"Other Fi",
      instrument_type == "NON-SECY ASSET STOCK" ~"Other"))
</code>```

If interested in data.table solution similar to case_when there is fcase in data.table which is available in development version of data.table.

Body:
i'm looking for a shortcut or less labour intensive way of grouping certain observations within the same variable, then output in a new column depending.

axa$type[axa$instrument_type == "CORPORATE BONDS" | axa$instrument_type == "GOVERNMENT BONDS"] <- 'BONDS'
axa$type[axa$instrument_type == "FOREIGN CURRENCY"] <- 'Cash'
axa$type[axa$instrument_type == "FUT-FIXED INCOME"] <- 'Derivatives'
axa$type[axa$instrument_type  ==  "INTEREST RATE SWAP"] <- 'Derivatives'
axa$type[axa$instrument_type == "MUTUAL FUNDS"] <- 'Funds'
axa$type[axa$instrument_type == "SHORT TERMS"] <- 'Cash Equivalent'
axa$type[axa$instrument_type == "CMO"] <- 'Other Fi'
axa$type[axa$instrument_type == "NON-SECY ASSET STOCK"] <- 'Other'

the code searches for certain observations,then will output in column axa$type, with the desired output: "cash", "derivatives".

is there any way of making this code shorter/compact.
preferably using the Data table Package

Body:
Not really shorter but using case_when from dplyr would make it cleaner and avoids writing dataframe_name$column_name every time. You can use %in% instead of | to compare multiple values in instrument_type.

library(dplyr)

axa %>%
   mutate(type = case_when(
      instrument_type %in% c("CORPORATE BONDS","GOVERNMENT BONDS") ~ "BONDS",
      instrument_type == "FOREIGN CURRENCY" ~ "Cash",
      instrument_type %in% c("FUT-FIXED INCOME", "INTEREST RATE SWAP") ~ "Derivatives",
      instrument_type == "MUTUAL FUNDS"~"Funds",
      instrument_type == "SHORT TERMS" ~ "Cash Equivalent",
      instrument_type == "CMO" ~"Other Fi",
      instrument_type == "NON-SECY ASSET STOCK" ~"Other"))

If interested in data.table solution similar to case_when there is fcase in data.table which is available in development version of data.table.