问:
Angular SVG text gets out of the view box
I am new to SVG and Im building some charts. I want to add some text on the top but it begins out of the view box. It seems like I could see the text if I scroll up but I am already on top of the page. It sounds stange but I hope it can be understood with the image:

I also attach the html code (as you can see the bottom part of the other texts is shown on the top, but just the bottom).

```<code> <svg  [attr.viewBox]="DIMENSIONES" [attr.font-size]="100000" >

    <!-- Cuadricula (x=ancho_izq + margen_izq_centro; y=alto_indices)-->
    <rect x="10000" y="1500" [attr.width] = "ancho_cuadricula"  [attr.height] = "alto_cuadricula" fill="none" stroke="black" stroke-width="350" />

    <!-- Todas las líneas -->
    <line *ngFor="let linea of lineasHorizontales"  [attr.x1]="linea.x1"  [attr.y1]="linea.y1" [attr.x2]="linea.x2"  [attr.y2]="linea.y2" stroke="black" stroke-width="50"/>

    <line *ngFor="let linea of lineasVerticales"  [attr.x1]="linea.x1"  [attr.y1]="linea.y1" [attr.x2]="linea.x2"  [attr.y2]="linea.y2" stroke="black" stroke-width="50"/>

    <!-- Índices (misma x que cuadrícula) -->
    <text x="10000" y="0" >0 1 2 3 4 </text>
    <text x="0" y="15" fill="red">I love SVG!</text>
    <text x="0" y="15" fill="red" transform="rotate(30 20,40)">I love SVG</text>

</svg>
</code>```

DIMENSIONES is the string "0 0 106400 76500" and linea is just a model with x1, y1, x2 and y2.

I have been changing the font-size and stuff but it does not work.

答: In case anyone has arrived here with the same issue, it seems as the y property refers to the bottom of the text and not to the top.</p>

Body:
I am new to SVG and Im building some charts. I want to add some text on the top but it begins out of the view box. It seems like I could see the text if I scroll up but I am already on top of the page. It sounds stange but I hope it can be understood with the image:

I also attach the html code (as you can see the bottom part of the other texts is shown on the top, but just the bottom).

 <svg  [attr.viewBox]="DIMENSIONES" [attr.font-size]="100000" >

    <rect x="10000" y="1500" [attr.width] = "ancho_cuadricula"  [attr.height] = "alto_cuadricula" fill="none" stroke="black" stroke-width="350" />

    <line *ngFor="let linea of lineasHorizontales"  [attr.x1]="linea.x1"  [attr.y1]="linea.y1" [attr.x2]="linea.x2"  [attr.y2]="linea.y2" stroke="black" stroke-width="50"/>

    <line *ngFor="let linea of lineasVerticales"  [attr.x1]="linea.x1"  [attr.y1]="linea.y1" [attr.x2]="linea.x2"  [attr.y2]="linea.y2" stroke="black" stroke-width="50"/>

    <text x="10000" y="0" >0 1 2 3 4 </text>
    <text x="0" y="15" fill="red">I love SVG!</text>
    <text x="0" y="15" fill="red" transform="rotate(30 20,40)">I love SVG</text>

</svg>

DIMENSIONES is the string "0 0 106400 76500" and linea is just a model with x1, y1, x2 and y2.

I have been changing the font-size and stuff but it does not work.


来源: stackexchange

问:
Remove characters from IP address
Thanks to @SantiagoSquarzon, I have a code which is comparing csv where few of the IP addresses are like 10.124.94.132 fe80::80fe:f4a7:b182:82e1

So when I am doing the comparison, it is returning wrong value.

below is my code

```<code>$CSV1 = Import-Csv -Path 'E:\IP_Details.csv'
$reference = [System.Collections.Generic.HashSet[string]]::new(
    [string[]](Import-Csv -Path 'E:\IP_Details_1.csv').'IP adress'.ForEach('Trim')
)

$results = foreach($line in $Csv1)
{
    $ip = $line.'IP adress'.Trim()
    [PSCustomObject]@{
        Value   = $ip
        IPName  = $line.IPName
        Results = ('Not Match', 'Match')[$reference.Contains($ip)]
    }
}

$results | Export-Csv -Path "E:\File.csv" -NoTypeInformation
</code>```

Please let me know how to remove the characters so that it should not affect the comparison.

答:
I think you have a combination of IPV4 and IPV6 addresses in there every now and then.

To exclude those in your comparison, I would do:

```<code>$Csv1      = Import-Csv -Path 'E:\IP_Details.csv'
# get an array of IPV4 addresses from the reference file
$reference = Import-Csv -Path 'E:\IP_Details_1.csv' | ForEach-Object {
                ([regex]'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}').Match($_.'IP adress').Value
             } | Sort-Object -Unique

$result = foreach($line in $Csv1) {
    # get the IPV4 address from the field
    $ip = ([regex]'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}').Match($line.'IP adress').Value
    [PSCustomObject]@{
        Value   = $ip
        IPName  = $line.IPName     # don't know what is in here..
        Results = $reference -contains $ip
    }
}

$result | Export-Csv -Path "E:\File.csv" -NoTypeInformation
</code>```

ContentLicense: CC BY-SA 4.0

Title: Remove characters from IP address

Body:
Thanks to @SantiagoSquarzon, I have a code which is comparing csv where few of the IP addresses are like 10.124.94.132 fe80::80fe:f4a7:b182:82e1

So when I am doing the comparison, it is returning wrong value.

below is my code

$CSV1 = Import-Csv -Path 'E:\IP_Details.csv'
$reference = [System.Collections.Generic.HashSet[string]]::new(
    [string[]](Import-Csv -Path 'E:\IP_Details_1.csv').'IP adress'.ForEach('Trim')
)

$results = foreach($line in $Csv1)
{
    $ip = $line.'IP adress'.Trim()
    [PSCustomObject]@{
        Value   = $ip
        IPName  = $line.IPName
        Results = ('Not Match', 'Match')[$reference.Contains($ip)]
    }
}

$results | Export-Csv -Path "E:\File.csv" -NoTypeInformation

Please let me know how to remove the characters so that it should not affect the comparison.

Body:
I think you have a combination of IPV4 and IPV6 addresses in there every now and then.

To exclude those in your comparison, I would do:

$Csv1      = Import-Csv -Path 'E:\IP_Details.csv'
# get an array of IPV4 addresses from the reference file
$reference = Import-Csv -Path 'E:\IP_Details_1.csv' | ForEach-Object {
                ([regex]'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}').Match($_.'IP adress').Value
             } | Sort-Object -Unique

$result = foreach($line in $Csv1) {
    # get the IPV4 address from the field
    $ip = ([regex]'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}').Match($line.'IP adress').Value
    [PSCustomObject]@{
        Value   = $ip
        IPName  = $line.IPName     # don't know what is in here..
        Results = $reference -contains $ip
    }
}

$result | Export-Csv -Path "E:\File.csv" -NoTypeInformation


问:
How can I download the Outlook mail by dragging it to PyQt5 area?
I am learning the drag and drop part of pyqt5.
Most files can know the path of the file when dragged to pyqt. However, the actual path cannot be found because the actual location of the Outlook mail exists in the .pst file. So, when dragging and dropping the Outlook mail to a specific layout in pyqt, I want to download the Outlook mail to a specific folder.

Is there a better way? Or can you give me advice?

