问:
Proper way to consume and immediately publish RabbitMQ messages from queue-to-queue?
What is the proper method of consuming a message, processing it, and then publishing it? I run into a lot of unacknowledged messages and I believe there is some blocking going on. Trying to understand the best practice for something like this.

I'm working on a set of services that will process around 50k requests a day. I have decided to use RabbitMQ and three Windows Services written in Dotnet Core 3.1.

I have diagrammed the process but essentially it works like this:

an external service publishes the message to Queue #1

service A is "listening" on Queue #1 and consumes any messages that arrive in the Queue. A database call is made and then Service A passes message to Queue #2

service B is "listening" on Queue #2 and consumes any messages that arrive in the Queue. Some internal processing is done and then Service B passes message to Queue #3

service C is "listening" on Queue #2 and consumes any messages that arrive in the Queue. Some internal processing is done and then Service C pushes message to database

Code example is below image

```<code>protected override void OnStart(string[] args)
    {

        logger.LogInformation("Starting Service ...");

        base.OnStart(args);
        string queue = "Queue_StageOne";

        this.connection = factory.CreateConnection();
        this.channel = connection.CreateModel();
        this.publishingChannel = connection.CreateModel();
        this.channel.BasicQos(0, 1, false);

        consumer = new AsyncEventingBasicConsumer(channel);
        consumer.Received += Consumer_Recieved;

        this.channel.BasicConsume(queue: queue, autoAck: false, consumer: consumer);
    }

    private async Task Consumer_Recieved(object sender, BasicDeliverEventArgs @event)
    {
        var body = @event.Body;
        var message = Encoding.UTF8.GetString(body.ToArray());
        var inboundTransferObject = PatientObject.ConvertFromJson(message);

        //logger.LogInformation("Processed message " + inboundTransferObject.WebhookMessageId);

        //ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault;
        //X509Certificate2 cert = new X509Certificate2(config["CertificationPath"].ToString(), config["PFXPassword"]);

        //JToken access_token = GetAccessToken(cert);

        //JObject payerData = GetPractitionerData(inboundTransferObject, cert, access_token);

        //inboundTransferObject = ProcessPractitioner(inboundTransferObject, payerData);

        var outboundTransferObject = Encoding.ASCII.GetBytes(inboundTransferObject.ConvertToJson());

        channel.BasicAck(deliveryTag: @event.DeliveryTag, multiple: false);
        publishingChannel.BasicPublish(exchange: "ExchangeA", routingKey: "Queue_StageTwo", basicProperties: null, body:outboundTransferObject);
        await Task.Delay(250);

    }
</code>```

答:
It's not clear exactly what you're asking here but one thing that does stand out is that your services should not acknowledge the inbound message unless and until they've completed all their processing steps, and that includes publishing follow-on outbound messages. In your code sample you appear to acknowledge the inbound message before publishing the outbound message.

That however does not explain the symptom you described "I run into a lot of unacknowledged messages". When do you run into these? How many is a lot? Have you set a prefetch limit on your channel? For testing purposes, you could try setting your prefetch count to one to ensure that only one message is in-flight at a time.

channel.BasicQos(1, global: true)

Please see this section of the RabbitMQ documentation:

"Because messages are sent (pushed) to clients asynchronously, there is usually more than one message "in flight" on a channel at any given moment. In addition, manual acknowledgements from clients are also inherently asynchronous in nature. So there's a sliding window of delivery tags that are unacknowledged. Developers would often prefer to cap the size of this window to avoid the unbounded buffer problem on the consumer end. This is done by setting a "prefetch count" value using the basic.qos method. The value defines the max number of unacknowledged deliveries that are permitted on a channel. Once the number reaches the configured count, RabbitMQ will stop delivering more messages on the channel unless at least one of the outstanding ones is acknowledged."

Body:
What is the proper method of consuming a message, processing it, and then publishing it? I run into a lot of unacknowledged messages and I believe there is some blocking going on. Trying to understand the best practice for something like this.

I'm working on a set of services that will process around 50k requests a day. I have decided to use RabbitMQ and three Windows Services written in Dotnet Core 3.1.

I have diagrammed the process but essentially it works like this:

an external service publishes the message to Queue #1

service A is "listening" on Queue #1 and consumes any messages that arrive in the Queue. A database call is made and then Service A passes message to Queue #2

service B is "listening" on Queue #2 and consumes any messages that arrive in the Queue. Some internal processing is done and then Service B passes message to Queue #3

service C is "listening" on Queue #2 and consumes any messages that arrive in the Queue. Some internal processing is done and then Service C pushes message to database

Code example is below image

protected override void OnStart(string[] args)
    {

        logger.LogInformation("Starting Service ...");

        base.OnStart(args);
        string queue = "Queue_StageOne";

        this.connection = factory.CreateConnection();
        this.channel = connection.CreateModel();
        this.publishingChannel = connection.CreateModel();
        this.channel.BasicQos(0, 1, false);

        consumer = new AsyncEventingBasicConsumer(channel);
        consumer.Received += Consumer_Recieved;

        this.channel.BasicConsume(queue: queue, autoAck: false, consumer: consumer);
    }

    private async Task Consumer_Recieved(object sender, BasicDeliverEventArgs @event)
    {
        var body = @event.Body;
        var message = Encoding.UTF8.GetString(body.ToArray());
        var inboundTransferObject = PatientObject.ConvertFromJson(message);

        //logger.LogInformation("Processed message " + inboundTransferObject.WebhookMessageId);

        //ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault;
        //X509Certificate2 cert = new X509Certificate2(config["CertificationPath"].ToString(), config["PFXPassword"]);

        //JToken access_token = GetAccessToken(cert);

        //JObject payerData = GetPractitionerData(inboundTransferObject, cert, access_token);

        //inboundTransferObject = ProcessPractitioner(inboundTransferObject, payerData);

        var outboundTransferObject = Encoding.ASCII.GetBytes(inboundTransferObject.ConvertToJson());

        channel.BasicAck(deliveryTag: @event.DeliveryTag, multiple: false);
        publishingChannel.BasicPublish(exchange: "ExchangeA", routingKey: "Queue_StageTwo", basicProperties: null, body:outboundTransferObject);
        await Task.Delay(250);

    }


来源: stackexchange

问:
How to escape nested single quotes inside back tick or back quote
Let's say we have the following template literal in ES6.

```<code>`'{"0": "It's Friday today"}'`
</code>```

How do we escape the single quote in the word It's

Also, let's say we have the following template literal:

```<code>`'{"0": "Thursday\nFriday"}'`
</code>```

How do we escape the \n in the above.

答:
1: Use a \ '{"0": "It\'s Friday today"}'
2: Again use \ '{"0": "Thursday\\nFriday"}'

ContentLicense: CC BY-SA 4.0

Body:
Let's say we have the following template literal in ES6.

`'{"0": "It's Friday today"}'`

How do we escape the single quote in the word It's

Also, let's say we have the following template literal:

`'{"0": "Thursday\nFriday"}'`

How do we escape the \n in the above.


问:
How to represent clock
Is there a built in way to represent clock in dart or flutter? I only want to represent time in 24 hours clock.

P.S. I am currently rolling my own solution because I needed a static, locale insensitive clock which is pretty easy. But I was just looking if there is a way.

P.P.S I owned the backend. So I was able to tweak it to return date.

Old question: I am getting a time back from an API which I want to parse in my flutter app. I had a look at DateTime class but there is no apparent method to parse time as I am not interested in the date. Is there a way to represent only time and parse it in dart? Ex- 20:05:00 which should mean 5 minutes past 8 o'clock.

P.S This is my implementation

extension NumberUtil on int {
  bool isBetween(int lowerBound, int upperBound) {
    /// Checks if an int is between lower and upper bound both inclusive
    return this >= lowerBound && this <= upperBound;
  }
}

class Time {
  final int hours, minutes, seconds;

  Time(this.hours, this.minutes, this.seconds) {
    assert( hours.isBetween(0, 24) && minutes.isBetween(0, 60) && seconds.isBetween(0, 60) );
  }

  factory Time.parse(String string) {
    /// String should be in 24 hour format: hh:mm:ss. The caller is responsible
    /// for catching the parsing exception because:
    /// 1. It should almost never occur.
    /// 2. Because this is a UI app, the UI is most suited to handle that by
    /// displaying a "something went wrong" dialog

    final temp = string.split(':');

    assert (temp.length == 3);
    return Time(
      int.parse(temp[0]),
      int.parse(temp[1]),
      int.parse(temp[2]),
    );
  }

  int compareTo(Time t) {
    /// Performs a 3 way comparison between the this and t. Returns 0 if the two
    /// objects are same. Returns 1 if this is greater than t. Returns -1 otherwise

    if (this.hours > t.hours) return 1;
    if (this.hours < t.hours) return -1;

    /// at this point hours is same

    if (this.minutes > t.minutes) return 1;
    if (this.minutes < t.minutes) return -1;

    /// At this point minutes are same

    if (this.seconds > t.seconds) return 1;
    if (this.seconds < t.seconds) return -1;

    /// At this point everything is same
    return 0;
  }
}
```

答:
Do you mean this?

```<code>currentTime = DateTime.now();
targetTime = DateTime.parse('here some times format');

currentTime.difference(targetTime)  or  currentTime.difference(targetTime).inHours // this??
</code>```

or

Do you find this package
https://pub.dev/packages/timeago

Title: How to represent clock

Body:
Do you mean this?

currentTime = DateTime.now();
targetTime = DateTime.parse('here some times format');

currentTime.difference(targetTime)  or  currentTime.difference(targetTime).inHours // this??

or

Do you find this package
https://pub.dev/packages/timeago


问:
Confused by a very simple if / else statement in perl
```<code>print "content-type: text/html \n\n";   #The header
$file = "newtext.txt";
if (unlink($file) == 0) {
    print "File deleted successfully.";
} else {
    print "File was not deleted.";
}
</code>```

This is some code I picked up from tizag.  The part I don't understand is that the bool value for true is 1, and false is 0.  So why is it when I successfully delete the file I'm checking to see if it returns a 0?

答: The snippet can simply be wrong, cause unlink returns the number of files successfully deleted.

ContentLicense: CC BY-SA 3.0

Body:
print "content-type: text/html \n\n";   #The header
$file = "newtext.txt";
if (unlink($file) == 0) {
    print "File deleted successfully.";
} else {
    print "File was not deleted.";
}

This is some code I picked up from tizag.  The part I don't understand is that the bool value for true is 1, and false is 0.  So why is it when I successfully delete the file I'm checking to see if it returns a 0?


问:
Error compiling with pyinstaller, "Error loading python38.dll"
I am compiling my first GUI Application, I am using pyinstaller because it is the one I know, it generates the .exe file.
I am using Python 3.8.1 (tags / v3.8.1: 1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32 bit (Intel)] on win32 on AMD 64Bits.

```<code>from tkcalendar import Calendar, DateEntry
from tkinter.ttk import *
from tkinter import messagebox
from tkinter import *
import datetime
import sqlite3
</code>```

Then when I go to run the exe file I get this error, please, can you tell me what it refers to or where I can find what the error is about or if there is another more effective way to compile.

This is the text generated by the compiler, I can't read it, I don't see if it describes the error I have here.

I appreciate any help, greetings and thanks in advance. If you can recommend me to continue with pyinstaller or if you can recommend another compiler, I have been trying to compile for 1 week and I feel stagnant since I do not advance, I do not get the error.

答:
I use cx_Freeze and I made a GUI which converts py to exe :

```<code>import os
import time
from tkinter import *
from tkinter.filedialog import askopenfile
from tkinter.scrolledtext import ScrolledText
from tkinter.messagebox import *