Please Help me..!!
(I've been up all night for 3 days because of this problem)

This picture is what I want.

The code block in this part is empty, and I want to fill out the above.

```<code>    def dragMoveEvent(self, event):
        if event.mimeData().hasUrls() or event.mimeData().hasFormat("FileContents"):
            event.setDropAction(Qt.CopyAction)
            event.accept()
        else:
            event.ignore()

    def dropEvent(self, event):
        if event.mimeData().hasFormat("FileContents"):
            event.setDropAction(Qt.CopyAction)
            event.accept()
            print(event.mimeData().text())
</code>```

答:
When you try to drag and drop from Outlook, Outlook correctly identifies the format as virtual files (CFSTR_FILEDESCRIPTORW) since the files do not exist directly on disk. Instead, they are contained in a PST file, OST file, or on an Exchange server.

Read more about the drag and drop operations in Outlook in the following articles:

Drag-and-Drop Attached File From Outlook (97 and above) to C# Window Form

Outlook File Drag

Body:
I am learning the drag and drop part of pyqt5.
Most files can know the path of the file when dragged to pyqt. However, the actual path cannot be found because the actual location of the Outlook mail exists in the .pst file. So, when dragging and dropping the Outlook mail to a specific layout in pyqt, I want to download the Outlook mail to a specific folder.

Is there a better way? Or can you give me advice?

Please Help me..!!
(I've been up all night for 3 days because of this problem)

This picture is what I want.

The code block in this part is empty, and I want to fill out the above.

    def dragMoveEvent(self, event):
        if event.mimeData().hasUrls() or event.mimeData().hasFormat("FileContents"):
            event.setDropAction(Qt.CopyAction)
            event.accept()
        else:
            event.ignore()

    def dropEvent(self, event):
        if event.mimeData().hasFormat("FileContents"):
            event.setDropAction(Qt.CopyAction)
            event.accept()
            print(event.mimeData().text())


问:
How to write case in Switch else statement in javavscript?
//This is my Problem
Complete the getLetter(s) function in the editor. It has one parameter: a string, , consisting of lowercase English alphabetic letters (i.e., a through z). It must return A, B, C, or D depending on the following criteria:</p>
```<code>If the first character in string  is in the set {aeiou}, then return A.
If the first character in string  is in the set {bcdfg}, then return B.
If the first character in string  is in the set {hjklm},, then return C.
If the first character in string  is in the set {npqrstvwxyz}, then return D.

I am trying to implement the above scenarion and to dthis I have written the following code.

//Here is my code
    function getLetter(s) {
        let letter;
        // Write your code here

            switch (s) {
            case s.match(/[aeiou]/g).includes(s[0]):
            letter = 'A'
            break;

            case s.match(/[bcdfg]/g).includes(s[0]):
            letter = 'B'
            break;

            case s.match(/[hjklm]/g).includes(s[0]):
            letter = 'C';
            break;

            case s.match(/[npqrstvwxyz]/g).includes(s[0]):
            letter = 'D';
            break;
            default:
            console.log("hello")
        }
        return letter
    }

The code is showing error. Would any help me to figure it out? How can I implement the above task using switch statement.
</code>```

答:
I don't know that much switch case, but maybe you can use parenthesis for the switch statement and if "s.match(/[aeiou]/g).includes(s[0])" return true or false
And you forgot ";" after the two first assignment</p>

Body:
//This is my Problem
Complete the getLetter(s) function in the editor. It has one parameter: a string, , consisting of lowercase English alphabetic letters (i.e., a through z). It must return A, B, C, or D depending on the following criteria:

If the first character in string  is in the set {aeiou}, then return A.
If the first character in string  is in the set {bcdfg}, then return B.
If the first character in string  is in the set {hjklm},, then return C.
If the first character in string  is in the set {npqrstvwxyz}, then return D.

I am trying to implement the above scenarion and to dthis I have written the following code.

//Here is my code
    function getLetter(s) {
        let letter;
        // Write your code here

            switch (s) {
            case s.match(/[aeiou]/g).includes(s[0]):
            letter = 'A'
            break;

            case s.match(/[bcdfg]/g).includes(s[0]):
            letter = 'B'
            break;

            case s.match(/[hjklm]/g).includes(s[0]):
            letter = 'C';
            break;

            case s.match(/[npqrstvwxyz]/g).includes(s[0]):
            letter = 'D';
            break;
            default:
            console.log("hello")
        }
        return letter
    }

The code is showing error. Would any help me to figure it out? How can I implement the above task using switch statement.


问:
AttributeError: <Class> object has no attribute
I have this class:

```<code>class MyManager():

    def __init__(self):
        self.__sock_service = ClientSocket()

    def say_hello(self, request: Dict):
        self.__sock_service.send(request['name'])
        return self.__sock_service.receive()
</code>```

When calling say_hello method, I get

```<code>"AttributeError: MyManager object has no attribute __sock_service".
</code>```

Though, I do have an object _MyManager.__sock_service that is initialized (plus, my server does recognize a new connection).

What am I doing wrong?

答:
Is this the full code?
If not please write the full code</p>

Body:
I have this class:

class MyManager():

    def __init__(self):
        self.__sock_service = ClientSocket()

    def say_hello(self, request: Dict):
        self.__sock_service.send(request['name'])
        return self.__sock_service.receive()

When calling say_hello method, I get

"AttributeError: MyManager object has no attribute __sock_service".

Though, I do have an object _MyManager.__sock_service that is initialized (plus, my server does recognize a new connection).

What am I doing wrong?


问:
Error: data and salt arguments required
I am trying to save a user to mongodb database using post request as follow, but I got the error bcrypt Error: data and hash arguments required .It's a pretty simple set up of the code but i can't figure out anything wrong with it.
models/users.js

const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const confic = require('../models/users');

// User schema
const UserSchema = mongoose.Schema({
 name: {
  type: String,
 },
 email: {
  type: String,
  required: true
 },
 username:{
  type: String,
  required: true
 },
 password: {
  type: String,
  required: true
 }
});

const User = module.exports = mongoose.model('User', UserSchema);

module.exports.getUserById = function(id,callback){
 User.findById(id,callback);
}

module.exports.getUserByUsername = function(username,callback){
 const query = {username:username}
 User.findOne(query,callback);
}

module.exports.addUser= function (newUser, callback) {
   bcrypt.genSalt(10,(err,salt) => {
    bcrypt.hash(newUser.password, salt , (err, hash) =>{
        if(err) throw (err);

        newUser.password=hash;
        newUser.save(callback);
    });
   });
}```
</div>
</div>

routes/users.js</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const jwt = require('jsonwebtoken');
User = require('../models/users')

// // Register
router.post('/register', (req, res, next) => {
  var newUser = new User({
    name: req.body.name,
    email: req.body.email,
    username: req.body.username,
    password: req.body.password
  });

  User.addUser(newUser, (err, User) => {
    if(err){
      // res.json({success: false, msg:'Failed to register user'});
    } else {
      // res.json({success: true, msg:'User registered'});
    }

  });

});

// Authenticate
router.post('/authenticate', (req, res, next) => {
  res.send('AUTHENTICATE');
});

// Profile
router.get('/profile', (req, res, next) => {
  res.send('PROFILE');
});

module.exports = router;</code>```

Server was running but after using postman chrome post request error are shown and server stop working as errors shown in image.

答: When I was testing with plain text mode, I got this error (data and salt argument required), once I did change to json, it was ok.</p>

ContentLicense: CC BY-SA 3.0

Title: Error: data and salt arguments required

Body:
I am trying to save a user to mongodb database using post request as follow, but I got the error bcrypt Error: data and hash arguments required .It's a pretty simple set up of the code but i can't figure out anything wrong with it.
models/users.js

const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const confic = require('../models/users');

// User schema
const UserSchema = mongoose.Schema({
 name: {
  type: String,
 },
 email: {
  type: String,
  required: true
 },
 username:{
  type: String,
  required: true
 },
 password: {
  type: String,
  required: true
 }
});

const User = module.exports = mongoose.model('User', UserSchema);

module.exports.getUserById = function(id,callback){
 User.findById(id,callback);
}

module.exports.getUserByUsername = function(username,callback){
 const query = {username:username}
 User.findOne(query,callback);
}

module.exports.addUser= function (newUser, callback) {
   bcrypt.genSalt(10,(err,salt) => {
    bcrypt.hash(newUser.password, salt , (err, hash) =>{
        if(err) throw (err);

        newUser.password=hash;
        newUser.save(callback);
    });
   });
}

routes/users.js

const jwt = require('jsonwebtoken');
User = require('../models/users')

// // Register
router.post('/register', (req, res, next) => {
  var newUser = new User({
    name: req.body.name,
    email: req.body.email,
    username: req.body.username,
    password: req.body.password
  });

  User.addUser(newUser, (err, User) => {
    if(err){
      // res.json({success: false, msg:'Failed to register user'});
    } else {
      // res.json({success: true, msg:'User registered'});
    }

  });

});

// Authenticate
router.post('/authenticate', (req, res, next) => {
  res.send('AUTHENTICATE');
});

// Profile
router.get('/profile', (req, res, next) => {
  res.send('PROFILE');
});

module.exports = router;

Server was running but after using postman chrome post request error are shown and server stop working as errors shown in image.


问:
Swift set content compression resistance
Using Swift again, am I missing something?

I have this line:

```<code>self.itemDescription?.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: UILayoutConstraintAxis.Vertical);
</code>```

But Xcode is giving me an error:

```<code>Undefined symbols for architecture i386: "_UILayoutPriorityRequired"
</code>```

Another one of Swift's quirks?

答:
You can also write this:

```<code>self.itemDescription?.setContentCompressionResistancePriority(UILayoutPriority(<float number>), forAxis: .Vertical)
</code>```

Example:

```<code>self.itemDescription?.setContentCompressionResistancePriority(UILayoutPriority(750), forAxis: .Vertical)
</code>```

Body:
Using Swift again, am I missing something?

I have this line:

self.itemDescription?.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: UILayoutConstraintAxis.Vertical);

But Xcode is giving me an error:

Undefined symbols for architecture i386: "_UILayoutPriorityRequired"

Another one of Swift's quirks?

Body:
You can also write this:

self.itemDescription?.setContentCompressionResistancePriority(UILayoutPriority(<float number>), forAxis: .Vertical)

Example:

self.itemDescription?.setContentCompressionResistancePriority(UILayoutPriority(750), forAxis: .Vertical)


答:
the way you wrote the switch case may be partially correct in GoLang. but in Javascript, it is not possible to achieve this using Switch-Case statement.

Better try using if-else-if statement something like below

```<code>if(s.test(/^[aeiou]/)) {
    return 'A';
} else if(s.test(/^[bcdfg]/)) {
    return 'B'
}
</code>```

Title: How to write case in Switch else statement in javavscript?

Body:
the way you wrote the switch case may be partially correct in GoLang. but in Javascript, it is not possible to achieve this using Switch-Case statement.

Better try using if-else-if statement something like below

if(s.test(/^[aeiou]/)) {
    return 'A';
} else if(s.test(/^[bcdfg]/)) {
    return 'B'
}


问:
javascript: how to convert array to tuple
I have strange requirement in which i am using javascript.

I have json file from where i extract the values leaving keys. when i extract values I have them in array. I should change the array to tuple

in Python, we have and array and tuple concepts. But i am not sure about javascript.
Can anyone help one this

sample json

```<code>[ {a:1 , b:2}, {c: 3, D:4} ]
</code>```

I am able to extract values for json array

my result is :

```<code>[1, 2]
</code>```

and i want it to be as

```<code> (1,2)
</code>```

where i need to pass the (1,2) as arguments to java program

Body:
I have strange requirement in which i am using javascript.

I have json file from where i extract the values leaving keys. when i extract values I have them in array. I should change the array to tuple

in Python, we have and array and tuple concepts. But i am not sure about javascript.
Can anyone help one this

sample json

[ {a:1 , b:2}, {c: 3, D:4} ]

I am able to extract values for json array

my result is :

[1, 2]

and i want it to be as

 (1,2)

where i need to pass the (1,2) as arguments to java program

Body:
let b = [1, 2, 3];

let ids = `('${b.join("','")}')`;

console.log(ids);
// "('1','2','3')"


问:
Is it possible to tell if a java ResultSet is empty without affecting the record?
I do not want to use next() since if the ResultSet is not empty, I do not want the cursor to be advanced. Is there some sort of peek() method or equivalent that will return false if the ResultSet is empty and true otherwise without affecting the record?

Edit:

I cannot call beforeFirst because I get the following

Operation requires a scrollable ResultSet, but this ResultSet is
  FORWARD_ONLY

I need FORWARD_ONLY because I'm using postgreSQL cursors

答:
```<code>   getFetchSize()
</code>```

based on the size returned you can proceed...

Body:
   getFetchSize()

based on the size returned you can proceed...


问:
How to return a json string with content type json in net 6 and minimal api?
If I have a json string (eg. read from a file) and my api returns as string, Postman will treat the response as text

```<code>app.MapGet("/myapi", () =>
{
    var json = File.ReadAllText("file.json");
    return json;
});
</code>```

So how can I force the content type to application/json? (not using Newtonsoft please)
I was able with that workaround, but seems ugly

```<code>app.MapGet("/myapi", () =>
{
    var json = File.ReadAllText("file.json");
    var jo = JsonSerializer.Deserialize<object>(json);
    return Results.Json(jo);
});
</code>```

Thanks

答:
Your "workaround" is the correct method to return Json from a minimal API.  Please see the methods available in the Results class for a full list of available responses.

Results.Json() is the correct response to return Json.  IMO, your second technique is not "ugly", but the correct way to read and deserialize Json. Don't worry about the performance of deserializing the Json to an object only to serialize it again - if it becomes a problem you can address it at that point.  What if you need to modify the json before returning it? You'd need to deserialize it in that case anyway.

I would also add that ideally you'd deserialize into a defined class rather than object:

var jo = JsonSerializer.Deserialize<CustomClass>(json);
```
<p><strong>Workaround</strong></p>
<p>However, you <em>could</em> use <code>Results.Text()</code> and specify the content-type:</p>
<pre class="lang-cs prettyprint-override"><code>return Results.Text(json, contentType: "application/json");
</code>```

which produces the same result in Postman as:

return Results.Json(jo);
```

Body:
If I have a json string (eg. read from a file) and my api returns as string, Postman will treat the response as text

app.MapGet("/myapi", () =>
{
    var json = File.ReadAllText("file.json");
    return json;
});

So how can I force the content type to application/json? (not using Newtonsoft please)
I was able with that workaround, but seems ugly

app.MapGet("/myapi", () =>
{
    var json = File.ReadAllText("file.json");
    var jo = JsonSerializer.Deserialize<object>(json);
    return Results.Json(jo);
});

Thanks

Body:
Your "workaround" is the correct method to return Json from a minimal API.  Please see the methods available in the Results class for a full list of available responses.

Results.Json() is the correct response to return Json.  IMO, your second technique is not "ugly", but the correct way to read and deserialize Json. Don't worry about the performance of deserializing the Json to an object only to serialize it again - if it becomes a problem you can address it at that point.  What if you need to modify the json before returning it? You'd need to deserialize it in that case anyway.

I would also add that ideally you'd deserialize into a defined class rather than object:

var jo = JsonSerializer.Deserialize<CustomClass>(json);

Workaround

However, you could use Results.Text() and specify the content-type:

return Results.Text(json, contentType: "application/json");

which produces the same result in Postman as:

return Results.Json(jo);


问:
Download UNIX python wheel in windows
I want to download a UNIX python wheel into my windows PC, for later install it in a UNIX server with no access to the internet

I tried

```<code>python -m pip download --only-binary :all: --no-cache imbalanced_learn
</code>```

But I get the wheels win_amd, but I need manylinux

Example download in windows:

```<code>Collecting threadpoolctl>=2.0.0
  Downloading threadpoolctl-3.1.0-py3-none-any.whl (14 kB)
  Saved c:\users\c58210a\onedrive - experian services corp\documents\proyectos\migracion db\descargar librerias\test\imbalanced_learn2\threadpoolctl-3.1.0-py3-none-any.whl
Collecting scipy>=1.1.0
  Downloading scipy-1.7.3-cp37-cp37m-win_amd64.whl (34.1 MB)
     |████████████████████████████████| 34.1 MB 6.8 MB/s
  Saved c:\users\c58210a\onedrive - experian services corp\documents\proyectos\migracion db\descargar librerias\test\imbalanced_learn2\scipy-1.7.3-cp37-cp37m-win_amd64.whl
Collecting scikit-learn>=1.0.1
  Downloading scikit_learn-1.0.2-cp37-cp37m-win_amd64.whl (7.1 MB)
     |████████████████████████████████| 7.1 MB 6.1 kB/s
  Saved c:\users\c58210a\onedrive - experian services corp\documents\proyectos\migracion db\descargar librerias\test\imbalanced_learn2\scikit_learn-1.0.2-cp37-cp37m-win_amd64.whl
Collecting joblib>=0.11
  Downloading joblib-1.1.0-py2.py3-none-any.whl (306 kB)
     |████████████████████████████████| 306 kB 242 kB/s
  Saved c:\users\c58210a\onedrive - experian services corp\documents\proyectos\migracion db\descargar librerias\test\imbalanced_learn2\joblib-1.1.0-py2.py3-none-any.whl
Collecting numpy>=1.14.6
  Downloading numpy-1.21.5-cp37-cp37m-win_amd64.whl (14.0 MB)
     |████████████████████████████████| 14.0 MB 6.4 MB/s
  Saved c:\users\c58210a\onedrive - experian services corp\documents\proyectos\migracion db\descargar librerias\test\imbalanced_learn2\numpy-1.21.5-cp37-cp37m-win_amd64.whl
Successfully downloaded imbalanced-learn threadpoolctl scipy scikit-learn joblib numpy
</code>```

Example download in UNIX:

```<code>Collecting imbalanced_learn
  Downloading imbalanced_learn-0.9.0-py3-none-any.whl (199 kB)
  Saved ./s3:/experian-s3-ascend-colombia-internal-buro-data/TempJC/imbalanced_learn-0.9.0-py3-none-any.whl
Collecting numpy>=1.14.6
  Downloading numpy-1.21.5-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (15.7 MB)
  Saved ./s3:/experian-s3-ascend-colombia-internal-buro-data/TempJC/numpy-1.21.5-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl
Collecting joblib>=0.11
  Downloading joblib-1.1.0-py2.py3-none-any.whl (306 kB)
  Saved ./s3:/experian-s3-ascend-colombia-internal-buro-data/TempJC/joblib-1.1.0-py2.py3-none-any.whl
Collecting scikit-learn>=1.0.1
  Downloading scikit_learn-1.0.2-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (24.8 MB)
  Saved ./s3:/experian-s3-ascend-colombia-internal-buro-data/TempJC/scikit_learn-1.0.2-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Collecting threadpoolctl>=2.0.0
  Downloading threadpoolctl-3.1.0-py3-none-any.whl (14 kB)
  Saved ./s3:/experian-s3-ascend-colombia-internal-buro-data/TempJC/threadpoolctl-3.1.0-py3-none-any.whl
Collecting scipy>=1.1.0
  Downloading scipy-1.7.3-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (38.1 MB)
  Saved ./s3:/experian-s3-ascend-colombia-internal-buro-data/TempJC/scipy-1.7.3-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl
Successfully downloaded imbalanced-learn numpy joblib scikit-learn threadpoolctl scipy
</code>```

Regards

答:
Use --platform ?

On my Ubuntu x86_64 :

```<code>$ pip download --only-binary=:all: --platform win_amd64 imbalanced_learn
[...]
Saved ./imbalanced_learn-0.9.0-py3-none-any.whl
Saved ./joblib-1.1.0-py2.py3-none-any.whl
Saved ./numpy-1.22.2-cp39-cp39-win_amd64.whl
Saved ./scikit_learn-1.0.2-cp39-cp39-win_amd64.whl
Saved ./scipy-1.8.0-cp39-cp39-win_amd64.whl
Saved ./threadpoolctl-3.1.0-py3-none-any.whl
[...]

$ pip download --only-binary=:all: --platform manylinux2014_x86_64 imbalanced_learn
[...]
Saved ./imbalanced_learn-0.9.0-py3-none-any.whl
Saved ./joblib-1.1.0-py2.py3-none-any.whl
Saved ./numpy-1.22.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Saved ./scikit_learn-1.0.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Saved ./scipy-1.8.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Saved ./threadpoolctl-3.1.0-py3-none-any.whl
[...]
</code>```

Or use another version for manylinux.

Title: Download UNIX python wheel in windows

Body:
I want to download a UNIX python wheel into my windows PC, for later install it in a UNIX server with no access to the internet

I tried

python -m pip download --only-binary :all: --no-cache imbalanced_learn

But I get the wheels win_amd, but I need manylinux

Example download in windows:

Collecting threadpoolctl>=2.0.0
  Downloading threadpoolctl-3.1.0-py3-none-any.whl (14 kB)
  Saved c:\users\c58210a\onedrive - experian services corp\documents\proyectos\migracion db\descargar librerias\test\imbalanced_learn2\threadpoolctl-3.1.0-py3-none-any.whl
Collecting scipy>=1.1.0
  Downloading scipy-1.7.3-cp37-cp37m-win_amd64.whl (34.1 MB)
     |████████████████████████████████| 34.1 MB 6.8 MB/s
  Saved c:\users\c58210a\onedrive - experian services corp\documents\proyectos\migracion db\descargar librerias\test\imbalanced_learn2\scipy-1.7.3-cp37-cp37m-win_amd64.whl
Collecting scikit-learn>=1.0.1
  Downloading scikit_learn-1.0.2-cp37-cp37m-win_amd64.whl (7.1 MB)
     |████████████████████████████████| 7.1 MB 6.1 kB/s
  Saved c:\users\c58210a\onedrive - experian services corp\documents\proyectos\migracion db\descargar librerias\test\imbalanced_learn2\scikit_learn-1.0.2-cp37-cp37m-win_amd64.whl
Collecting joblib>=0.11
  Downloading joblib-1.1.0-py2.py3-none-any.whl (306 kB)
     |████████████████████████████████| 306 kB 242 kB/s
  Saved c:\users\c58210a\onedrive - experian services corp\documents\proyectos\migracion db\descargar librerias\test\imbalanced_learn2\joblib-1.1.0-py2.py3-none-any.whl
Collecting numpy>=1.14.6
  Downloading numpy-1.21.5-cp37-cp37m-win_amd64.whl (14.0 MB)
     |████████████████████████████████| 14.0 MB 6.4 MB/s
  Saved c:\users\c58210a\onedrive - experian services corp\documents\proyectos\migracion db\descargar librerias\test\imbalanced_learn2\numpy-1.21.5-cp37-cp37m-win_amd64.whl
Successfully downloaded imbalanced-learn threadpoolctl scipy scikit-learn joblib numpy

Example download in UNIX:

Collecting imbalanced_learn
  Downloading imbalanced_learn-0.9.0-py3-none-any.whl (199 kB)
  Saved ./s3:/experian-s3-ascend-colombia-internal-buro-data/TempJC/imbalanced_learn-0.9.0-py3-none-any.whl
Collecting numpy>=1.14.6
  Downloading numpy-1.21.5-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (15.7 MB)
  Saved ./s3:/experian-s3-ascend-colombia-internal-buro-data/TempJC/numpy-1.21.5-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl
Collecting joblib>=0.11
  Downloading joblib-1.1.0-py2.py3-none-any.whl (306 kB)
  Saved ./s3:/experian-s3-ascend-colombia-internal-buro-data/TempJC/joblib-1.1.0-py2.py3-none-any.whl
Collecting scikit-learn>=1.0.1
  Downloading scikit_learn-1.0.2-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (24.8 MB)
  Saved ./s3:/experian-s3-ascend-colombia-internal-buro-data/TempJC/scikit_learn-1.0.2-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Collecting threadpoolctl>=2.0.0
  Downloading threadpoolctl-3.1.0-py3-none-any.whl (14 kB)
  Saved ./s3:/experian-s3-ascend-colombia-internal-buro-data/TempJC/threadpoolctl-3.1.0-py3-none-any.whl
Collecting scipy>=1.1.0
  Downloading scipy-1.7.3-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (38.1 MB)
  Saved ./s3:/experian-s3-ascend-colombia-internal-buro-data/TempJC/scipy-1.7.3-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl
Successfully downloaded imbalanced-learn numpy joblib scikit-learn threadpoolctl scipy

Regards

Body:
Use --platform ?

On my Ubuntu x86_64 :

$ pip download --only-binary=:all: --platform win_amd64 imbalanced_learn
[...]
Saved ./imbalanced_learn-0.9.0-py3-none-any.whl
Saved ./joblib-1.1.0-py2.py3-none-any.whl
Saved ./numpy-1.22.2-cp39-cp39-win_amd64.whl
Saved ./scikit_learn-1.0.2-cp39-cp39-win_amd64.whl
Saved ./scipy-1.8.0-cp39-cp39-win_amd64.whl
Saved ./threadpoolctl-3.1.0-py3-none-any.whl
[...]

$ pip download --only-binary=:all: --platform manylinux2014_x86_64 imbalanced_learn
[...]
Saved ./imbalanced_learn-0.9.0-py3-none-any.whl
Saved ./joblib-1.1.0-py2.py3-none-any.whl
Saved ./numpy-1.22.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Saved ./scikit_learn-1.0.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Saved ./scipy-1.8.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Saved ./threadpoolctl-3.1.0-py3-none-any.whl
[...]

Or use another version for manylinux.


问:
Gutenberg NPM doesn't do any changes
The NPM when i created  some changes in blocks or something else .. the changes not working ,
and this my gutenberg.php

```<code>    function MyBlocks()
{
    wp_register_script('blocks-js', get_template_directory_uri() . '/build/index.js', array('wp-blocks' , 'wp-editor' , 'wp-components' ));
    register_block_type('yusuf/custom-cta', array('editor_script' => 'blocks-js'));
    // register_block_type('yusuf/custom-pro', array('editor_script' => 'blocks-js'));
    // register_block_type("yusuf/statics" , array('editor_script' => 'blocks-js'));

}
add_action('init', 'MyBlocks');
</code>```

I commented the blocks and still shows up ,
and removed it from build/index.js too , and still shows up ,
i want know why it happened with me !
And already the "NPM START" Runs

答: it's all In browser cache .. you can use a private browser or cleaning the browser cache every time you try to make any change .. and you will see your updates seems good</p>

Title: Gutenberg NPM doesn't do any changes

Body:
The NPM when i created  some changes in blocks or something else .. the changes not working ,
and this my gutenberg.php

    function MyBlocks()
{
    wp_register_script('blocks-js', get_template_directory_uri() . '/build/index.js', array('wp-blocks' , 'wp-editor' , 'wp-components' ));
    register_block_type('yusuf/custom-cta', array('editor_script' => 'blocks-js'));
    // register_block_type('yusuf/custom-pro', array('editor_script' => 'blocks-js'));
    // register_block_type("yusuf/statics" , array('editor_script' => 'blocks-js'));

}
add_action('init', 'MyBlocks');

I commented the blocks and still shows up ,
and removed it from build/index.js too , and still shows up ,
i want know why it happened with me !
And already the "NPM START" Runs


问:
Can I make multiple assignments within a given case_when true clause?
Update: Apparently this feature is now planned for dplyr, as discussed here: https://github.com/tidyverse/dplyr/pull/6145

In SQL one can assign multiple variables - say var1 and var2 - when a given case is verified, with a construction like

case when condition then var1 = x, var2 = y

Does dplyr::case_when (or anything else in the tidyverse) support this useful feature), and if so, how?!

Note that in the example below, var1, var2  and var3 have exactly the same test conditions, i.e. Species == "setosa", and the degenerate case TRUE. I want to reduce this redundancy by not repeating the conditions: one call to case_when (or similar), albeit with different eval_on_true expressions for var1, var2 and var3, respectively. Obviously redundancy is not a problem here in this example, but my case_when's get very large and complex in real life examples.

library(tidyverse)

# create example data
set.seed(1337)
data <- iris %>%
  sample_n(5) %>%
  select(Petal.Length, Petal.Width, Species) %>%
  as_tibble()
data
#> # A tibble: 5 × 3
#>   Petal.Length Petal.Width Species
#>          <dbl>       <dbl> <fct>
#> 1          5.5         1.8 virginica
#> 2          5           1.9 virginica
#> 3          1.5         0.2 setosa
#> 4          5.9         2.3 virginica
#> 5          4.1         1.3 versicolor
data %>%
  mutate(var1 = case_when(Species == "setosa" ~ "green", TRUE ~ "blue"),
         var2 = case_when(Species == "setosa" ~ Petal.Length * 99, TRUE ~ Petal.Length),
         var3 = case_when(Species == "setosa" ~ as.Date("2002-12-01"), TRUE ~ as.Date("2003-12-02")))
#> # A tibble: 5 × 6
#>   Petal.Length Petal.Width Species    var1   var2 var3
#>          <dbl>       <dbl> <fct>      <chr> <dbl> <date>
#> 1          5.5         1.8 virginica  blue    5.5 2003-12-02
#> 2          5           1.9 virginica  blue    5   2003-12-02
#> 3          1.5         0.2 setosa     green 148.  2002-12-01
#> 4          5.9         2.3 virginica  blue    5.9 2003-12-02
#> 5          4.1         1.3 versicolor blue    4.1 2003-12-02
```

Created on 2022-02-09 by the reprex package (v2.0.1)

答:
The problem with case_when is that accepts a value whose length is either nrow or 1. Therefore, you have to trick case_when by producing a list of nrow 1-row dataframes.
The accessor function lod (defined below) constructs a list of 1-row dataframes:

lod <- function(...) {
  args <- list(...)
  do.call(function(...) mapply(data.frame, ..., SIMPLIFY = FALSE), args)
}

lod(x = 1:4, y = letters[1:4])

[[1]]
  x y
1 1 a

[[2]]
  x y
1 2 b

[[3]]
  x y
1 3 c

[[4]]
  x y
1 4 d
```
<p>Then write your <code>case_when</code> statement, using <code>lod</code> to group variables, as follows:</p>
<pre class="lang-r prettyprint-override"><code>data |>
  mutate(case_when(Species == "setosa" ~
                     lod(var1 = "green",
                         var2 = Petal.Length * 99,
                         var3 = as.Date("2002-12-01")),
                   TRUE ~
                     lod(var1 = "blue",
                         var2 = Petal.Length,
                         var3 = as.Date("2003-12-02"))) |>
         bind_rows())

+ # A tibble: 5 x 6
  Petal.Length Petal.Width Species    var1   var2 var3
         <dbl>       <dbl> <fct>      <chr> <dbl> <date>
1          5.5         1.8 virginica  blue    5.5 2003-12-02
2          5           1.9 virginica  blue    5   2003-12-02
3          1.5         0.2 setosa     green 148.  2002-12-01
4          5.9         2.3 virginica  blue    5.9 2003-12-02
5          4.1         1.3 versicolor blue    4.1 2003-12-02
</code>```

The final bind_rows is required for mutate to accept the new variables.

Body:
Update: Apparently this feature is now planned for dplyr, as discussed here: https://github.com/tidyverse/dplyr/pull/6145

In SQL one can assign multiple variables - say var1 and var2 - when a given case is verified, with a construction like

case when condition then var1 = x, var2 = y

Does dplyr::case_when (or anything else in the tidyverse) support this useful feature), and if so, how?!

Note that in the example below, var1, var2  and var3 have exactly the same test conditions, i.e. Species == "setosa", and the degenerate case TRUE. I want to reduce this redundancy by not repeating the conditions: one call to case_when (or similar), albeit with different eval_on_true expressions for var1, var2 and var3, respectively. Obviously redundancy is not a problem here in this example, but my case_when's get very large and complex in real life examples.

library(tidyverse)

# create example data
set.seed(1337)
data <- iris %>%
  sample_n(5) %>%
  select(Petal.Length, Petal.Width, Species) %>%
  as_tibble()
data
#> # A tibble: 5 × 3
#>   Petal.Length Petal.Width Species
#>          <dbl>       <dbl> <fct>
#> 1          5.5         1.8 virginica
#> 2          5           1.9 virginica
#> 3          1.5         0.2 setosa
#> 4          5.9         2.3 virginica
#> 5          4.1         1.3 versicolor
data %>%
  mutate(var1 = case_when(Species == "setosa" ~ "green", TRUE ~ "blue"),
         var2 = case_when(Species == "setosa" ~ Petal.Length * 99, TRUE ~ Petal.Length),
         var3 = case_when(Species == "setosa" ~ as.Date("2002-12-01"), TRUE ~ as.Date("2003-12-02")))
#> # A tibble: 5 × 6
#>   Petal.Length Petal.Width Species    var1   var2 var3
#>          <dbl>       <dbl> <fct>      <chr> <dbl> <date>
#> 1          5.5         1.8 virginica  blue    5.5 2003-12-02
#> 2          5           1.9 virginica  blue    5   2003-12-02
#> 3          1.5         0.2 setosa     green 148.  2002-12-01
#> 4          5.9         2.3 virginica  blue    5.9 2003-12-02
#> 5          4.1         1.3 versicolor blue    4.1 2003-12-02