tk = Tk()
tk.title(".py -> .exe")
tk.resizable(0, 0)

f = None

def browse():
    global f, btn
    try:
        f = askopenfile().name # get the py file
        btn["text"] = os.path.basename(f)
    except:
        f = None

def convert():
    global f, btn, ver, des
    OK = False
    try:
        dots = 0
        for x in ver.get(): # check the number of dots in version
            if x == ".":
                dots += 1
            else:
                x = int(x)
        if dots < 4:
            OK = True
    except:
        showwarning("","The version must be int.int.int... with max 3 dots.")
    if OK:
        try:
            if f is None:
                showwarning("","You must choose a file to convert.")
                btn.focus()
            elif ver.get() == "":
                showwarning("","You must enter a version.")
                ver.focus()
            else:
                with open("setup.py", "w") as f_: # fill a new file setup.py (installer)
                    f_.write("NAME = '" + f +
                        "'\nVERSION = '" + ver.get() +
                        "'\nDESCRIPTION = \"\"\"" + des.get(1.0, "end") +
                        "\"\"\"\nFILENAME = '" + f +
                        "'\n\nfrom cx_Freeze import setup, Executable\nsetup(name = NAME, version = VERSION, description = DESCRIPTION, executables = [Executable(FILENAME)])")
                with open("setup.bat", "w") as f_: # fill a new file setup.bat (installation launcher)
                    f_.write("py setup.py build")
                os.system("setup.bat")
                btn["text"] = "Browse..."
                f = None
                os.remove("setup.py")  # remove files created in this script
                os.remove("setup.bat") #
                showinfo("Information","End. Your exe file is in folder 'build'.")
        except:
            showerror("Error","Error detected.")

# create GUI

Label(text="File to convert").grid(column=0, row=0, sticky="w")

btn = Button(text="Browse...", command=browse)
btn.grid(column=1, row=0)

Label(text="Version").grid(column=0, row=2, sticky="w")

ver = Entry()
ver.grid(column=1, row=2, padx=5)

Label(text="Description").grid(column=0, row=3, sticky="w")

des = ScrolledText(width=15, height=5, wrap=WORD)
des.grid(column=1, row=3)

Label(text="Convert to .exe").grid(column=0, row=4, sticky="w")

Button(text="Convert", command=convert).grid(column=1, row=4, pady=5)

tk.mainloop()
</code>```

Don't forget to install cx_Freeze !

Body:
I am compiling my first GUI Application, I am using pyinstaller because it is the one I know, it generates the .exe file.
I am using Python 3.8.1 (tags / v3.8.1: 1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32 bit (Intel)] on win32 on AMD 64Bits.

from tkcalendar import Calendar, DateEntry
from tkinter.ttk import *
from tkinter import messagebox
from tkinter import *
import datetime
import sqlite3

Then when I go to run the exe file I get this error, please, can you tell me what it refers to or where I can find what the error is about or if there is another more effective way to compile.

This is the text generated by the compiler, I can't read it, I don't see if it describes the error I have here.

I appreciate any help, greetings and thanks in advance. If you can recommend me to continue with pyinstaller or if you can recommend another compiler, I have been trying to compile for 1 week and I feel stagnant since I do not advance, I do not get the error.

Body:
I use cx_Freeze and I made a GUI which converts py to exe :

import os
import time
from tkinter import *
from tkinter.filedialog import askopenfile
from tkinter.scrolledtext import ScrolledText
from tkinter.messagebox import *

tk = Tk()
tk.title(".py -> .exe")
tk.resizable(0, 0)

f = None

def browse():
    global f, btn
    try:
        f = askopenfile().name # get the py file
        btn["text"] = os.path.basename(f)
    except:
        f = None

def convert():
    global f, btn, ver, des
    OK = False
    try:
        dots = 0
        for x in ver.get(): # check the number of dots in version
            if x == ".":
                dots += 1
            else:
                x = int(x)
        if dots < 4:
            OK = True
    except:
        showwarning("","The version must be int.int.int... with max 3 dots.")
    if OK:
        try:
            if f is None:
                showwarning("","You must choose a file to convert.")
                btn.focus()
            elif ver.get() == "":
                showwarning("","You must enter a version.")
                ver.focus()
            else:
                with open("setup.py", "w") as f_: # fill a new file setup.py (installer)
                    f_.write("NAME = '" + f +
                        "'\nVERSION = '" + ver.get() +
                        "'\nDESCRIPTION = \"\"\"" + des.get(1.0, "end") +
                        "\"\"\"\nFILENAME = '" + f +
                        "'\n\nfrom cx_Freeze import setup, Executable\nsetup(name = NAME, version = VERSION, description = DESCRIPTION, executables = [Executable(FILENAME)])")
                with open("setup.bat", "w") as f_: # fill a new file setup.bat (installation launcher)
                    f_.write("py setup.py build")
                os.system("setup.bat")
                btn["text"] = "Browse..."
                f = None
                os.remove("setup.py")  # remove files created in this script
                os.remove("setup.bat") #
                showinfo("Information","End. Your exe file is in folder 'build'.")
        except:
            showerror("Error","Error detected.")

# create GUI

Label(text="File to convert").grid(column=0, row=0, sticky="w")

btn = Button(text="Browse...", command=browse)
btn.grid(column=1, row=0)

Label(text="Version").grid(column=0, row=2, sticky="w")

ver = Entry()
ver.grid(column=1, row=2, padx=5)

Label(text="Description").grid(column=0, row=3, sticky="w")

des = ScrolledText(width=15, height=5, wrap=WORD)
des.grid(column=1, row=3)

Label(text="Convert to .exe").grid(column=0, row=4, sticky="w")

Button(text="Convert", command=convert).grid(column=1, row=4, pady=5)

tk.mainloop()

Don't forget to install cx_Freeze !


问:
Querying a sub-collection in firestore using cloud functions
I am fairly new to cloud functions and I am trying to create a notifications feature in my app. The notifications are stored in a sub-collection. The error shown at the logs is

TypeError: Cannot read property 'first_name' of undefined at
  Promise.all.then.result (/srv/index.js:29:41).

What could be the issue?

```<code>'use-strict'

const functions = require('firebase-functions');
const admin = require ('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.firestore.document("Employee_Details/{user_id}/Notifications/{notification_id}")
.onWrite((change , context) =>{

  const user_id = context.params.user_id;
  const notification_id = context.params.notification_id;

  //console.log("User ID:" + user_id + "| Notification ID : " + notification_id);

  return admin.firestore().collection("Employee_Details").doc(user_id).collection("Notifications").doc(notification_id).get().then(queryResult => {

    const from_user_id = queryResult.data().from;

    const from_data = admin.firestore().collection("Employee_Details").doc(from_user_id).get();
    const to_data = admin.firestore().collection("Employee_Details").doc(user_id).get();

  //  console.log("FROM_DAT:" + from_data + "TO_DATA:" + to_data);

    return Promise.all([from_data , to_data]).then(result => {

      const from_name = result[0].data().first_name;
      const to_name =  result[1].data().first_name;

      return console.log("FROM: "+ from_name + "TO:" + to_name);

    });

  });

});
</code>```

答:
If the screenshots you have attached belong to the values you are trying to retrieve, there's no document in Employee_Details with the id at Employee_Details.Gh82W1.Notifications.KR0CN4.from. This is why result[0] is undefined, because it couldn't retrieve anything.

Is there any reason why you think you are using old syntax? It seems correct to me. You are using the same methods as in the sample code for nodejs. The only change I would do is to avoid using admin.firestore() every time. Something like this:

```<code>const db = admin.firestore();
const from_data = db.collection("Employee_Details").doc(from_user_id).get();
const to_data = db.collection("Employee_Details").doc(user_id).get();
</code>```

But that's a personal preference.

Body:
I am fairly new to cloud functions and I am trying to create a notifications feature in my app. The notifications are stored in a sub-collection. The error shown at the logs is

TypeError: Cannot read property 'first_name' of undefined at
  Promise.all.then.result (/srv/index.js:29:41).

What could be the issue?

'use-strict'

const functions = require('firebase-functions');
const admin = require ('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.firestore.document("Employee_Details/{user_id}/Notifications/{notification_id}")
.onWrite((change , context) =>{

  const user_id = context.params.user_id;
  const notification_id = context.params.notification_id;

  //console.log("User ID:" + user_id + "| Notification ID : " + notification_id);

  return admin.firestore().collection("Employee_Details").doc(user_id).collection("Notifications").doc(notification_id).get().then(queryResult => {

    const from_user_id = queryResult.data().from;

    const from_data = admin.firestore().collection("Employee_Details").doc(from_user_id).get();
    const to_data = admin.firestore().collection("Employee_Details").doc(user_id).get();

  //  console.log("FROM_DAT:" + from_data + "TO_DATA:" + to_data);

    return Promise.all([from_data , to_data]).then(result => {

      const from_name = result[0].data().first_name;
      const to_name =  result[1].data().first_name;

      return console.log("FROM: "+ from_name + "TO:" + to_name);

    });

  });

});

Body:
If the screenshots you have attached belong to the values you are trying to retrieve, there's no document in Employee_Details with the id at Employee_Details.Gh82W1.Notifications.KR0CN4.from. This is why result[0] is undefined, because it couldn't retrieve anything.

Is there any reason why you think you are using old syntax? It seems correct to me. You are using the same methods as in the sample code for nodejs. The only change I would do is to avoid using admin.firestore() every time. Something like this:

const db = admin.firestore();
const from_data = db.collection("Employee_Details").doc(from_user_id).get();
const to_data = db.collection("Employee_Details").doc(user_id).get();

But that's a personal preference.


答:
You don't have to escape either of them, unless you want to use the contents of the template literal as a string literal quoted with a single quote at some point. Which looks really suspect: Never manually create JSON strings (and if you do, don't do it wrapped in a string literal in a template literal! :-) ). But if you're looking to define that string literal within the template literal here's how to do the escaping at the string literal level:

To escape the ' in It's in the string literal the template will define, you need to put a backslash in front of it. But because backslashes are escapes in template literals, you need to escape the backslash so it's not consumed by the template literal and later is used when evaluating the string literal. So:

// Define the template literal:
const s1 = `'{"0": "It\\'s Friday today"}'`;
// Escaped backslash −^^
console.log(s1);

// Evaluate the single-quoted string literal it defined:
const s2 = eval("(" + s1 + ")");
console.log(s2);

// Since that defined a string containing JSON, let's parse it:
const obj = JSON.parse(s2);
console.log(obj[0]);```
</div>
</div>
</p>

<p>In the second example with the <code>\n</code>, that <code>\n</code> escape sequence is being consumed at the template literal level, meaning the template literal contains a newline. But you want it not to be a newline from the template literal's perspective, so you...escape it: <code>\\n</code>. Now it's not a newline to the template literal anymore, but it is to the single-quoted string literal. Now it's the same as <code>It's</code> above: If you don't want the single-quoted string literal to consume the <code>\n</code> esape sequence, you need to escape it. That means you end up with <code>\\\\n</code>:</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>// Define the template literal:
// 1st escaped backslash −−−vv
const s1 = `'{"0": "Thursday\\\\nFriday"}'`;
// 2nd escaped backslash −−−−−^^
console.log(s1);

// Evaluate the single-quoted string literal it defined:
const s2 = eval("(" + s1 + ")");
console.log(s2);

// Since that defined a string containing JSON, let's parse it:
const obj = JSON.parse(s2);
console.log(obj[0]);</code>```

Title: How to escape nested single quotes inside back tick or back quote

Body:
You don't have to escape either of them, unless you want to use the contents of the template literal as a string literal quoted with a single quote at some point. Which looks really suspect: Never manually create JSON strings (and if you do, don't do it wrapped in a string literal in a template literal! :-) ). But if you're looking to define that string literal within the template literal here's how to do the escaping at the string literal level:

To escape the ' in It's in the string literal the template will define, you need to put a backslash in front of it. But because backslashes are escapes in template literals, you need to escape the backslash so it's not consumed by the template literal and later is used when evaluating the string literal. So:

// Define the template literal:
const s1 = `'{"0": "It\\'s Friday today"}'`;
// Escaped backslash −^^
console.log(s1);

// Evaluate the single-quoted string literal it defined:
const s2 = eval("(" + s1 + ")");
console.log(s2);

// Since that defined a string containing JSON, let's parse it:
const obj = JSON.parse(s2);
console.log(obj[0]);

In the second example with the \n, that \n escape sequence is being consumed at the template literal level, meaning the template literal contains a newline. But you want it not to be a newline from the template literal's perspective, so you...escape it: \\n. Now it's not a newline to the template literal anymore, but it is to the single-quoted string literal. Now it's the same as It's above: If you don't want the single-quoted string literal to consume the \n esape sequence, you need to escape it. That means you end up with \\\\n:

// Define the template literal:
// 1st escaped backslash −−−vv
const s1 = `'{"0": "Thursday\\\\nFriday"}'`;
// 2nd escaped backslash −−−−−^^
console.log(s1);

// Evaluate the single-quoted string literal it defined:
const s2 = eval("(" + s1 + ")");
console.log(s2);

// Since that defined a string containing JSON, let's parse it:
const obj = JSON.parse(s2);
console.log(obj[0]);


问:
cURL - Badly formed request, unable to translate bytes... to Unicode
I need a snippet of cURL to run from the Command Prompt or GitBash on Windows 10, but getting an "Invalid Request" error. I am calling an API and I have tested my credentials another way, so I know those are correct. I was thinking maybe my code snippet is flawed in some way.

Note: I am unable to run single quotes without error, so I escaped them in the body. I also kept getting globbing errors, so I escaped the "{" and "[" parts. I ran the command with verbose, to get a longer print out. Is my snippet wrong?

```<code>$ curl -v -X POST "https://<ACCOUNT-NAME>.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/languages" -H "Ocp-Apim-Subscription-Key:<KEY>" -H "Content-Type:application/json" --data-raw "\{documents:\[\{id:1,text:\"This is a document written in English.\"\},\{id:2,text:\"Este es un document escrito en Español.\"\},\{id:3,text:\"这是一个用中文写的文件\"\}\]\}"

Note: Unnecessary use of -X or --request, POST is already inferred.
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0*   Trying 52.229.16.14:443...
* TCP_NODELAY set
* Connected to <ACCOUNT-NAME>.cognitiveservices.azure.com (52.229.16.14) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt
  CApath: none
} [5 bytes data]
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
} [512 bytes data]
* TLSv1.3 (IN), TLS handshake, Server hello (2):
{ [89 bytes data]
* TLSv1.2 (IN), TLS handshake, Certificate (11):
{ [3692 bytes data]
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
{ [365 bytes data]
* TLSv1.2 (IN), TLS handshake, Server finished (14):
{ [4 bytes data]
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
} [102 bytes data]
* TLSv1.2 (OUT), TLS change cipher, Change cipher spec (1):
} [1 bytes data]
* TLSv1.2 (OUT), TLS handshake, Finished (20):
} [16 bytes data]
* TLSv1.2 (IN), TLS handshake, Finished (20):
{ [16 bytes data]
* SSL connection using TLSv1.2 / <<...>>
* ALPN, server did not agree to a protocol
* Server certificate:
*  subject: CN=*.cognitive.microsoft.com
*  start date: Apr 13 04:11:34 2020 GMT
*  expire date: Apr 13 04:11:34 2021 GMT
*  subjectAltName: host "<ACCOUNT-NAME>.cognitiveservices.azure.com" matched cert's "*.cognitiveservices.azure.com"
*  issuer: C=US; ST=Washington; L=Redmond; O=Microsoft Corporation; OU=Microsoft IT; CN=Microsoft IT TLS CA 5
*  SSL certificate verify ok.
} [5 bytes data]
> POST /text/analytics/v3.0-preview.1/languages HTTP/1.1
> Host: <ACCOUNT-NAME>.cognitiveservices.azure.com
> User-Agent: curl/7.65.3
> Accept: */*
> Ocp-Apim-Subscription-Key:<KEY>
> Content-Type:application/json
> Content-Length: 156
>
} [156 bytes data]
* upload completely sent off: 156 out of 156 bytes
{ [5 bytes data]
* Mark bundle as not supporting multiuse
< HTTP/1.1 400 Bad Request
< Transfer-Encoding: chunked
< Content-Type: application/json; charset=utf-8
< x-envoy-upstream-service-time: 4
< apim-request-id: <<ID-REQUEST>>
< Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
< x-content-type-options: nosniff
< Date: Tue, 12 May 2020 02:30:08 GMT
<
{ [156 bytes data]
100   306    0   150  100   156    592    616 --:--:-- --:--:-- --:--:--  1209{"error":{"code":"InvalidRequest","message":"Badly formed request: Unable to translate bytes [F1] at index 117 from specified code page to Unicode."}}
* Connection #0 to host <ACCOUNT-NAME>.cognitiveservices.azure.com left intact
</code>```

答:
You could try the Curl sample in the API Reference:Text Analytics API.

Also, you could just test it in this API Reference, select the testing console in the region where you created your resource, the URL will be like this: https://eastus.dev.cognitive.microsoft.com/docs/services/TextAnalytics-v3-0-Preview-1/operations/Languages/console

Body:
I need a snippet of cURL to run from the Command Prompt or GitBash on Windows 10, but getting an "Invalid Request" error. I am calling an API and I have tested my credentials another way, so I know those are correct. I was thinking maybe my code snippet is flawed in some way.

Note: I am unable to run single quotes without error, so I escaped them in the body. I also kept getting globbing errors, so I escaped the "{" and "[" parts. I ran the command with verbose, to get a longer print out. Is my snippet wrong?

$ curl -v -X POST "https://<ACCOUNT-NAME>.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/languages" -H "Ocp-Apim-Subscription-Key:<KEY>" -H "Content-Type:application/json" --data-raw "\{documents:\[\{id:1,text:\"This is a document written in English.\"\},\{id:2,text:\"Este es un document escrito en Español.\"\},\{id:3,text:\"这是一个用中文写的文件\"\}\]\}"