Created on 2022-02-09 by the reprex package (v2.0.1)

Body:
The problem with case_when is that accepts a value whose length is either nrow or 1. Therefore, you have to trick case_when by producing a list of nrow 1-row dataframes.
The accessor function lod (defined below) constructs a list of 1-row dataframes:

lod <- function(...) {
  args <- list(...)
  do.call(function(...) mapply(data.frame, ..., SIMPLIFY = FALSE), args)
}

lod(x = 1:4, y = letters[1:4])

[[1]]
  x y
1 1 a

[[2]]
  x y
1 2 b

[[3]]
  x y
1 3 c

[[4]]
  x y
1 4 d

Then write your case_when statement, using lod to group variables, as follows:

data |>
  mutate(case_when(Species == "setosa" ~
                     lod(var1 = "green",
                         var2 = Petal.Length * 99,
                         var3 = as.Date("2002-12-01")),
                   TRUE ~
                     lod(var1 = "blue",
                         var2 = Petal.Length,
                         var3 = as.Date("2003-12-02"))) |>
         bind_rows())

+ # A tibble: 5 x 6
  Petal.Length Petal.Width Species    var1   var2 var3
         <dbl>       <dbl> <fct>      <chr> <dbl> <date>
1          5.5         1.8 virginica  blue    5.5 2003-12-02
2          5           1.9 virginica  blue    5   2003-12-02
3          1.5         0.2 setosa     green 148.  2002-12-01
4          5.9         2.3 virginica  blue    5.9 2003-12-02
5          4.1         1.3 versicolor blue    4.1 2003-12-02

The final bind_rows is required for mutate to accept the new variables.


问:
swf(flash) plays automatically in chrome
I embed the swf file by swfobject. I do not want the swf file(it's an advertisement) play automatically, so I set the attribute of play with "false". as following html:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <script type="text/javascript" src="swfobject/swfobject.js"></script>
        <script type="text/javascript">
            swfobject.registerObject("myFlashContent", "9.0.0", "expressInstall.swf");
        </script>
    </head>
    <body>
        <div>
            <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="970" height="250" id="myFlashContent">
                <param name="movie" value="day_110702/ad.swf" />
                <param name="play" value="false" />
                <!--[if !IE]>-->
                <object type="application/x-shockwave-flash" data="day_110702/ad.swf" width="970" height="250">
                <!--<![endif]-->
                    <a href="http://www.adobe.com/go/getflashplayer">
                        <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />
                    </a>
                <!--[if !IE]>-->
                </object>
                <!--<![endif]-->
            </object>
        </div>
    </body>
</html>
</code>```

It works perfectly on IE but it doesn't work on Chrome/Firefox. In Chrome/Firefox the swf file plays automatically.

In addition, another behavior of swf file differ from Chrome/Firefox and IE is:
when you embedded the swf file with invisible iframe tag. as

```<code><iframe id="iframe"  src="swf.html" style="width:100%;height:100%; display:none; visibility:hidden;"></iframe>
</code>```

When you browse the page that contains this iframe in IE/Firefox, the swf will NOT play until you make iframe visible. But if yo browse the page in Chrome, the swf will play automatically even if iframe is invisible.

Anyone can tell me why the swf(flash) behavior is differ in different browsers?
Cross-browsers problem always make crazy :).

答:
Have you tried embedding the SWF using dynamic publishing instead of static publishing?</p>

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <script type="text/javascript" src="swfobject.js"></script>
        <script type="text/javascript">
            var flashvars = {};
            var params = {};
            params.play = "true";
            var attributes = {};
            swfobject.embedSWF("day_110702/ad.swf", "myAlternativeContent", "970", "250", "9.0.0", false, flashvars, params, attributes);
        </script>
    </head>
    <body>
        <div id="myAlternativeContent">
            <a href="http://www.adobe.com/go/getflashplayer">
                <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />
            </a>
        </div>
    </body>
</html>
</code>```

Body:
I embed the swf file by swfobject. I do not want the swf file(it's an advertisement) play automatically, so I set the attribute of play with "false". as following html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

            <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="970" height="250" id="myFlashContent">
                <param name="movie" value="day_110702/ad.swf" />
                <param name="play" value="false" />

                <object type="application/x-shockwave-flash" data="day_110702/ad.swf" width="970" height="250">

                </object>

            </object>

It works perfectly on IE but it doesn't work on Chrome/Firefox. In Chrome/Firefox the swf file plays automatically.

In addition, another behavior of swf file differ from Chrome/Firefox and IE is:
when you embedded the swf file with invisible iframe tag. as

When you browse the page that contains this iframe in IE/Firefox, the swf will NOT play until you make iframe visible. But if yo browse the page in Chrome, the swf will play automatically even if iframe is invisible.

Anyone can tell me why the swf(flash) behavior is differ in different browsers?
Cross-browsers problem always make crazy :).

Body:
Have you tried embedding the SWF using dynamic publishing instead of static publishing?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <script type="text/javascript" src="swfobject.js"></script>
        <script type="text/javascript">
            var flashvars = {};
            var params = {};
            params.play = "true";
            var attributes = {};
            swfobject.embedSWF("day_110702/ad.swf", "myAlternativeContent", "970", "250", "9.0.0", false, flashvars, params, attributes);
        </script>
    </head>
    <body>
        <div id="myAlternativeContent">
            <a href="http://www.adobe.com/go/getflashplayer">
                <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />
            </a>
        </div>
    </body>
</html>


问:
Omit Leptonica Library from Tesseract
Working on an OCR project, I am trying to figure out if there is any way or possibility to omit Leptonica Library from Tesseract and maybe replace it with OpenCV.
Already have OpenCV on the C layer and planning to combine that with Tesseract.</p>

答:
No, it is not possible (unless you rewrite tesseract).

But you can compile leptonica with the minimal dependencies (zlib + png).

Also I would suggest to check your OpenCV package as it includes support for tesseract OCR.

Title: Omit Leptonica Library from Tesseract


问:
Gradle jar not running. Could not find or load main class
I have created a very basic gradle java project that prints "Hello Word". The main class builds and runs fine. When i try to run java -jar out\artifacts\helloWorld_jar\helloWorld.jar on the command line it gives me this error

```<code>Error: Could not find or load main class com.exmple.helloWorld
Caused by: java.lang.ClassNotFoundException: com.exmple.helloWorld
</code>```

here is how my directory looks

```<code>|-gradle
|-.idea
|-build
|-gradle
|-META-INF
|-out
 | -artifacts
 | -helloWorld_jar
 | -helloWorld.jar
|-src
 |-main
  |-java
   |- com.exmple
    |-helloWorld
 |-test
|build.gradle
etc...
</code>```

My build.gradle file looks like this:

```<code>plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}
jar{
    manifest{
        attributes "Main-Class": "com.exmple.helloWorld"
    }

}
dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
}

test {
    useJUnitPlatform()
}

</code>```

I have tried both single quotes and double quotes and it still runs an error. Any ideas on how to fix this? I have been trying for a few days now.

PS. example is spelt wrong, but its spelt exmple throughout

答:
It is looking like you have a typo in the path that you are passing:

Error: Could not find or load main class com.exmple.helloWorld
Caused by: java.lang.ClassNotFoundException: com.exmple.helloWorld"

An A is missing from example package

Body:
I have created a very basic gradle java project that prints "Hello Word". The main class builds and runs fine. When i try to run java -jar out\artifacts\helloWorld_jar\helloWorld.jar on the command line it gives me this error

Error: Could not find or load main class com.exmple.helloWorld
Caused by: java.lang.ClassNotFoundException: com.exmple.helloWorld

here is how my directory looks

|-gradle
|-.idea
|-build
|-gradle
|-META-INF
|-out
 | -artifacts
 | -helloWorld_jar
 | -helloWorld.jar
|-src
 |-main
  |-java
   |- com.exmple
    |-helloWorld
 |-test
|build.gradle
etc...

My build.gradle file looks like this:

plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}
jar{
    manifest{
        attributes "Main-Class": "com.exmple.helloWorld"
    }

}
dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
}