Note: Unnecessary use of -X or --request, POST is already inferred.
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0*   Trying 52.229.16.14:443...
* TCP_NODELAY set
* Connected to <ACCOUNT-NAME>.cognitiveservices.azure.com (52.229.16.14) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt
  CApath: none
} [5 bytes data]
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
} [512 bytes data]
* TLSv1.3 (IN), TLS handshake, Server hello (2):
{ [89 bytes data]
* TLSv1.2 (IN), TLS handshake, Certificate (11):
{ [3692 bytes data]
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
{ [365 bytes data]
* TLSv1.2 (IN), TLS handshake, Server finished (14):
{ [4 bytes data]
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
} [102 bytes data]
* TLSv1.2 (OUT), TLS change cipher, Change cipher spec (1):
} [1 bytes data]
* TLSv1.2 (OUT), TLS handshake, Finished (20):
} [16 bytes data]
* TLSv1.2 (IN), TLS handshake, Finished (20):
{ [16 bytes data]
* SSL connection using TLSv1.2 / <<...>>
* ALPN, server did not agree to a protocol
* Server certificate:
*  subject: CN=*.cognitive.microsoft.com
*  start date: Apr 13 04:11:34 2020 GMT
*  expire date: Apr 13 04:11:34 2021 GMT
*  subjectAltName: host "<ACCOUNT-NAME>.cognitiveservices.azure.com" matched cert's "*.cognitiveservices.azure.com"
*  issuer: C=US; ST=Washington; L=Redmond; O=Microsoft Corporation; OU=Microsoft IT; CN=Microsoft IT TLS CA 5
*  SSL certificate verify ok.
} [5 bytes data]
> POST /text/analytics/v3.0-preview.1/languages HTTP/1.1
> Host: <ACCOUNT-NAME>.cognitiveservices.azure.com
> User-Agent: curl/7.65.3
> Accept: */*
> Ocp-Apim-Subscription-Key:<KEY>
> Content-Type:application/json
> Content-Length: 156
>
} [156 bytes data]
* upload completely sent off: 156 out of 156 bytes
{ [5 bytes data]
* Mark bundle as not supporting multiuse
< HTTP/1.1 400 Bad Request
< Transfer-Encoding: chunked
< Content-Type: application/json; charset=utf-8
< x-envoy-upstream-service-time: 4
< apim-request-id: <<ID-REQUEST>>
< Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
< x-content-type-options: nosniff
< Date: Tue, 12 May 2020 02:30:08 GMT
<
{ [156 bytes data]
100   306    0   150  100   156    592    616 --:--:-- --:--:-- --:--:--  1209{"error":{"code":"InvalidRequest","message":"Badly formed request: Unable to translate bytes [F1] at index 117 from specified code page to Unicode."}}
* Connection #0 to host <ACCOUNT-NAME>.cognitiveservices.azure.com left intact


答:
Actually, I think that's a bug. From the perldoc for unlink:

On success, it returns the number of files it successfully deleted. On failure, it returns false and sets $! (errno)

Probably a shell programming on autopilot.

Title: Confused by a very simple if / else statement in perl


问:
Pandas masking a specific column by date
I have a dataframe (df) with 2 main columns--one called 'TIMESTAMP' representing dates, and one called 'QC' reflecting quality control flags as ints. This df has about 40,000 rows so I do not want to iterate over each one.

I have a new dataframe (dfNew) with just two columns of several start and end date pairs. I want to go through my original df and for all rows where the TIMESTAMP falls in between any of the start-end date pairs listed in dfNew, I want to replace the QC value with -1. This dfNew has about 400 rows so I figured iterating here would not be too bad.

The df looks something like this:

```<code>TIMESTAMP       | QC
2019-05-04 00:22    5
2019-05-04 00:24    1
2019-05-09 03:30    3
</code>```

the dfNew looks something like this:

```<code>START         | END
20190504_0023   20190504_0024
</code>```

So I would want to replace QC=1 for the second row in df with QC=-1.

This is my code so far:

```<code>for index, row in dfNew.iterrows():
    df['TIMESTAMP'] = pd.to_datetime(df['TIMESTAMP'])
    start = datetime.datetime.strptime(row[0], "%Y%m%d_%H%M")
    end = datetime.datetime.strptime(row[1], "%Y%m%d_%H%M")
    masked = (df['TIMESTAMP'] >= start) & (df['TIMESTAMP'] <= end)
    df['QC'].mask(masked, -1)
</code>```

However for some reason, the mask is not working. No values get replaced with -1. I think it may have something to with the fact that I'm creating the mask using the TIMESTAMP column but trying to use that mask to replace values in the QC columns, but I cannot figure out what it is. Any thoughts would be appreciated!

答:
I think this is what you want.</p>

```<code>df.TIMESTAMP = pd.to_datetime(df.TIMESTAMP)
dfNew.START = pd.to_datetime(dfNew.START, format='"%Y%m%d_%H%M"')
dfNew.END = pd.to_datetime(dfNew.END, format='"%Y%m%d_%H%M"')

def f(row):
    df.loc[df['TIMESTAMP'].between(row[0], row[1]), 'QC'] = -1

dfNew.apply(f, axis=1)
</code>```

Body:
I have a dataframe (df) with 2 main columns--one called 'TIMESTAMP' representing dates, and one called 'QC' reflecting quality control flags as ints. This df has about 40,000 rows so I do not want to iterate over each one.

I have a new dataframe (dfNew) with just two columns of several start and end date pairs. I want to go through my original df and for all rows where the TIMESTAMP falls in between any of the start-end date pairs listed in dfNew, I want to replace the QC value with -1. This dfNew has about 400 rows so I figured iterating here would not be too bad.

The df looks something like this:

TIMESTAMP       | QC
2019-05-04 00:22    5
2019-05-04 00:24    1
2019-05-09 03:30    3

the dfNew looks something like this:

START         | END
20190504_0023   20190504_0024

So I would want to replace QC=1 for the second row in df with QC=-1.

This is my code so far:

for index, row in dfNew.iterrows():
    df['TIMESTAMP'] = pd.to_datetime(df['TIMESTAMP'])
    start = datetime.datetime.strptime(row[0], "%Y%m%d_%H%M")
    end = datetime.datetime.strptime(row[1], "%Y%m%d_%H%M")
    masked = (df['TIMESTAMP'] >= start) & (df['TIMESTAMP'] <= end)
    df['QC'].mask(masked, -1)

However for some reason, the mask is not working. No values get replaced with -1. I think it may have something to with the fact that I'm creating the mask using the TIMESTAMP column but trying to use that mask to replace values in the QC columns, but I cannot figure out what it is. Any thoughts would be appreciated!

Body:
I think this is what you want.

df.TIMESTAMP = pd.to_datetime(df.TIMESTAMP)
dfNew.START = pd.to_datetime(dfNew.START, format='"%Y%m%d_%H%M"')
dfNew.END = pd.to_datetime(dfNew.END, format='"%Y%m%d_%H%M"')

def f(row):
    df.loc[df['TIMESTAMP'].between(row[0], row[1]), 'QC'] = -1

dfNew.apply(f, axis=1)


答:
I think that using back ticks are wrong,
You can write that in this way:

'\'{"0": "It\'s Friday today"}\''

'\'{"0": "Thursday\nFriday"}\''
```

<p>Anyway i think the entire purpose of this is overcomplicated, if you just want to create a json, just create an object and then convert it to a json:</p>

<pre class="lang-js prettyprint-override"><code>var obj1 = {0: "It's Friday today"};
var obj2 = {0: "Thursday\nFriday"};

var json1 =  JSON.stringify(obj1);
var json2 =  JSON.stringify(obj2);

var final1 = "'" + json1 + "'";
var final2 = "'" + json2 + "'";
</code>```

In this way is easier and it's less likely to syntax errors.

Hope it helps.

Body:
I think that using back ticks are wrong,
You can write that in this way:

'\'{"0": "It\'s Friday today"}\''

'\'{"0": "Thursday\nFriday"}\''

Anyway i think the entire purpose of this is overcomplicated, if you just want to create a json, just create an object and then convert it to a json:

var obj1 = {0: "It's Friday today"};
var obj2 = {0: "Thursday\nFriday"};

var json1 =  JSON.stringify(obj1);
var json2 =  JSON.stringify(obj2);

var final1 = "'" + json1 + "'";
var final2 = "'" + json2 + "'";

In this way is easier and it's less likely to syntax errors.

Hope it helps.


问:
Spring boot thin launcher exec jar is not located
I have created a spring boot maven project and tried to convert it in to thin jar using plugin

```<code>       <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.boot.experimental</groupId>
                    <artifactId>spring-boot-thin-layout</artifactId>
                    <version>1.0.25.BUILD-SNAPSHOT</version>
                </dependency>
            </dependencies>
        </plugin>
</code>```

It create a thin jar but when I tried to run it using

```<code> java  -Dthin.root=. -Dthin.archive=. -jar target/thin-jar-poc-0.0.1-SNAPSHOT.jar
</code>```

I am getting below error:

```<code>Cannot locate launcher: ./repository/org/springframework/boot/experimental/spring-boot-thin-launcher/1.0.25.BUILD-SNAPSHOT/spring-boot-thin-launcher-1.0.25.BUILD-SNAPSHOT-exec.jar
    at org.springframework.boot.loader.wrapper.ThinJarWrapper.launch(ThinJarWrapper.java:131)
    at org.springframework.boot.loader.wrapper.ThinJarWrapper.main(ThinJarWrapper.java:107)
</code>```

I am not able to figure out the reason.

答:
The problem was that network was behind a proxy and it was not downloading the dependencies
I put a settings.xml in {thin.repo}/.m2 directory with correct proxy settings and It worked</p>

Body:
I have created a spring boot maven project and tried to convert it in to thin jar using plugin

       <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.boot.experimental</groupId>
                    <artifactId>spring-boot-thin-layout</artifactId>
                    <version>1.0.25.BUILD-SNAPSHOT</version>
                </dependency>
            </dependencies>
        </plugin>

It create a thin jar but when I tried to run it using

 java  -Dthin.root=. -Dthin.archive=. -jar target/thin-jar-poc-0.0.1-SNAPSHOT.jar

I am getting below error:

Cannot locate launcher: ./repository/org/springframework/boot/experimental/spring-boot-thin-launcher/1.0.25.BUILD-SNAPSHOT/spring-boot-thin-launcher-1.0.25.BUILD-SNAPSHOT-exec.jar
    at org.springframework.boot.loader.wrapper.ThinJarWrapper.launch(ThinJarWrapper.java:131)
    at org.springframework.boot.loader.wrapper.ThinJarWrapper.main(ThinJarWrapper.java:107)

I am not able to figure out the reason.


问:
Assign multiple o365 licenses to a single user using PowerShell
I'm using a simple Powershell script to add new users to O365 and assign a license. However im trying to add multiple licenses at once to a single user.

Powershell

```<code>Connect-MsolService -Credential $UserCredential

Import-Csv -Path "C:\Users\Jesse\Documents\Powershell\NewAccounts.csv" | foreach {New-MsolUser -DisplayName $_.DisplayName -FirstName $_.FirstName -LastName $_.LastName -UserPrincipalName $_.UserPrincipalName -UsageLocation $_.UsageLocation -LicenseAssignment $_.AccountSkuId} | Export-Csv -Path "C:\Users\Jesse\Documents\Powershell\NewAccountResults.csv" -Verbose
</code>```

.CSV

```<code>DisplayName,FirstName,LastName,UserPrincipalName,Usagelocation,AccountSkuId
Test Jesse,Tes,Jesse,test.jesse@(tenant).nl,NL,(tenant):EMS
</code>```

For this example i'd like to add the EMS & ENTERPRISEPACK license to the test user.

答:
You can add another filed to your CSV:

```<code>DisplayName,FirstName,LastName,UserPrincipalName,Usagelocation,AccountSkuIdEMS, AccountSkuIdENTERPRISEPACK
Test Jesse,Tes,Jesse,test.jesse@(tenant).nl,NL,(tenant):EMS,(tenant):ENTERPRISEPACK
</code>```

And tweak the script:

```<code>Import-Csv -Path "C:\Users\Jesse\Documents\Powershell\NewAccounts.csv" | foreach {New-MsolUser -DisplayName $_.DisplayName -FirstName $_.FirstName -LastName $_.LastName -UserPrincipalName $_.UserPrincipalName -UsageLocation $_.UsageLocation -LicenseAssignment $_.AccountSkuIdEMS,$_.AccountSkuIdENTERPRISEPACK} | Export-Csv -Path "C:\Users\Jesse\Documents\Powershell\NewAccountResults.csv" -Verbose
</code>```

Body:
I'm using a simple Powershell script to add new users to O365 and assign a license. However im trying to add multiple licenses at once to a single user.

Powershell

Connect-MsolService -Credential $UserCredential

Import-Csv -Path "C:\Users\Jesse\Documents\Powershell\NewAccounts.csv" | foreach {New-MsolUser -DisplayName $_.DisplayName -FirstName $_.FirstName -LastName $_.LastName -UserPrincipalName $_.UserPrincipalName -UsageLocation $_.UsageLocation -LicenseAssignment $_.AccountSkuId} | Export-Csv -Path "C:\Users\Jesse\Documents\Powershell\NewAccountResults.csv" -Verbose

.CSV

DisplayName,FirstName,LastName,UserPrincipalName,Usagelocation,AccountSkuId
Test Jesse,Tes,Jesse,test.jesse@(tenant).nl,NL,(tenant):EMS

For this example i'd like to add the EMS & ENTERPRISEPACK license to the test user.

Body:
You can add another filed to your CSV:

DisplayName,FirstName,LastName,UserPrincipalName,Usagelocation,AccountSkuIdEMS, AccountSkuIdENTERPRISEPACK
Test Jesse,Tes,Jesse,test.jesse@(tenant).nl,NL,(tenant):EMS,(tenant):ENTERPRISEPACK

And tweak the script:

Import-Csv -Path "C:\Users\Jesse\Documents\Powershell\NewAccounts.csv" | foreach {New-MsolUser -DisplayName $_.DisplayName -FirstName $_.FirstName -LastName $_.LastName -UserPrincipalName $_.UserPrincipalName -UsageLocation $_.UsageLocation -LicenseAssignment $_.AccountSkuIdEMS,$_.AccountSkuIdENTERPRISEPACK} | Export-Csv -Path "C:\Users\Jesse\Documents\Powershell\NewAccountResults.csv" -Verbose


问:
Problem with AJAX chat
The problem is this.I want to save every message in MySQL DB and I try to do this making this javascript function:

```<code>function doWork(str)
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// Използваните браузъри
  xmlhttp=new XMLHttpRequest();
  }
else
  {// Кой ли ползва тези версии..
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
    xmlhttp.open("GET","newmsg.php?q="+str,true);
    xmlhttp.send();
}
</code>```

Then the text field :

```<code>  <div id="sender">
     Your message: <input type="text" name="msg" size="30" id="msg" />
     <button onclick="doWork(this.msg);">Send</button>
  </div>
</code>```

And finally the php file:

```<code>$q=$_GET["q"];
  (str)$q;
    $db_connect = mysql_connect('localhost', 'root', 'diamond');
    if(!$db_connect)
        {
         die('Не може да се осъществи връзка с базата данни' . mysql_error());
        }
mysql_select_db("chat", $db_connect);
$sql = "INSERT INTO messages (user_id, time, text) VALUES ('1','1234','$q')";
mysql_query($sql);
mysql_close($db_connect);
</code>```

And what actually happen is that the user_id and time fields are filled properly, but the 'text' filed says "undefined".
What does it mean and how can I fix the problem(s)?
Thanks
Leron

答:
I believe the issue is in your reference to the input text field. Try this instead:

```<code><div id="sender">
   Your message: <input type="text" name="msg" size="30" id="msg" />
   <button onclick="doWork(document.getElementById('msg').value);">Send</button>
</div>
</code>```

When you use the following, 'this' refers to the button element, so don't do the following.

```<code><button onclick="doWork(this.msg);">Send</button>
</code>```

Title: Problem with AJAX chat

Body:
The problem is this.I want to save every message in MySQL DB and I try to do this making this javascript function:

function doWork(str)
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// Използваните браузъри
  xmlhttp=new XMLHttpRequest();
  }
else
  {// Кой ли ползва тези версии..
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
    xmlhttp.open("GET","newmsg.php?q="+str,true);
    xmlhttp.send();
}

Then the text field :

     Your message: <input type="text" name="msg" size="30" id="msg" />
     <button onclick="doWork(this.msg);">Send</button>

And finally the php file:

$q=$_GET["q"];
  (str)$q;
    $db_connect = mysql_connect('localhost', 'root', 'diamond');
    if(!$db_connect)
        {
         die('Не може да се осъществи връзка с базата данни' . mysql_error());
        }
mysql_select_db("chat", $db_connect);
$sql = "INSERT INTO messages (user_id, time, text) VALUES ('1','1234','$q')";
mysql_query($sql);
mysql_close($db_connect);

And what actually happen is that the user_id and time fields are filled properly, but the 'text' filed says "undefined".
What does it mean and how can I fix the problem(s)?
Thanks
Leron

Body:
I believe the issue is in your reference to the input text field. Try this instead:

<div id="sender">
   Your message: <input type="text" name="msg" size="30" id="msg" />
   <button onclick="doWork(document.getElementById('msg').value);">Send</button>
</div>

When you use the following, 'this' refers to the button element, so don't do the following.

<button onclick="doWork(this.msg);">Send</button>


问:
runtime polymorphism and dynamic_cast need clarification
Might answered some where else, but could not found right phrase to ask

so hear it goes.

I have base class A, with child B and C; (completely for training purpose)

```<code>#include <iostream>

class A
{
    public:
        virtual void print () { std::cout<< "A::print()" << std::endl; }
};

class B: public A
{
    public:
        void print () { std::cout<< "B::print()" << std::endl; }
};

class C : public B
{
    public:
        void print () { std::cout<< "C::print()" << std::endl; }
};
</code>```

so, in my main I have declared base pointer A* bptr; later child's B and C also declared.

later bPtr pointed to B and called print function works as expected;
later bPtr pointed to C and called print function works as expected;

hear is code, no problems hear.

```<code>int main()
{
    A* bPtr;

    B b;
    C c;

    bPtr = &b;
    bPtr->print(); // prints B::print() - as expected;

    bPtr = &c;
    bPtr->print(); // prints C::print() - as expected;

}
</code>```

hear is my dilemma, I may understand wrong;
now what I thought all these days, dynamic_cast also does exactly above;
but things are different OR I am doing something wrong.

```<code>int main()
{

    A* bPtr = new C;

    bPtr = dynamic_cast<B*>( bPtr );

    bPtr->print(); // prints C::print() - expected B::print()

    /*
        I know above can be correct with explicit call
    */

    (dynamic_cast<B*>( bPtr ))->B::print(); // B::print

    bPtr = dynamic_cast<C*>( bPtr );

    bPtr->print(); // prints C::print()

    return 0;

    if ( B* b = dynamic_cast<B*>( bPtr ))
    {
        b->print(); // still calls C::print() anyway;
    }

}
</code>```

so hear is my question is dynamic_cast good for and only places like if statement to determine
the existence of inheritance between base and child's or safe cast between base and child's?

```<code>if ( B* b = dynamic_cast<B*>( bPtr ))
{
        b->print(); // still calls C::print() anyway;
}
</code>```

答:
This behaviour has nothing to do with dynamic_cast.

The behaviour of a virtual call will always depend on the actual runtime type of the value. In your second example, the only thing actually constructed is a C, so all calls will resolve to C, whether you call it an A: A * a = bPtr or a B: B * b = bPtr, it will resolve to C::print() because the statement new C constructs the actual value as a C.

Dynamic_cast is just going to cast the value given to the type specific, if it is (a subtype of) that type, or otherwise return nullptr. So dynamically casting a B * to C * will fail and return nullptr, but in your case you are casting C * to one of its base types, which will always succeed and never change the value itself.

Body:
Might answered some where else, but could not found right phrase to ask

so hear it goes.

I have base class A, with child B and C; (completely for training purpose)

#include <iostream>

class A
{
    public:
        virtual void print () { std::cout<< "A::print()" << std::endl; }
};

class B: public A
{
    public:
        void print () { std::cout<< "B::print()" << std::endl; }
};

class C : public B
{
    public:
        void print () { std::cout<< "C::print()" << std::endl; }
};

so, in my main I have declared base pointer A* bptr; later child's B and C also declared.

later bPtr pointed to B and called print function works as expected;
later bPtr pointed to C and called print function works as expected;

hear is code, no problems hear.

int main()
{
    A* bPtr;

    B b;
    C c;

    bPtr = &b;
    bPtr->print(); // prints B::print() - as expected;

    bPtr = &c;
    bPtr->print(); // prints C::print() - as expected;

}

hear is my dilemma, I may understand wrong;
now what I thought all these days, dynamic_cast also does exactly above;
but things are different OR I am doing something wrong.

int main()
{

    A* bPtr = new C;

    bPtr = dynamic_cast( bPtr );

    bPtr->print(); // prints C::print() - expected B::print()

    /*
        I know above can be correct with explicit call
    */

    (dynamic_cast( bPtr ))->B::print(); // B::print

    bPtr = dynamic_cast<C*>( bPtr );

    bPtr->print(); // prints C::print()

    return 0;

    if ( B* b = dynamic_cast( bPtr ))
    {
        b->print(); // still calls C::print() anyway;
    }

}

so hear is my question is dynamic_cast good for and only places like if statement to determine
the existence of inheritance between base and child's or safe cast between base and child's?

if ( B* b = dynamic_cast( bPtr ))
{
        b->print(); // still calls C::print() anyway;
}


问:
Why is the web page show a scroll bar when `body` set to `min-height: 100vh`?
I already reset all the margin and padding to 0.
see the codepen: https://codepen.io/geeklog/pen/zYvVeOZ

hello

```