test {
    useJUnitPlatform()
}

I have tried both single quotes and double quotes and it still runs an error. Any ideas on how to fix this? I have been trying for a few days now.

PS. example is spelt wrong, but its spelt exmple throughout


问:
How to build a 404 page with react-router-dom v6
I just upgraded to v6beta for react-router-dom because I wanted to organize my routes, but the 404 page is now broken:

```<code>export function AllRoutes(props) {

  return(
    <Routes>

      <Route path="/about-us">
        <Route path="contact">     <AboutContact/> </Route>
        <Route path="our-logo">    <AboutLogo/>    </Route>
        <Route path="the-mission"> <AboutMission/> </Route>
        <Route path="the-team">    <AboutTeam/>    </Route>
        <Route path="our-work">    <AboutWork/>    </Route>
      </Route>

      <Route path="/user">
        <Route path="sign-in"> <UserSignIn/> </Route>
        <Route path="sign-up"> <UserSignUp/> </Route>
      </Route>

      <Route path="/">
        <Home/>
      </Route>

      <Route >
        <NotFound/>
      </Route>

    </Routes>
  )
}
</code>```

So everything works as expected (including the home page) except the not found page, which does not work even when adding path="/*" or path="*"

Any easy solution for this?

答:
You need to render a Route with a path of *, and React Router will make sure to only render it if none of the other Routes match.

If your 404 component name is PageNotFound:

<Route path="*" element={<PageNotFound/>} />

1 Stackblitz link (its implementation is a little bit different)

2 The easiest example is here

Body:
I just upgraded to v6beta for react-router-dom because I wanted to organize my routes, but the 404 page is now broken:

export function AllRoutes(props) {

  return(
    <Routes>

      <Route path="/about-us">
        <Route path="contact">     <AboutContact/> </Route>
        <Route path="our-logo">    <AboutLogo/>    </Route>
        <Route path="the-mission"> <AboutMission/> </Route>
        <Route path="the-team">    <AboutTeam/>    </Route>
        <Route path="our-work">    <AboutWork/>    </Route>
      </Route>

      <Route path="/user">
        <Route path="sign-in"> <UserSignIn/> </Route>
        <Route path="sign-up"> <UserSignUp/> </Route>
      </Route>

      <Route path="/">
        <Home/>
      </Route>

      <Route >
        <NotFound/>
      </Route>

    </Routes>
  )
}

So everything works as expected (including the home page) except the not found page, which does not work even when adding path="/*" or path="*"

Any easy solution for this?


问:
Tailwind CSS IntelliSense is not auto-suggesting in VScode inside a svelte js application? it works if I reinstall it every time I open VScode
It seems that Tailwind CSS IntelliSense is not working every time I start VScode , after reinstalling it works, on the other hand when it works  Tailwind CSS IntelliSense is not suggesting unless I press the space button. If I move one class to another it doesn't suggest unless I press the space button

I am using  Tailwind CSS IntelliSense v0.7.4 ,VScode 1.63.2 , Ubuntu 21.10

package.json

```<code>{
  "name": "svelte-ts-tailwind-app",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "build": "rollup -c",
    "dev": "rollup -c -w",
    "start": "sirv public",
    "check": "svelte-check --tsconfig ./tsconfig.json"
  },
  "devDependencies": {
    "@rollup/plugin-commonjs": "^21.0.0",
    "@rollup/plugin-node-resolve": "^13.0.0",
    "@rollup/plugin-typescript": "^8.3.0",
    "@tsconfig/svelte": "^2.0.1",
    "autoprefixer": "^10.4.0",
    "postcss": "^8.4.4",
    "postcss-load-config": "^3.1.0",
    "rollup": "^2.60.2",
    "rollup-plugin-css-only": "^3.1.0",
    "rollup-plugin-livereload": "^2.0.0",
    "rollup-plugin-svelte": "^7.1.0",
    "rollup-plugin-terser": "^7.0.2",
    "svelte": "^3.44.2",
    "svelte-check": "^2.2.10",
    "svelte-preprocess": "^4.9.4",
    "tailwindcss": "~3.0.0",
    "tslib": "^2.3.1",
    "typescript": "~4.5.3"
  },
  "dependencies": {
    "sirv-cli": "^1.0.14"
  }
}
</code>```

tailwind.config.cjs

```<code>module.exports = {
  mode:"jit",
  darkMode: 'class', // This can be 'media' if preferred.
  // Don't add a glob below `public` as Rollup doesn't
  // recognize them and will rebuild in an infinite loop.
  content: [
    './src/**/*.svelte',
    './src/**/*.html',
    './public/index.html',
  ],
  theme: {
    extend: {
      colors: {
        svelte: '#ff3e00',
      },
    },
  },
  plugins: [],
}

</code>```

postcss.config.cjs

```<code>module.exports = {
  plugins: [
    require('tailwindcss'),
  ]
};
</code>```

答:
By default in VS code, settings for suggestion for strings is false, and as we type class names in components as a string you have to set this to true like this:</p>
```<code>"editor.quickSuggestions": {
        "other": true,
        "comments": false,
        "strings": true,
    }
}
</code>```

Body:
It seems that Tailwind CSS IntelliSense is not working every time I start VScode , after reinstalling it works, on the other hand when it works  Tailwind CSS IntelliSense is not suggesting unless I press the space button. If I move one class to another it doesn't suggest unless I press the space button

I am using  Tailwind CSS IntelliSense v0.7.4 ,VScode 1.63.2 , Ubuntu 21.10

package.json

{
  "name": "svelte-ts-tailwind-app",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "build": "rollup -c",
    "dev": "rollup -c -w",
    "start": "sirv public",
    "check": "svelte-check --tsconfig ./tsconfig.json"
  },
  "devDependencies": {
    "@rollup/plugin-commonjs": "^21.0.0",
    "@rollup/plugin-node-resolve": "^13.0.0",
    "@rollup/plugin-typescript": "^8.3.0",
    "@tsconfig/svelte": "^2.0.1",
    "autoprefixer": "^10.4.0",
    "postcss": "^8.4.4",
    "postcss-load-config": "^3.1.0",
    "rollup": "^2.60.2",
    "rollup-plugin-css-only": "^3.1.0",
    "rollup-plugin-livereload": "^2.0.0",
    "rollup-plugin-svelte": "^7.1.0",
    "rollup-plugin-terser": "^7.0.2",
    "svelte": "^3.44.2",
    "svelte-check": "^2.2.10",
    "svelte-preprocess": "^4.9.4",
    "tailwindcss": "~3.0.0",
    "tslib": "^2.3.1",
    "typescript": "~4.5.3"
  },
  "dependencies": {
    "sirv-cli": "^1.0.14"
  }
}

tailwind.config.cjs

module.exports = {
  mode:"jit",
  darkMode: 'class', // This can be 'media' if preferred.
  // Don't add a glob below `public` as Rollup doesn't
  // recognize them and will rebuild in an infinite loop.
  content: [
    './src/**/*.svelte',
    './src/**/*.html',
    './public/index.html',
  ],
  theme: {
    extend: {
      colors: {
        svelte: '#ff3e00',
      },
    },
  },
  plugins: [],
}

postcss.config.cjs

module.exports = {
  plugins: [
    require('tailwindcss'),
  ]
};

Body:
By default in VS code, settings for suggestion for strings is false, and as we type class names in components as a string you have to set this to true like this:

"editor.quickSuggestions": {
        "other": true,
        "comments": false,
        "strings": true,
    }
}


问:
INSERT INTO table from 2 unrelated tables
Not sure how to achieve the result, need your help

Source A:

```<code>SELECT SourceAID
FROM [dbo].[SourceA]
</code>```

Source B:

```<code>SELECT SourceBID
FROM [dbo].[SourceB]
</code>```

Result table (select example):

```<code>SELECT SourceAID
      ,SourceBID
      ,Value
  FROM [dbo].[Result]
</code>```

Idea of insert: For each SourceAID, i need to insert records with all SourceBID. There is no any reference between these 2 tables.

Idea by hand looks like this:

```<code> INSERT INTO [dbo].[Result] ([SourceAID], [SourceBID], [Value])
  VALUES ('AID_1', 'BID_1', NULL),
('AID_1', 'BID_2', NULL),
('AID_1', 'BID_3', NULL),
('AID_2', 'BID_1', NULL),
('AID_2', 'BID_2', NULL),
('AID_2', 'BID_3', NULL)
</code>```

and so on

答:
The other way is using subquery</p>
```<code>INSERT INTO [dbo].[Result] ([SourceAID], [SourceBID], [Value])
SELECT SA.SourceAID,SB.SourceBID,NULL
(SELECT 1 AS ID ,SA.SourceAID FROM [dbo].[SourceA]) SA
join
(SELECT 1 AS ID ,SA.SourceBID FROM [dbo].[SourceB]) SB
on SA.ID=SB.ID
</code>```

Body:
Not sure how to achieve the result, need your help

Source A:

SELECT SourceAID
FROM [dbo].[SourceA]

Source B:

SELECT SourceBID
FROM [dbo].[SourceB]

Result table (select example):

SELECT SourceAID
      ,SourceBID
      ,Value
  FROM [dbo].[Result]

Idea of insert: For each SourceAID, i need to insert records with all SourceBID. There is no any reference between these 2 tables.

Idea by hand looks like this:

 INSERT INTO [dbo].[Result] ([SourceAID], [SourceBID], [Value])
  VALUES ('AID_1', 'BID_1', NULL),
('AID_1', 'BID_2', NULL),
('AID_1', 'BID_3', NULL),
('AID_2', 'BID_1', NULL),
('AID_2', 'BID_2', NULL),
('AID_2', 'BID_3', NULL)

and so on

Body:
The other way is using subquery

INSERT INTO [dbo].[Result] ([SourceAID], [SourceBID], [Value])
SELECT SA.SourceAID,SB.SourceBID,NULL
(SELECT 1 AS ID ,SA.SourceAID FROM [dbo].[SourceA]) SA
join
(SELECT 1 AS ID ,SA.SourceBID FROM [dbo].[SourceB]) SB
on SA.ID=SB.ID


问:
Alias "ext.components.MyClass" is invalid. Make sure it points to an existing PHP file and the file is readable
i am new in yii framework. currently i am using yii 1.1.
now i want to create custom components and we can say than create global function which is use anywhere in the application.
According to this url 'http://www.yiiframework.com/wiki/727/updated-how-to-create-call-custom-global-function-in-whole-application/'

i am follow all steps according to above url
but i have occur a error
Alias "ext.components.MyClass" is invalid. Make sure it points to an existing PHP file and the file is readable.

MyClass.php in the components folder

```<code>class MyClass extends CApplicationComponent {

      public function get_my_info() {
      $value = '1';
          return $value;
     }

    }
</code>```

Declare in the config folder

```<code>'components'=>array(

        'user'=>array(
            // enable cookie-based authentication
            'allowAutoLogin'=>true,
        ),

                'myClass' => array(
                    'class' => 'ext.components.MyClass',
                ),
</code>```

And use in the view file

```<code><?php
        $myInfo = Yii::app()->myClass->get_my_info();
        echo $myInfo;

?>
</code>```

答: Write full path like application.modules.setting.components.*

Body:
i am new in yii framework. currently i am using yii 1.1.
now i want to create custom components and we can say than create global function which is use anywhere in the application.
According to this url 'http://www.yiiframework.com/wiki/727/updated-how-to-create-call-custom-global-function-in-whole-application/'

i am follow all steps according to above url
but i have occur a error
Alias "ext.components.MyClass" is invalid. Make sure it points to an existing PHP file and the file is readable.

MyClass.php in the components folder

class MyClass extends CApplicationComponent {

      public function get_my_info() {
      $value = '1';
          return $value;
     }

    }

Declare in the config folder

'components'=>array(

        'user'=>array(
            // enable cookie-based authentication
            'allowAutoLogin'=>true,
        ),

                'myClass' => array(
                    'class' => 'ext.components.MyClass',
                ),

And use in the view file

<?php
        $myInfo = Yii::app()->myClass->get_my_info();
        echo $myInfo;

?>


问:
How to attache a volume to kubernetes pod container like in docker?
I am new to Kubernetes but familiar with docker.

Docker Use Case

Usually, when I want to persist data I just create a volume with a name then attach it to the container, and even when I stop it then start another one with the same image I can see the data persisting.
So this is what i used to do in docker

docker volume create nginx-storage
run -it --rm -v nginx-storage:/usr/share/nginx/html -p 80:80 nginx:1.14.2
```

then I:

Create a new html file in /usr/share/nginx/html

Stop container

Run the same docker run command again (will create another container with same volume)

html file exists (which means data persisted in that volume)

Kubernetes Use Case

Usually, when I work with Kubernetes volumes I specify a PVC (PersistentVolumeClaim) and PV (PersistentVolume) using hostPath which will bind mount directory or a file from the host machine to the container.

what I want to do is reproduce the same behavior specified in the previous example (Docker Use Case) so how can I do that? Is Kubernetes creating volumes process is different from Docker? and if possible providing a YAML file would help me understand.

答:
To a first approximation, you can't (portably) do this.  Build your content into the image instead.

There are two big practical problems, especially if you're running a production-oriented system on a cloud-hosted Kubernetes:

If you look at the list of PersistentVolume types, very few of them can be used in ReadWriteMany mode.  It's very easy to get, say, an AWSElasticBlockStore volume that can only be used on one node at a time, and something like this will probably be the default cluster setup.  That means you'll have trouble running multiple pod replicas serving the same (static) data.

Once you do get a volume, it's very hard to edit its contents.  Consider the aforementioned EBS volume: you can't edit it without being logged into the node on which it's mounted, which means finding the node, convincing your security team that you can have root access over your entire cluster, enabling remote logins, and then editing the file.  That's not something that's actually possible in most non-developer Kubernetes setups.

The thing you should do instead is build your static content into a custom image.  An image registry of some sort is all but required to run Kubernetes and you can push this static content server into the same registry as your application code.

FROM nginx:1.14.2
COPY . /usr/share/nginx/html
# Base image has a working CMD, no need to repeat it
```

Then in your deployment spec, set image: registry.example.com/nginx-frontend:20220209 or whatever you've chosen to name this build of this image, and do not use volumes at all.  You'd deploy this the same way you deploy other parts of your application; you could use Helm or Kustomize to simplify the update process.

Correspondingly, in the plain-Docker case, I'd avoid volumes here.  You don't discuss how files get into the nginx-storage named volume; if you're using imperative commands like docker cp or debugging tools like docker exec, those approaches are hard to script and are intrinsically local to the system they're running on.  It's not easy to copy a Docker volume from one place to another.  Images, though, can be pushed and pulled through a registry.

Body:
I am new to Kubernetes but familiar with docker.

Docker Use Case

Usually, when I want to persist data I just create a volume with a name then attach it to the container, and even when I stop it then start another one with the same image I can see the data persisting.
So this is what i used to do in docker

docker volume create nginx-storage
run -it --rm -v nginx-storage:/usr/share/nginx/html -p 80:80 nginx:1.14.2

then I:

Create a new html file in /usr/share/nginx/html

Stop container

Run the same docker run command again (will create another container with same volume)

html file exists (which means data persisted in that volume)

Kubernetes Use Case

Usually, when I work with Kubernetes volumes I specify a PVC (PersistentVolumeClaim) and PV (PersistentVolume) using hostPath which will bind mount directory or a file from the host machine to the container.

what I want to do is reproduce the same behavior specified in the previous example (Docker Use Case) so how can I do that? Is Kubernetes creating volumes process is different from Docker? and if possible providing a YAML file would help me understand.

Body:
To a first approximation, you can't (portably) do this.  Build your content into the image instead.

There are two big practical problems, especially if you're running a production-oriented system on a cloud-hosted Kubernetes:

If you look at the list of PersistentVolume types, very few of them can be used in ReadWriteMany mode.  It's very easy to get, say, an AWSElasticBlockStore volume that can only be used on one node at a time, and something like this will probably be the default cluster setup.  That means you'll have trouble running multiple pod replicas serving the same (static) data.

Once you do get a volume, it's very hard to edit its contents.  Consider the aforementioned EBS volume: you can't edit it without being logged into the node on which it's mounted, which means finding the node, convincing your security team that you can have root access over your entire cluster, enabling remote logins, and then editing the file.  That's not something that's actually possible in most non-developer Kubernetes setups.

The thing you should do instead is build your static content into a custom image.  An image registry of some sort is all but required to run Kubernetes and you can push this static content server into the same registry as your application code.

FROM nginx:1.14.2
COPY . /usr/share/nginx/html
# Base image has a working CMD, no need to repeat it

Then in your deployment spec, set image: registry.example.com/nginx-frontend:20220209 or whatever you've chosen to name this build of this image, and do not use volumes at all.  You'd deploy this the same way you deploy other parts of your application; you could use Helm or Kustomize to simplify the update process.

Correspondingly, in the plain-Docker case, I'd avoid volumes here.  You don't discuss how files get into the nginx-storage named volume; if you're using imperative commands like docker cp or debugging tools like docker exec, those approaches are hard to script and are intrinsically local to the system they're running on.  It's not easy to copy a Docker volume from one place to another.  Images, though, can be pushed and pulled through a registry.


问:
Template partial specialization for integral non-type parameters and non-integral non-types, difference between g++ and clang

The following is a simple template partial specialization:

```<code>// #1
template <typename T, T n1, T n2>
struct foo {
    static const char* scenario() {
        return "#1 the base template";
    }
};

// #2
// partial specialization where T is unknown and n1 == n2
template <typename T, T a>
struct foo<T, a, a> {
    static const char* scenario() {
        return "#2 partial specialization";
    }
};
</code>```

The main below gets different results on g++ (6.1) and clang++ (3.8.0):

```<code>extern const char HELLO[] = "hello";
double d = 2.3;

int main() {
    cout <<   foo<int, 1, 2>                    ::scenario() << endl;
    cout <<   foo<int, 2, 2>                    ::scenario() << endl;
    cout <<   foo<long, 3, 3>                   ::scenario() << endl;
    cout <<   foo<double&, d, d>                ::scenario() << endl;
    cout <<   foo<double*, &d, &d>              ::scenario() << endl;
    cout <<   foo<double*, nullptr, nullptr>    ::scenario() << endl;
    cout <<   foo<int*, nullptr, nullptr>       ::scenario() << endl;
    cout <<   foo<nullptr_t, nullptr, nullptr>  ::scenario() << endl;
    cout <<   foo<const char*, HELLO, HELLO>    ::scenario() << endl;
}
</code>```

Results on g++ and clang++

# | The code                          | g++ (6.1)       |  clang++ (3.8.0) |

1 | foo<int, 1, 2>                    | #1 as expected  |  #1 as expected  |

2 | foo<int, 2, 2>                    | #2 as expected  |  #2 as expected  |

3 | foo<long, 3, 3>                   | #2 as expected  |  #2 as expected  |

4 | foo<double&, d, d>                | #1 -- why?      |  #2 as expected  |

5 | foo<double*, &d, &d>              | #2 as expected  |  #2 as expected  |

6 | foo<double*, nullptr, nullptr>    | #2 as expected  |  #1 -- why?      |

7 | foo<int*, nullptr, nullptr>       | #2 as expected  |  #1 -- why?      |

8 | foo<nullptr_t, nullptr, nullptr>  | #2 as expected  |  #1 -- why?      |

9 | foo<const char*, HELLO, HELLO>    | #2 as expected  |  #2 as expected  |

Which one is right?

Code: https://godbolt.org/z/4GfYqxKn3

EDIT, Dec-2021:

Along the years since the original post, the results have changed, and were even identical for gcc and clang at a certain point in time, but checking again, g++ (11.2) and clang++ (12.0.1) changed their results on references (case 4), but still differ on it. It seems that currently gcc is getting it all right and clang is wrong on the reference case.

# | The code                          | g++ (11.2)      | clang++ (12.0.1) |

1 | foo<int, 1, 2>                    | #1 as expected  |  #1 as expected  |

2 | foo<int, 2, 2>                    | #2 as expected  |  #2 as expected  |

3 | foo<long, 3, 3>                   | #2 as expected  |  #2 as expected  |

4 | foo<double&, d, d>                | #2 as expected  |  #1 -- why?      |

5 | foo<double*, &d, &d>              | #2 as expected  |  #2 as expected  |

6 | foo<double*, nullptr, nullptr>    | #2 as expected  |  #2 as expected  |

7 | foo<int*, nullptr, nullptr>       | #2 as expected  |  #2 as expected  |

8 | foo<nullptr_t, nullptr, nullptr>  | #2 as expected  |  #2 as expected  |

9 | foo<const char*, HELLO, HELLO>    | #2 as expected  |  #2 as expected  |

答:
I took the latest compilers and tried to explain the case of
foo<double&, d, d> behaver.

The foo function is declared as follow

```<code>// #1
template <typename T, T n1, T n2>
struct foo {
    static const char* scenario() {
        return "#1 the base template";
    }
};

// #2
// partial specialization where T is unknown and n1 == n2
template <typename T, T a>
struct foo<T, a, a> {
    static const char* scenario() {
        return "#2 partial specialization";
    }
};
</code>```

The issue here is that the T type gets deduced by the call immediately as double and not double& as expected, and then it is implicit cast to double &.
That's why the different compilers behave in a different way.
changing the foo function to the following will solve the issue.

```<code>// #1
template <typename T, typename std::type_identity<T>::type n1, typename std::type_identity<T>::type n2>
struct foo {
  static const char* scenario() {return "#1 the basic: template <typename T, T n1, T n2>";}
};

// #2
// partial specialization where T is unknown and n1 == n2
template <typename T, typename std::type_identity<T>::type a>
struct foo<T, a, a> {
  static const char* scenario() {return "#2 partial specialization: template<typename T, T a> foo<typename T, a, a>";}
};
</code>```

Body:
The following is a simple template partial specialization:

// #1
template <typename T, T n1, T n2>
struct foo {
    static const char* scenario() {
        return "#1 the base template";
    }
};

// #2
// partial specialization where T is unknown and n1 == n2
template <typename T, T a>
struct foo<T, a, a> {
    static const char* scenario() {
        return "#2 partial specialization";
    }
};

The main below gets different results on g++ (6.1) and clang++ (3.8.0):

extern const char HELLO[] = "hello";
double d = 2.3;

int main() {
    cout <<   foo<int, 1, 2>                    ::scenario() << endl;
    cout <<   foo<int, 2, 2>                    ::scenario() << endl;
    cout <<   foo<long, 3, 3>                   ::scenario() << endl;
    cout <<   foo<double&, d, d>                ::scenario() << endl;
    cout <<   foo<double*, &d, &d>              ::scenario() << endl;
    cout <<   foo<double*, nullptr, nullptr>    ::scenario() << endl;
    cout <<   foo<int*, nullptr, nullptr>       ::scenario() << endl;
    cout <<   foo<nullptr_t, nullptr, nullptr>  ::scenario() << endl;
    cout <<   foo<const char*, HELLO, HELLO>    ::scenario() << endl;
}

Results on g++ and clang++

# | The code                          | g++ (6.1)       |  clang++ (3.8.0) |

1 | foo<int, 1, 2>                    | #1 as expected  |  #1 as expected  |

2 | foo<int, 2, 2>                    | #2 as expected  |  #2 as expected  |

3 | foo<long, 3, 3>                   | #2 as expected  |  #2 as expected  |

4 | foo<double&, d, d>                | #1 -- why?      |  #2 as expected  |

5 | foo<double*, &d, &d>              | #2 as expected  |  #2 as expected  |

6 | foo<double*, nullptr, nullptr>    | #2 as expected  |  #1 -- why?      |

7 | foo<int*, nullptr, nullptr>       | #2 as expected  |  #1 -- why?      |

8 | foo<nullptr_t, nullptr, nullptr>  | #2 as expected  |  #1 -- why?      |

9 | foo<const char*, HELLO, HELLO>    | #2 as expected  |  #2 as expected  |

Which one is right?

Code: https://godbolt.org/z/4GfYqxKn3

EDIT, Dec-2021:

Along the years since the original post, the results have changed, and were even identical for gcc and clang at a certain point in time, but checking again, g++ (11.2) and clang++ (12.0.1) changed their results on references (case 4), but still differ on it. It seems that currently gcc is getting it all right and clang is wrong on the reference case.

# | The code                          | g++ (11.2)      | clang++ (12.0.1) |

1 | foo<int, 1, 2>                    | #1 as expected  |  #1 as expected  |

2 | foo<int, 2, 2>                    | #2 as expected  |  #2 as expected  |

3 | foo<long, 3, 3>                   | #2 as expected  |  #2 as expected  |

4 | foo<double&, d, d>                | #2 as expected  |  #1 -- why?      |

5 | foo<double*, &d, &d>              | #2 as expected  |  #2 as expected  |

6 | foo<double*, nullptr, nullptr>    | #2 as expected  |  #2 as expected  |

7 | foo<int*, nullptr, nullptr>       | #2 as expected  |  #2 as expected  |

8 | foo<nullptr_t, nullptr, nullptr>  | #2 as expected  |  #2 as expected  |

9 | foo<const char*, HELLO, HELLO>    | #2 as expected  |  #2 as expected  |

Body:
I took the latest compilers and tried to explain the case of
foo<double&, d, d> behaver.

The foo function is declared as follow

// #1
template <typename T, T n1, T n2>
struct foo {
    static const char* scenario() {
        return "#1 the base template";
    }
};

// #2
// partial specialization where T is unknown and n1 == n2
template <typename T, T a>
struct foo<T, a, a> {
    static const char* scenario() {
        return "#2 partial specialization";
    }
};

The issue here is that the T type gets deduced by the call immediately as double and not double& as expected, and then it is implicit cast to double &.
That's why the different compilers behave in a different way.
changing the foo function to the following will solve the issue.

// #1
template <typename T, typename std::type_identity<T>::type n1, typename std::type_identity<T>::type n2>
struct foo {
  static const char* scenario() {return "#1 the basic: template <typename T, T n1, T n2>";}
};

// #2
// partial specialization where T is unknown and n1 == n2
template <typename T, typename std::type_identity<T>::type a>
struct foo<T, a, a> {
  static const char* scenario() {return "#2 partial specialization: template<typename T, T a> foo<typename T, a, a>";}
};


问:
CET timezone strings to datetime
```<code>date_cet                           col1
---------------------------------------
2021-10-31 02:00:00+02:00           7.0
2021-10-31 02:00:00+02:00           7.0
2021-10-31 02:00:00+02:00           8.0
2021-10-31 02:00:00+01:00          10.0
2021-10-31 02:00:00+01:00          11.0
</code>```

I have a data frame that has columns looking similar to this. This data is imported from SQL into a Pandas data frame, and when I print out the dtypes I can see that the date_cet column is object. Since I need it further on, I want to convert it to a datetime object. However, the stuff I've tried just doesn't work, and I think it might have something to do with 1) the timezone difference and 2) the fact that this date is where DST changes (i.e. the +01:00 and +02:00).