<pre class="lang-css prettyprint-override"><code>* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  min-height: 100vh;
  background-color: pink;
}

.container {
  margin: 10px auto;
  background-color: orange;
}
</code>```

答: Because it was minimum height, so  height will be greater than 100vh.  try to change min-height to max-height.</p>

Body:
I already reset all the margin and padding to 0.
see the codepen: https://codepen.io/geeklog/pen/zYvVeOZ

hello

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  min-height: 100vh;
  background-color: pink;
}

.container {
  margin: 10px auto;
  background-color: orange;
}


问:
How to avoid page template duplication in Nuxt
I have a generic page template in Nuxt which I want to use for multiple roots. I want the following urls to map to the same template (which then loads it's content from prismic api)

```<code>/:root-level-page
/products/:product
</code>```

I can't see a way of doing this without the duplicating the page template in the pages folder like this

```<code>pages/_page.vue
pages/products/_page.vue
</code>```

This would work fine by I can't bring myself to break the golden DRY rule.

答:
Think I've found the answer myself so will leave here. I now just have the page template in my pages folder

```<code>pages/_page.vue
</code>```

I have then added the following to nuxt.config.js

```<code>router: {
extendRoutes (routes, resolve) {
  routes.push({
    name: 'section-page',
    path: '/:section/:page',
    component: resolve(__dirname, 'pages/_page.vue')
  })
}
</code>```

}

This means the routes below all use the same page template

```<code>/about
/products/some-product
/some-other-section/some-other-page
</code>```

Body:
I have a generic page template in Nuxt which I want to use for multiple roots. I want the following urls to map to the same template (which then loads it's content from prismic api)

/:root-level-page
/products/:product

I can't see a way of doing this without the duplicating the page template in the pages folder like this

pages/_page.vue
pages/products/_page.vue

This would work fine by I can't bring myself to break the golden DRY rule.

Body:
Think I've found the answer myself so will leave here. I now just have the page template in my pages folder

pages/_page.vue

I have then added the following to nuxt.config.js

router: {
extendRoutes (routes, resolve) {
  routes.push({
    name: 'section-page',
    path: '/:section/:page',
    component: resolve(__dirname, 'pages/_page.vue')
  })
}

}

This means the routes below all use the same page template

/about
/products/some-product
/some-other-section/some-other-page


问:
how to force to crash firebasecrashlytics?
I am developing news app and  I am new to firebase Crashlytics I want to force to crash and I want to get a report of the crash but I am not getting any crash reports how can I achieve that

below my Implementation

```<code>binding.root.setOnClickListener { v ->

                FirebaseCrashlytics.getInstance()

                val intent = Intent(v.context, DetailActivity::class.java)
                intent.putExtra(urlKey, articleList[position].url)

                v.context.startActivity(intent)
            }
</code>```

below my firebase crashlytics console screenshot
my firebasecrashlytics console

I want to know where I am making mistake how can I force to crash my app

答:
You can try this:

```<code>binding.root.setOnClickListener { v ->
       val intent = Intent(v.context, DetailActivity::class.java)
       intent.putExtra(urlKey, articleList[articleList.size].url) // you can throw ArrayIndexOutOfBoundsException

       v.context.startActivity(intent)
}
</code>```

or

```<code>binding.root.setOnClickListener { v ->
         throw RuntimeException("Test Crash") // Force a crash
}
</code>```

Body:
I am developing news app and  I am new to firebase Crashlytics I want to force to crash and I want to get a report of the crash but I am not getting any crash reports how can I achieve that

below my Implementation

binding.root.setOnClickListener { v ->

                FirebaseCrashlytics.getInstance()

                val intent = Intent(v.context, DetailActivity::class.java)
                intent.putExtra(urlKey, articleList[position].url)

                v.context.startActivity(intent)
            }

below my firebase crashlytics console screenshot
my firebasecrashlytics console

I want to know where I am making mistake how can I force to crash my app

Body:
You can try this:

binding.root.setOnClickListener { v ->
       val intent = Intent(v.context, DetailActivity::class.java)
       intent.putExtra(urlKey, articleList[articleList.size].url) // you can throw ArrayIndexOutOfBoundsException

       v.context.startActivity(intent)
}

or

binding.root.setOnClickListener { v ->
         throw RuntimeException("Test Crash") // Force a crash
}


问:
Populating a QComboBox and a QTable[View|Widget] from javascript
I'm trying to write a script for an application developed with Qt, using javascript for the business logic and a .ui file for the GUI, but I'm facing two problems.

In the ui I declared a QComboBox, to which I successfully connect javascript functions to handle
signals such as editTextChanged, etc. I was wondering I cannot populate the combobox from within
javascript code, because the addItem function is not exposed to script-side code.

```<code>combobox.editTextChanged[action](ComboBoxChanged);  // OK (action is "connect" or "disconnect")
combobox.addItem("element 1");   // Error!
</code>```

Is there any (other) way to do this?

I need to show a set of items (strings) in a table-like component. I tried using a QTableView and
QTableWidget but I cannot insert or get items. For example, from javascript I cannot access the
setModel function of a QTableView (if at least I could create a QAbstractItemModel from
script...), neither I can access the item(row,col) function of a QTableWidget class, to set an
item's text. Is there any way to show a table of strings to the user, let edit them and retrieve
the modified contents?

Thanks in advance.

Antonio

答: Because the addItem() function isn't a slot, you'll need an intermediate public slot to handle the transaction. It'll be the same with the other functions you are trying to get at as well. </p>

Body:
I'm trying to write a script for an application developed with Qt, using javascript for the business logic and a .ui file for the GUI, but I'm facing two problems.

In the ui I declared a QComboBox, to which I successfully connect javascript functions to handle
signals such as editTextChanged, etc. I was wondering I cannot populate the combobox from within
javascript code, because the addItem function is not exposed to script-side code.

combobox.editTextChanged[action](ComboBoxChanged);  // OK (action is "connect" or "disconnect")
combobox.addItem("element 1");   // Error!

Is there any (other) way to do this?

I need to show a set of items (strings) in a table-like component. I tried using a QTableView and
QTableWidget but I cannot insert or get items. For example, from javascript I cannot access the
setModel function of a QTableView (if at least I could create a QAbstractItemModel from
script...), neither I can access the item(row,col) function of a QTableWidget class, to set an
item's text. Is there any way to show a table of strings to the user, let edit them and retrieve
the modified contents?

Thanks in advance.

Antonio


问:
Cython/Python comparison invalid syntax error
I would like to compare Python with Cython in term of time execution, so I wrote two files:

fac.py

```<code>def factorial(n):
    if n >= 1:
        return n*factorial(n - 1)
    return 1
</code>```

fastfac.pyx

```<code>cpdef long fastfactorial(long n):
    if n>= 1:
        return n*fastfactorial(n - 1)
    return 1
</code>```

Then I wrote a setup file:

setup.py

```<code>from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules = cythonize('fastfac.pyx'))
</code>```

From the Powershell I executed the two commands:

```<code>pip install Cython
python setup.py build_ext --inplace
</code>```

From the second command I get the following message:

```<code>Compiling fastfac.pyx because it changed.
[1/1] Cythonizing fastfac.pyx
C:\Users\.....\venv\lib\site-packages\Cython\Compiler\Main.py:369: FutureWarning: Cython directive 'language_level' not set, using 2 for now (Py2). This will change in a later release! File: C:\Users\.....\fastfac.pyx
  tree = Parsing.p_module(s, pxd, full_module_name)