I've tried to do stuff like this:

```<code>import datetime as dt

df["new_date"] = [dt.datetime.strptime(str(x), "%Y-%m-%d %H:%M:%S %z") for x in df["date_cet"]]

df['new_date']= pd.to_datetime(df['date_cet'])
</code>```

and a hand full of other stuff.

The first gives an error of:

```<code>ValueError: time data '2021-10-31 02:00:00+02:00' does not match format '%Y-%m-%d %H:%M:%S %z'
</code>```

And the last:

```<code>ValueError: Tz-aware datetime.datetime cannot be converted to datetime64 unless utc=True
</code>```

Basically, I have no idea how to fix this. I just need this column to become a datetime[ns, Europe/Copenhagen] type of column, but everything I've done so far doesn't work.

答:
In the datetime string ('2021-10-31 02:00:00+02:00') there is no space between %S and %z

try to change to this format - "%Y-%m-%d %H:%M:%S%z"

```<code>import datetime as dt

df["new_date"] = [dt.datetime.strptime(str(x), "%Y-%m-%d %H:%M:%S%z") for x in df["date_cet"]]

df['new_date']= pd.to_datetime(df['date_cet'])
</code>```

Update:

to fix the error try adding - utc=True:

```<code>import datetime as dt

df["new_date"] = [dt.datetime.strptime(str(x), "%Y-%m-%d %H:%M:%S%z") for x in df["date_cet"]]

df['new_date']= pd.to_datetime(df['date_cet'], utc=True)
</code>```

you can do this by one line:

```<code>df['new_date']= pd.to_datetime(df['date_cet'], format="%Y-%m-%d %H:%M:%S%z", utc=True)
</code>```

Title: CET timezone strings to datetime

Body:
date_cet                           col1
---------------------------------------
2021-10-31 02:00:00+02:00           7.0
2021-10-31 02:00:00+02:00           7.0
2021-10-31 02:00:00+02:00           8.0
2021-10-31 02:00:00+01:00          10.0
2021-10-31 02:00:00+01:00          11.0

I have a data frame that has columns looking similar to this. This data is imported from SQL into a Pandas data frame, and when I print out the dtypes I can see that the date_cet column is object. Since I need it further on, I want to convert it to a datetime object. However, the stuff I've tried just doesn't work, and I think it might have something to do with 1) the timezone difference and 2) the fact that this date is where DST changes (i.e. the +01:00 and +02:00).

I've tried to do stuff like this:

import datetime as dt

df["new_date"] = [dt.datetime.strptime(str(x), "%Y-%m-%d %H:%M:%S %z") for x in df["date_cet"]]

df['new_date']= pd.to_datetime(df['date_cet'])

and a hand full of other stuff.

The first gives an error of:

ValueError: time data '2021-10-31 02:00:00+02:00' does not match format '%Y-%m-%d %H:%M:%S %z'

And the last:

ValueError: Tz-aware datetime.datetime cannot be converted to datetime64 unless utc=True

Basically, I have no idea how to fix this. I just need this column to become a datetime[ns, Europe/Copenhagen] type of column, but everything I've done so far doesn't work.

Body:
In the datetime string ('2021-10-31 02:00:00+02:00') there is no space between %S and %z

try to change to this format - "%Y-%m-%d %H:%M:%S%z"

import datetime as dt

df["new_date"] = [dt.datetime.strptime(str(x), "%Y-%m-%d %H:%M:%S%z") for x in df["date_cet"]]

df['new_date']= pd.to_datetime(df['date_cet'])

Update:

to fix the error try adding - utc=True:

import datetime as dt

df["new_date"] = [dt.datetime.strptime(str(x), "%Y-%m-%d %H:%M:%S%z") for x in df["date_cet"]]

df['new_date']= pd.to_datetime(df['date_cet'], utc=True)

you can do this by one line:

df['new_date']= pd.to_datetime(df['date_cet'], format="%Y-%m-%d %H:%M:%S%z", utc=True)


问:
How to fill NA's when you have enough information to calculate what the NA should be in R
I've got a dataset where there are some NA's but I can manually work out what the values should be as the df is a column for name and the rest of the columns are just numbers followed by a final column with total. Only one NA appears per row at most so I can work out what the value should be by using the total column and the sum of all the other columns. Just wondering what would be the best way to fill these NA's without having to hardcode one by one as the df I'm using is pretty big

example df:

```<code>df = structure(list(city = c("sydney", "new york", "london", "beijing", "paris", "madrid"),
                    year = c(2005:2010),
                    A = c(1, 4, 5 , NA, 2, 1),
                    B = c(3, NA, 4 , 9, 0, 6),
                    C = c(3, 4 , 6, 1, 8, NA),
                    total = c(NA, 10, 15, 14, NA, 15)),
               class = "data.frame", row.names = c(NA, -6L))

df
</code>```

Body:
I've got a dataset where there are some NA's but I can manually work out what the values should be as the df is a column for name and the rest of the columns are just numbers followed by a final column with total. Only one NA appears per row at most so I can work out what the value should be by using the total column and the sum of all the other columns. Just wondering what would be the best way to fill these NA's without having to hardcode one by one as the df I'm using is pretty big

example df:

df = structure(list(city = c("sydney", "new york", "london", "beijing", "paris", "madrid"),
                    year = c(2005:2010),
                    A = c(1, 4, 5 , NA, 2, 1),
                    B = c(3, NA, 4 , 9, 0, 6),
                    C = c(3, 4 , 6, 1, 8, NA),
                    total = c(NA, 10, 15, 14, NA, 15)),
               class = "data.frame", row.names = c(NA, -6L))

df

Body:
Here is a base R solution with apply.

df = structure(list(city = c("sydney", "new york", "london", "beijing", "paris", "madrid"),
                    year = c(2005:2010),
                    A = c(1, 4, 5 , NA, 2, 1),
                    B = c(3, NA, 4 , 9, 0, 6),
                    C = c(3, 4 , 6, 1, 8, NA),
                    total = c(NA, 10, 15, 14, NA, 15)),
               class = "data.frame", row.names = c(NA, -6L))

df[-(1:2)] <- t(apply(df[-(1:2)], 1, \(x) {
  if(is.na(x[4])) {
    x[4] <- sum(x[-4])
  } else if(anyNA(x[-4])) {
      x[-4][is.na(x[-4])] <- x[4] - sum(x[-4][!is.na(x[-4])])
  }
  x
}))
df
#>       city year A B C total
#> 1   sydney 2005 1 3 3     7
#> 2 new york 2006 4 2 4    10
#> 3   london 2007 5 4 6    15
#> 4  beijing 2008 4 9 1    14
#> 5    paris 2009 2 0 8    10
#> 6   madrid 2010 1 6 8    15

Created on 2022-02-09 by the reprex package (v2.0.1)


问:
SAP Function Listener in Muleosft
Need help to configure Function Listener for SAP in Mulesoft.  Can anyone help for the cofiguration details including Gateway host, Gate service, Program Id, Connection count, Targeted function.  And who can share those details?</p>

答:
I have the same issue, as the MuleSoft examples are inconsistent in the values used, so it's a bit of a guessing game as to how to configure them!

The Gateway Host is your SAP instance host machine, the Gateway Service happens to be 3300 on my host, and the Program ID is a value of your own choosing which you share with whomever is calling your IDoc server. (Be aware that if you want to receive a different IDoc with a different IDoc listener, you need to use a different Program ID.)

I got this to work yesterday for MATMAS05 IDoc.

Title: SAP Function Listener in Muleosft


问:
What does error mean? : "Forbidden (Referer checking failed - no Referer.):"
I have a website running, which appears to be working fine. Yet, now I've seen this error in the logs for the fist time.

```<code>Forbidden (Referer checking failed - no Referer.): /pointlocations/
[pid: 4143|app: 0|req: 148/295] 104.176.70.209 () {48 vars in 1043 bytes} [Wed Jul 26 19:49:35 2017] POST /pointlocations/?participant=A2TYLR23CHRULH&assignmentId=3P4MQ7TPPYF65ANAUBF8A3B38A0BB6 => generated 2737 bytes in 2 msecs (HTTP/1.1 403) 1 headers in 51 bytes (1 switches on core 0)
</code>```

It happens when posting to /pointlocations/, but only for one specific person ( each participant is unique per account, so I know it's only one person, having this problem repeatedly. Over 500+ other participant have had no such problem/error.

What does this error mean, what is likely causing it and can I fix this?

答:
Upgrading Django might fix the missing Referer error (as it's sent voluntarily by the client depending on Referrer-Policy).

As of Django 4.0 (release notes), the backend will first check the Origin header before falling back to the Referer header (source):

CsrfViewMiddleware verifies the Origin header, if provided by the browser, against the current host and the CSRF_TRUSTED_ORIGINS setting. This provides protection against cross-subdomain attacks.

In addition, for HTTPS requests, if the Origin header isn’t provided, CsrfViewMiddleware performs strict referer checking. This means that even if a subdomain can set or modify cookies on your domain, it can’t force a user to post to your application since that request won’t come from your own exact domain.

Body:
I have a website running, which appears to be working fine. Yet, now I've seen this error in the logs for the fist time.

Forbidden (Referer checking failed - no Referer.): /pointlocations/
[pid: 4143|app: 0|req: 148/295] 104.176.70.209 () {48 vars in 1043 bytes} [Wed Jul 26 19:49:35 2017] POST /pointlocations/?participant=A2TYLR23CHRULH&assignmentId=3P4MQ7TPPYF65ANAUBF8A3B38A0BB6 => generated 2737 bytes in 2 msecs (HTTP/1.1 403) 1 headers in 51 bytes (1 switches on core 0)

It happens when posting to /pointlocations/, but only for one specific person ( each participant is unique per account, so I know it's only one person, having this problem repeatedly. Over 500+ other participant have had no such problem/error.

What does this error mean, what is likely causing it and can I fix this?


问:
Django Form Field for a list of strings
I need a Django Form Field which will take a list of strings.

I'll iterate over this list and create a new model object for each string.

I can't do a Model Multiple Choice Field, because the model objects aren't created until after form submission, and I can't do a Multiple Choice Field, because I need to accept arbitrary strings, not just a series of pre-defined options.

Anyone know how to do this?

答: In my case to process list of strings I used forms.JSONField(decoder="array") in my forms.py in form class

Title: Django Form Field for a list of strings


问:
How to put Nextcloud in kubernetes in maintenance mode
I'm trying to migrate my Nextcloud instance to a kubernetes cluster. I've succesfully deployed a Nextcloud instance using openEBS-cStor storage. Before I can "kubectl cp" my old files to the cluster, I need to put Nextcloud in maintenance mode.

This is what I've tried so far:

Shell access to pod

Navigate to folder

Run OCC command to put next cloud in maintenance mode

These are the commands I used for the OCC way:

kubectl exec --stdin --tty -n nextcloud nextcloud-7ff9cf449d-rtlxh -- /bin/bash
su -c 'php occ maintenance:mode --on' www-data
# This account is currently not available.
```

Any tips on how to put Nextcloud in maintenance mode would be appreciated!

答:
The su command fails because there is no shell associated with the www-data user.

What worked for me is explicitly specifying the shell in the su command:

su -s /bin/bash www-data -c "php occ maintenance:mode --on"
```

Body:
I'm trying to migrate my Nextcloud instance to a kubernetes cluster. I've succesfully deployed a Nextcloud instance using openEBS-cStor storage. Before I can "kubectl cp" my old files to the cluster, I need to put Nextcloud in maintenance mode.

This is what I've tried so far:

Shell access to pod

Navigate to folder

Run OCC command to put next cloud in maintenance mode

These are the commands I used for the OCC way:

kubectl exec --stdin --tty -n nextcloud nextcloud-7ff9cf449d-rtlxh -- /bin/bash
su -c 'php occ maintenance:mode --on' www-data
# This account is currently not available.

Any tips on how to put Nextcloud in maintenance mode would be appreciated!


问:
Extracting individual growth constants using population growth curve model in R
I would like to derive individual growth rates from our growth model directly, similar to this OP and this OP.

I am working with a dataset that contains the age and weight (wt) measurements for ~2000 individuals in a population. Each individual is represented by a unique id number.

A sample of the data can be found here. Here is what the data looks like:

```<code>          id   age    wt
        1615     6      15
        3468     32     61
        1615     27     50
        1615     60     145
        6071     109    209
        6071     125    207
       10645     56     170
       10645     118    200
</code>```

I have developed a non-linear growth curve to model growth for this dataset (at the population level). It looks like this:

```<code>wt~ A*atan(k*age - t0) + m
</code>```

which predicts weight (wt) for a given age and has modifiable parameters A, t0, and m. I have fit this model to the dataset at the population level using a nlme regression fit where I specified individual id as a random effect and used pdDiag to specify each parameter as uncorrelated. (Note: the random effect would need to be dropped when looking at the individual level.)

The code for this looks like:

```<code>nlme.k = nlme(wt~ A*atan(k*age - t0) + m,
data = df,
fixed = A+k+t0+m~1,
random = list(id = pdDiag(A+t0+k+m~1)), #cannot include when looking at the individual level
start = c(A = 99.31,k = 0.02667, t0 = 1.249, m = 103.8), #these values are what we are using at the population level # might need to be changed for individual models
na.action = na.omit,
control = nlmeControl(maxIter = 200, pnlsMaxIter = 10, msMaxIter = 100))
</code>```

I have our population level growth model (nlme.k), but I would like to use it to derive/extract individual values for each growth constant.

How can I extract individual growth constants for each id using my population level growth model (nlme.k)? Note that I don't need it to be a solution that uses nlme, that is just the model I used for the population growth model.

Any suggestions would be appreciated!

答:
I think this is not possible due to the nature on how random effects are designed. According to this post the effect size (your growth constant) is estimated using partial pooling. This involves using data points from other groups. Thus you can not estimate the effect size of each group (your individual id).
Strictly speaking (see here) random effects are not really a part of the model at all, but more a part of the error.

However, you can estimate the R2 for all groups together. If you want it on an individual level (e.g. parameter estiamtes for id 1), then just run the same model only on all data points of this particular individual. This give you n models with n parameter sets for n individuals.

Body:
I would like to derive individual growth rates from our growth model directly, similar to this OP and this OP.

I am working with a dataset that contains the age and weight (wt) measurements for ~2000 individuals in a population. Each individual is represented by a unique id number.

A sample of the data can be found here. Here is what the data looks like:

          id   age    wt
        1615     6      15
        3468     32     61
        1615     27     50
        1615     60     145
        6071     109    209
        6071     125    207
       10645     56     170
       10645     118    200

I have developed a non-linear growth curve to model growth for this dataset (at the population level). It looks like this:

wt~ A*atan(k*age - t0) + m

which predicts weight (wt) for a given age and has modifiable parameters A, t0, and m. I have fit this model to the dataset at the population level using a nlme regression fit where I specified individual id as a random effect and used pdDiag to specify each parameter as uncorrelated. (Note: the random effect would need to be dropped when looking at the individual level.)

The code for this looks like:

nlme.k = nlme(wt~ A*atan(k*age - t0) + m,
data = df,
fixed = A+k+t0+m~1,
random = list(id = pdDiag(A+t0+k+m~1)), #cannot include when looking at the individual level
start = c(A = 99.31,k = 0.02667, t0 = 1.249, m = 103.8), #these values are what we are using at the population level # might need to be changed for individual models
na.action = na.omit,
control = nlmeControl(maxIter = 200, pnlsMaxIter = 10, msMaxIter = 100))

I have our population level growth model (nlme.k), but I would like to use it to derive/extract individual values for each growth constant.

How can I extract individual growth constants for each id using my population level growth model (nlme.k)? Note that I don't need it to be a solution that uses nlme, that is just the model I used for the population growth model.

Any suggestions would be appreciated!