running build_ext
building 'fastfac' extension
error: Unable to find vcvarsall.bat
</code>```

However I tried to make a comparison, so I wrote the file:

comparison.py

```<code>from fastfac import fastfactorial
from fac import factorial
from timeit import timeit

print(timeit('fastfactorial(20)', globals = globals(), number = 10000))
print(timeit('factorial(20)', globals = globals(), number = 10000))
</code>```

When I run it, I get this error message:

```<code>Traceback (most recent call last):
  File "C:/Users/...../comparison.py", line 1, in <module>
    from fastfac import fastfactorial
ModuleNotFoundError: No module named 'fastfac'
</code>```

It seems that in the file python.pyx the definition cpdef long fastfactorial(long n) is not recognized as a regular function definition but as a syntax error; in fact, if I try to run that file I get the error message:

```<code>  File "C:/Users/...../fastfac.pyx", line 1
    cpdef long fastfactorial(long n):
             ^
SyntaxError: invalid syntax
</code>```

How can I solve? How can I correctly define a cpdef inside a .pyx file?
what am I missing?

答:
The problem is not your definition of fastfactorial, it is the fact that your setup.py exited with an error and, presumably, without compiling fastfac into a c library.  In general, you should always fix such errors.

Your error appears to be happening because you don't have a Microsoft Visual C++ compiler installed.  You can follow the instructions in this answer to choose a version of Visual C++ to install.

You also have a warning about the language_level not being set.  You shouldn't ignore warnings either so it is worth explicitly stating the level in your setup.py.

```<code>setup(ext_modules=cythonize('fastfac.pyx'), language_level=3)
</code>```

Body:
I would like to compare Python with Cython in term of time execution, so I wrote two files:

fac.py

def factorial(n):
    if n >= 1:
        return n*factorial(n - 1)
    return 1

fastfac.pyx

cpdef long fastfactorial(long n):
    if n>= 1:
        return n*fastfactorial(n - 1)
    return 1

Then I wrote a setup file:

setup.py

from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules = cythonize('fastfac.pyx'))

From the Powershell I executed the two commands:

pip install Cython
python setup.py build_ext --inplace

From the second command I get the following message:

Compiling fastfac.pyx because it changed.
[1/1] Cythonizing fastfac.pyx
C:\Users\.....\venv\lib\site-packages\Cython\Compiler\Main.py:369: FutureWarning: Cython directive 'language_level' not set, using 2 for now (Py2). This will change in a later release! File: C:\Users\.....\fastfac.pyx
  tree = Parsing.p_module(s, pxd, full_module_name)
running build_ext
building 'fastfac' extension
error: Unable to find vcvarsall.bat

However I tried to make a comparison, so I wrote the file:

comparison.py

from fastfac import fastfactorial
from fac import factorial
from timeit import timeit

print(timeit('fastfactorial(20)', globals = globals(), number = 10000))
print(timeit('factorial(20)', globals = globals(), number = 10000))

When I run it, I get this error message:

Traceback (most recent call last):
  File "C:/Users/...../comparison.py", line 1, in <module>
    from fastfac import fastfactorial
ModuleNotFoundError: No module named 'fastfac'

It seems that in the file python.pyx the definition cpdef long fastfactorial(long n) is not recognized as a regular function definition but as a syntax error; in fact, if I try to run that file I get the error message:

  File "C:/Users/...../fastfac.pyx", line 1
    cpdef long fastfactorial(long n):
             ^
SyntaxError: invalid syntax

How can I solve? How can I correctly define a cpdef inside a .pyx file?
what am I missing?

Body:
The problem is not your definition of fastfactorial, it is the fact that your setup.py exited with an error and, presumably, without compiling fastfac into a c library.  In general, you should always fix such errors.

Your error appears to be happening because you don't have a Microsoft Visual C++ compiler installed.  You can follow the instructions in this answer to choose a version of Visual C++ to install.

You also have a warning about the language_level not being set.  You shouldn't ignore warnings either so it is worth explicitly stating the level in your setup.py.

setup(ext_modules=cythonize('fastfac.pyx'), language_level=3)


问:
Selecting if count for different value is 1 or more
I have the following table data,

```<code>Number              Code
   1                 430
   1                 430
   2                 430
   2                 430
   3                 420
   3                 340
   3                 430
   1                 420
</code>```

Given the above data, I am trying to get records which have different code exist on them to make it clear following is the output I am expecting.

```<code>Number              Code
  1                 430
  1                 420
  3                 420
  3                 340
  3                 430
</code>```

If you see I am only selecting a number where different code exists if the number doesn't have different code on them I don't want to select that number.

I have tried with group by with having and then filtering out the matching codes but I am still not able to figure it out and messing with my output. I can't add having count(*) > 1 because same number can have multiple rows with same code.

Any help or pointers would be great.

答:
You can try this below logic with sub query-</p>

```<code>SELECT DISTINCT * FROM your_table
WHERE num IN
(
    SELECT num
    FROM your_table
    group by Num
    HAVING COUNT(DISTINCT Code) > 1
)
</code>```

Body:
I have the following table data,

Number              Code
   1                 430
   1                 430
   2                 430
   2                 430
   3                 420
   3                 340
   3                 430
   1                 420

Given the above data, I am trying to get records which have different code exist on them to make it clear following is the output I am expecting.

Number              Code
  1                 430
  1                 420
  3                 420
  3                 340
  3                 430

If you see I am only selecting a number where different code exists if the number doesn't have different code on them I don't want to select that number.

I have tried with group by with having and then filtering out the matching codes but I am still not able to figure it out and messing with my output. I can't add having count(*) > 1 because same number can have multiple rows with same code.

Any help or pointers would be great.

Body:
You can try this below logic with sub query-

SELECT DISTINCT * FROM your_table
WHERE num IN
(
    SELECT num
    FROM your_table
    group by Num
    HAVING COUNT(DISTINCT Code) > 1
)


问:
onclick show div and hide other div doesn't work
Could you please help me?

My code doens't work, the section doesnt appear after clicking the bottom section.

```<code><script>
$("#img1").on('click', function() {
   $("#div1").fadeIn();
   $("#div2,#div3,#div4").fadeOut();
});
$("#img2").on('click', function() {
   $("#div2").fadeIn();
   $("#div1,#div3,#div4").fadeOut();
});
$("#img3").on('click', function() {
   $("#div3").fadeIn();
   $("#div1,#div2,#div4").fadeOut();
});
$("#img4").on('click', function() {
   $("#div4").fadeIn();
   $("#div1,#div2,#div3").fadeOut();
});
</script>
</code>```

http://bookshark.phlexon.com/home-2/

Thanks so much!

答:
This is an alternate option other than by @aviboy2006.

You can insert the jQuery path to use the $ sign.

```<code><link rel='stylesheet' id='dashicons-css'  href='http://bookshark.phlexon.com/wp-includes/css/dashicons.min.css?ver=5.4.1' type='text/css' media='all' />
<!-- ****************** Add in jQuery path ************************************************-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- ***************************************************************************************-->
<script type='text/javascript' src='http://bookshark.phlexon.com/wp-includes/js/jquery/jquery.js?ver=1.12.4-wp'></script>
<script type='text/javascript' src='http://bookshark.phlexon.com/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.4.1'></script>
<script type='text/javascript' src='//cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.min.js?ver=5.4.1'></script>
</code>```

Then, your code should be working as below: (wrap inside $(document).ready(function(){)

```<code>$(document).ready(function(){
    $("#img1").on('click', function() {
       $("#div1").fadeIn();
       $("#div2,#div3,#div4").fadeOut();
    });
    $("#img2").on('click', function() {
       $("#div2").fadeIn();
       $("#div1,#div3,#div4").fadeOut();
    });
    $("#img3").on('click', function() {
       $("#div3").fadeIn();
       $("#div1,#div2,#div4").fadeOut();
    });
    $("#img4").on('click', function() {
       $("#div4").fadeIn();
       $("#div1,#div2,#div3").fadeOut();
    });
});
</code>```

Body:
Could you please help me?

My code doens't work, the section doesnt appear after clicking the bottom section.

http://bookshark.phlexon.com/home-2/

Thanks so much!

Body:
This is an alternate option other than by @aviboy2006.

You can insert the jQuery path to use the $ sign.

<link rel='stylesheet' id='dashicons-css'  href='http://bookshark.phlexon.com/wp-includes/css/dashicons.min.css?ver=5.4.1' type='text/css' media='all' />
<!-- ****************** Add in jQuery path ************************************************-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- ***************************************************************************************-->
<script type='text/javascript' src='http://bookshark.phlexon.com/wp-includes/js/jquery/jquery.js?ver=1.12.4-wp'></script>
<script type='text/javascript' src='http://bookshark.phlexon.com/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.4.1'></script>
<script type='text/javascript' src='//cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.min.js?ver=5.4.1'></script>

Then, your code should be working as below: (wrap inside $(document).ready(function(){)

$(document).ready(function(){
    $("#img1").on('click', function() {
       $("#div1").fadeIn();
       $("#div2,#div3,#div4").fadeOut();
    });
    $("#img2").on('click', function() {
       $("#div2").fadeIn();
       $("#div1,#div3,#div4").fadeOut();
    });
    $("#img3").on('click', function() {
       $("#div3").fadeIn();
       $("#div1,#div2,#div4").fadeOut();
    });
    $("#img4").on('click', function() {
       $("#div4").fadeIn();
       $("#div1,#div2,#div3").fadeOut();
    });
});


问:
Java: method to get position of a match in a String?
```<code>String match = "hello";
String text = "0123456789hello0123456789";

int position = getPosition(match, text); // should be 10, is there such a method?
</code>```

答:
```<code>public int NumberWordsInText(String FullText_, String WordToFind_, int[] positions_)
   {
    int iii1=0;
    int iii2=0;
    int iii3=0;
    while((iii1=(FullText_.indexOf(WordToFind_,iii1)+1))>0){iii2=iii2+1;}
    // iii2 is the number of the occurences
    if(iii2>0) {
        positions_ = new int[iii2];
        while ((iii1 = (FullText_.indexOf(WordToFind_, iii1) + 1)) > 0) {
            positions_[iii3] = iii1-1;
            iii3 = iii3 + 1;
            System.out.println("position=" + positions_[iii3 - 1]);
        }
    }
    return iii2;
}
</code>```

ContentLicense: CC BY-SA 2.5


问:
How to access the ext_conf_template.txt (extension configuration) in typoscript?
There are a few settings in the ext_conf_template.txt in my extension.

I want to check the value of one of these settings, but in typoscript, not in PHP.

In PHP it works like this:

```<code>unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['myExt'])
</code>```

How should I do this in typoscript?

答:
Thanks to the answer of Marcus I was able to get a extension configuration setting into typoscript. First create the extension setting in ext_conf_template.txt:

```<code># cat=Storage; type=string; label=storageFolderPid
storageFolderPid = 1
</code>```

In ext_local_conf.php add the following lines:

```<code>\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addTypoScriptConstants(
    "plugin.tx_extensionname.settings.storageFolderPid = ".$GLOBALS['TYPO3_CONF_VARS']['EXTENSIONS']['extension']['storageFolderPid']
);
</code>```

Then you can use this variabele in your typosript, for instance to create a submenu of a storage folder:

```<code>lib.submenu = CONTENT
lib.submenu {
    table = tx_extension_domain_model_article
    select {
        pidInList = {$plugin.tx_extensionname.settings.storageFolderPid}
        selectFields = tx_extensionname_domain_model_article.*
    }
    ...
}
</code>```

Body:
There are a few settings in the ext_conf_template.txt in my extension.

I want to check the value of one of these settings, but in typoscript, not in PHP.

In PHP it works like this:

unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['myExt'])

How should I do this in typoscript?

Body:
Thanks to the answer of Marcus I was able to get a extension configuration setting into typoscript. First create the extension setting in ext_conf_template.txt:

# cat=Storage; type=string; label=storageFolderPid
storageFolderPid = 1

In ext_local_conf.php add the following lines:

\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addTypoScriptConstants(
    "plugin.tx_extensionname.settings.storageFolderPid = ".$GLOBALS['TYPO3_CONF_VARS']['EXTENSIONS']['extension']['storageFolderPid']
);

Then you can use this variabele in your typosript, for instance to create a submenu of a storage folder:

lib.submenu = CONTENT
lib.submenu {
    table = tx_extension_domain_model_article
    select {
        pidInList = {$plugin.tx_extensionname.settings.storageFolderPid}
        selectFields = tx_extensionname_domain_model_article.*
    }
    ...
}


问:
Match a pattern using some condition and replace it with some string using regexp_replace in Oracle
I have a requirement to identify a particular string in a text using below conditions:

*1. Any string containing whitespace before and after it OR

Any string containing a . (dot) as prefix and whitespace as suffix OR

Any string having whitespace as prefix and , (comma) as suffix*

Once found, i need to replace it with another string without replacing the prefix and suffix as mentioned above. And this needs to be done in a pl/sql code in Oracle (preferably using regexp_replace function).

Example:

Text : 'This, is a sample_text, which_needs_.to_be_replaced as per, the matching.criteria.defined above,'

Replace string: 'replaced'

Output: 'This, replaced replaced replaced, which_needs_.replaced replaced replaced, replaced matching.criteria.replaced replaced'

I know this is a weird example, but the actual requirement is even more weird than this. Please guide me how to achieve this.

Thank you in advance.

答:
Rather than trying to write one giant regex, it may be easier to split the string into rows for each token. You can do this by adapting any of the CSV-to-rows methods around. e.g.:

```<code>with rws as (
  select 'This, is a sample_text, which_needs_.to_be_replaced as per, the matching.criteria.defined above,' str from dual
), vals as (
  select regexp_substr(str,'[A-z_,]+(\.|\s)?', 1, level) str, level l
  from   rws
  connect by regexp_substr(str, '[^, .]+', 1, level) is not null
)
  select * from vals;

STR               L
This,                  1
is                     2
a                      3
sample_text,           4
which_needs_.          5
to_be_replaced         6
as                     7
per,                   8
the                    9
matching.             10
criteria.             11
defined               12
above,                13
</code>```

Now replace each of these according to your rules. You're only dealing with one token at a time, so it's easy to see which you're replacing correctly. This makes the regex easier to write and debug:

```<code>with rws as (
  select 'This, is a sample_text, which_needs_.to_be_replaced as per, the matching.criteria.defined above,' str from dual
), vals as (
  select regexp_substr(str,'[A-z_,]+(\.|\s)?', 1, level) str, level l
  from   rws
  connect by regexp_substr(str, '[^, .]+', 1, level) is not null
)
  select case
           when l = 1 then str
           when substr ( str, -1, 1 ) = '.' then
             str
           else
           regexp_replace (
             str,
             '^[A-z_]+',
             'replaced'
           )
       end replaced, l
  from   vals;

REPLACED        L
This,                1
replaced             2
replaced             3
replaced,            4
which_needs_.        5
replaced             6
replaced             7
replaced,            8
replaced             9
matching.           10
criteria.           11
replaced            12
replaced,           13
</code>```

Then you listagg the values back together to get the final string:

```<code>with rws as (
  select 'This, is a sample_text, which_needs_.to_be_replaced as per, the matching.criteria.defined above,' str from dual
), vals as (
  select regexp_substr(str,'[A-z_,]+(\.|\s)?', 1, level) str, level l
  from   rws
  connect by regexp_substr(str, '[^, .]+', 1, level) is not null
), replaces as (
  select case
           when l = 1 then str
           when substr ( str, -1, 1 ) = '.' then
             str
           else
           regexp_replace (
             str,
             '[A-z_]+',
             'replaced'
           )
       end replaced, l
  from   vals
)
  select listagg ( replaced )
           within group ( order by l ) s
  from   replaces;

S
This, replaced replaced replaced, which_needs_.replaced replaced replaced, replaced matching.criteria.replaced replaced,
</code>```

Ensure you test thoroughly! In my experience, you find more exceptions/refinements when you have complex rules like this. So it's likely you'll have to tinker with the replacement rules in the case expression.

Body:
Rather than trying to write one giant regex, it may be easier to split the string into rows for each token. You can do this by adapting any of the CSV-to-rows methods around. e.g.:

with rws as (
  select 'This, is a sample_text, which_needs_.to_be_replaced as per, the matching.criteria.defined above,' str from dual
), vals as (
  select regexp_substr(str,'[A-z_,]+(\.|\s)?', 1, level) str, level l
  from   rws
  connect by regexp_substr(str, '[^, .]+', 1, level) is not null
)
  select * from vals;

STR               L
This,                  1
is                     2
a                      3
sample_text,           4
which_needs_.          5
to_be_replaced         6
as                     7
per,                   8
the                    9
matching.             10
criteria.             11
defined               12
above,                13

Now replace each of these according to your rules. You're only dealing with one token at a time, so it's easy to see which you're replacing correctly. This makes the regex easier to write and debug:

with rws as (
  select 'This, is a sample_text, which_needs_.to_be_replaced as per, the matching.criteria.defined above,' str from dual
), vals as (
  select regexp_substr(str,'[A-z_,]+(\.|\s)?', 1, level) str, level l
  from   rws
  connect by regexp_substr(str, '[^, .]+', 1, level) is not null
)
  select case
           when l = 1 then str
           when substr ( str, -1, 1 ) = '.' then
             str
           else
           regexp_replace (
             str,
             '^[A-z_]+',
             'replaced'
           )
       end replaced, l
  from   vals;

REPLACED        L
This,                1
replaced             2
replaced             3
replaced,            4
which_needs_.        5
replaced             6
replaced             7
replaced,            8
replaced             9
matching.           10
criteria.           11
replaced            12
replaced,           13

Then you listagg the values back together to get the final string:

with rws as (
  select 'This, is a sample_text, which_needs_.to_be_replaced as per, the matching.criteria.defined above,' str from dual
), vals as (
  select regexp_substr(str,'[A-z_,]+(\.|\s)?', 1, level) str, level l
  from   rws
  connect by regexp_substr(str, '[^, .]+', 1, level) is not null
), replaces as (
  select case
           when l = 1 then str
           when substr ( str, -1, 1 ) = '.' then
             str
           else
           regexp_replace (
             str,
             '[A-z_]+',
             'replaced'
           )
       end replaced, l
  from   vals
)
  select listagg ( replaced )
           within group ( order by l ) s
  from   replaces;

S
This, replaced replaced replaced, which_needs_.replaced replaced replaced, replaced matching.criteria.replaced replaced,

Ensure you test thoroughly! In my experience, you find more exceptions/refinements when you have complex rules like this. So it's likely you'll have to tinker with the replacement rules in the case expression.


问:
how to call a method with -- at runtime in python (like shell script) with run time arguments
how to call a method with -- at runtime  in python (like shell script) with run time arguments
for example below file name is mathematics.py

```<code>class maths():
    pass

    def add(self, *args):
        sum = 0
        for x in args:
            sum = sum + x
        return sum

    def mult(self, *args):
        if args:
            mul = 1
            for x in args:
                mul = mul * x
            return mul
        else:
            return None
m = maths()
m.add(1,2,3,)
m.mult(1,2,3)
</code>```

i would like to run this as :

```<code>python mathematics.py --add 1 2 3
or
python mathematics.py --mult 1 2 3
</code>```

答:
use 'optionParser' or 'sys' module

```<code>from optparse import OptionParser
parser = OptionParser()
parser.add_option('-m', "--mult",dest='mult' default='true')

(options, _args) = parser.parse_args()

</code>```

options.mult is your arguments

import sys
a1 = sys.argv[0]
a2 = sys.argv[1]
a3 = sys.argv[2]
```

a1 is your file name,
a2 is your first argument,
a2 is your second argument,

your arguments:python app.py port 8888

a1=app.py

a2=port

a3=8888

Body:
how to call a method with -- at runtime  in python (like shell script) with run time arguments
for example below file name is mathematics.py

class maths():
    pass

    def add(self, *args):
        sum = 0
        for x in args:
            sum = sum + x
        return sum

    def mult(self, *args):
        if args:
            mul = 1
            for x in args:
                mul = mul * x
            return mul
        else:
            return None
m = maths()
m.add(1,2,3,)
m.mult(1,2,3)

i would like to run this as :

python mathematics.py --add 1 2 3
or
python mathematics.py --mult 1 2 3

Body:
use 'optionParser' or 'sys' module

from optparse import OptionParser
parser = OptionParser()
parser.add_option('-m', "--mult",dest='mult' default='true')

(options, _args) = parser.parse_args()

options.mult is your arguments

import sys
a1 = sys.argv[0]
a2 = sys.argv[1]
a3 = sys.argv[2]

a1 is your file name,
a2 is your first argument,
a2 is your second argument,

your arguments:python app.py port 8888

a1=app.py

a2=port

a3=8888


问:
Maxpulse code doesn't want to work, really simple
I can't figure out why this simple code isn't working?</p>

```<code>maxpuls = 220

ålder = input("Hej! Vi vill mäta din maxpuls skriv in din ålder här:")

print("Detta är din maxpuls:" + (ålder - maxpuls))
</code>```

答:
Try if this works. You either have encoding issues because you are using high-ascii characters in your script, or it is because you have to convert the input to an integer.</p>

```<code># -*- coding: utf-8 -*-

maxpuls = 220

ålder = input("Hej! Vi vill mäta din maxpuls skriv in din ålder här:")

print("Detta är din maxpuls:" + str ( int(ålder) - maxpuls))
</code>```

Body:
I can't figure out why this simple code isn't working?

maxpuls = 220

ålder = input("Hej! Vi vill mäta din maxpuls skriv in din ålder här:")

print("Detta är din maxpuls:" + (ålder - maxpuls))

Body:
Try if this works. You either have encoding issues because you are using high-ascii characters in your script, or it is because you have to convert the input to an integer.

# -*- coding: utf-8 -*-

maxpuls = 220

ålder = input("Hej! Vi vill mäta din maxpuls skriv in din ålder här:")

print("Detta är din maxpuls:" + str ( int(ålder) - maxpuls))


问:
Pysaprk multi groupby with different column
I have data like below

```<code>year    name    percent     sex
1880    John    0.081541    boy
1881    William 0.080511    boy
1881    John    0.050057    boy
</code>```

I need to groupby and count using different columns

```<code>df_year = df.groupby('year').count()
df_name = df.groupby('name').count()
df_sex = df.groupby('sex').count()
</code>```

then I have to create a Window to get the top-3 data by each column

```<code>window = Window.partitionBy('year').orderBy(col("count").desc())
top4_res = df_year.withColumn('topn', func.row_number().over(window)).\
                                              filter(col('topn') <= 4).repartition(1)
</code>```

suppose I have hundreds of columns to groupby and count and topk_3 operation.

can I do it all in once?

or is there any better ways to do it?

答:
If you want top n values of columns that have the biggest count, this should work:</p>

```<code>from pyspark.sql.functions import *

columns_to_check = [ 'year', 'name' ]
n = 4

for c in columns_to_check:
  # returns a dataframe
  x = df.groupBy(c).count().sort(col("count").desc()).limit(n)
  x.show()

  # returns a list of rows
  x = df.groupBy(c).count().sort(col("count").desc()).take(n)
  print(x)
</code>```

Body:
I have data like below

year    name    percent     sex
1880    John    0.081541    boy
1881    William 0.080511    boy
1881    John    0.050057    boy

I need to groupby and count using different columns

df_year = df.groupby('year').count()
df_name = df.groupby('name').count()
df_sex = df.groupby('sex').count()

then I have to create a Window to get the top-3 data by each column

window = Window.partitionBy('year').orderBy(col("count").desc())
top4_res = df_year.withColumn('topn', func.row_number().over(window)).\
                                              filter(col('topn') <= 4).repartition(1)

suppose I have hundreds of columns to groupby and count and topk_3 operation.

can I do it all in once?

or is there any better ways to do it?

Body:
If you want top n values of columns that have the biggest count, this should work:

from pyspark.sql.functions import *

columns_to_check = [ 'year', 'name' ]
n = 4

for c in columns_to_check:
  # returns a dataframe
  x = df.groupBy(c).count().sort(col("count").desc()).limit(n)
  x.show()

  # returns a list of rows
  x = df.groupBy(c).count().sort(col("count").desc()).take(n)
  print(x)