问:
Font awesome unicode some icons not displaying
I am using unicode as per cheetsheet:  https://fontawesome.com/v5/cheatsheet/free/solid

I tried changing font-weight as per answer here but it hasnt helped: Font awesome 5 on pseudo elements

Maybe the issue is in css I linked? I dont know where to get other css version if there is newer.

.icon {
  font-family: 'Font Awesome 5 Free', 'Font Awesome 5 Regular', 'Font Awesome 5 Brands', 'Arial';
  font-size: 18px;
  font-weight: 900;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" rel="stylesheet" />
<div><span class="icon brand"></span>airbnb</div>
<div><span class="icon"></span>amazon-pay</div>
<div><span class="icon"></span>bacteria</div></code>```

答:
The Unicode for the first and last icons are incorrect if you are using just Font Awesome 5.

 doesn't exist in any icon library or in Unicode at all.

 matches with glyphicon-facetime-video from Bootstrap Icons and replay_10 from Google Material Icons. The reason why it didn't show up as either is because Bootstrap Icons needs the class glyphicon and Google Material needs the class material-icons.

Moreover Font Awesome also needs a class assigned to it's element. The CSS class in OP code, .icon is sufficient (it has the FA font-family property), but if you don't have that, the built-in classes are adequate as well (free versions are: fa, fas, and fab).

HTML

With Unicode


Without Unicode

:root,
body {
  font: 2ch/1 'Segoe UI'
}

.fab,
.fas {
  margin: 2px 3px;
  font-family: 'Font Awesome 5 Free', 'Font Awesome 5 Regular', 'Font Awesome 5 Brands', 'Arial';
  font-size: 1.5rem;
  font-weight: 900;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" rel="stylesheet">

<div><i class="fas fa-bed"></i> Airbnb Locator</div>
<div><i class="fab"></i> Amazon Pay</div>
<div><i class="fas fa-biohazard"></i> COV-ID Status</div></code>```

Body:
I am using unicode as per cheetsheet:  https://fontawesome.com/v5/cheatsheet/free/solid

I tried changing font-weight as per answer here but it hasnt helped: Font awesome 5 on pseudo elements

Maybe the issue is in css I linked? I dont know where to get other css version if there is newer.

.icon {
  font-family: 'Font Awesome 5 Free', 'Font Awesome 5 Regular', 'Font Awesome 5 Brands', 'Arial';
  font-size: 18px;
  font-weight: 900;
}

<link href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" rel="stylesheet" />

airbnb

amazon-pay

bacteria

Body:
The Unicode for the first and last icons are incorrect if you are using just Font Awesome 5.

&#xf834; doesn't exist in any icon library or in Unicode at all.

&#xe059; matches with glyphicon-facetime-video from Bootstrap Icons and replay_10 from Google Material Icons. The reason why it didn't show up as either is because Bootstrap Icons needs the class glyphicon and Google Material needs the class material-icons.

Moreover Font Awesome also needs a class assigned to it's element. The CSS class in OP code, .icon is sufficient (it has the FA font-family property), but if you don't have that, the built-in classes are adequate as well (free versions are: fa, fas, and fab).

HTML

With Unicode
<i class="fas">&#xf780;</i>

Without Unicode
<i class="fas fa-biohazard"></i>

:root,
body {
  font: 2ch/1 'Segoe UI'
}

.fab,
.fas {
  margin: 2px 3px;
  font-family: 'Font Awesome 5 Free', 'Font Awesome 5 Regular', 'Font Awesome 5 Brands', 'Arial';
  font-size: 1.5rem;
  font-weight: 900;
}

<link href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" rel="stylesheet">

<div><i class="fas fa-bed"></i> Airbnb Locator</div>
<div><i class="fab">&#xf42c;</i> Amazon Pay</div>
<div><i class="fas fa-biohazard"></i> COV-ID Status</div>


来源: stackexchange

问:
Eclipse IDE Some random words
my project name is not in English how do I revert it back to english</p>

答:
You have some weird font(s) installed on your system that don't play nicely with Eclipse. You can change your Eclipse theme to Classic to avoid this issue.</p>
```<code>Windows Menu > Preferences > General > Appearance > Theme
</code>```

ContentLicense: CC BY-SA 4.0

Title: Eclipse IDE Some random words

Body:
You have some weird font(s) installed on your system that don't play nicely with Eclipse. You can change your Eclipse theme to Classic to avoid this issue.

Windows Menu > Preferences > General > Appearance > Theme


问:
Can I receive a share intent without opening my Flutter app?
I'm creating an app in Flutter to store any type of media, imagem, video, pdfs, etc. And I want to be able to receive share intents from other apps in the easiest way possible for the user.

So, my idea is to be able to simply receive the media without needing to open the app for the user to input something, they should simply select my app to receive the media and continue using the "source" app. Is that possible in flutter?

答:
Using Receive Sharing intent package, you can receive text & media files in closed as well as opened application.

Below code snippet to receive intent in closed application,

```<code>// For sharing images coming from outside the app while the app is closed
    ReceiveSharingIntent.getInitialMedia().then((List<SharedMediaFile> value) {
      setState(() {
        _sharedFiles = value;
      });
    });
</code>```

You can go through this link for further understanding on how to receive intent in already opened & closed application.

Body:
Using Receive Sharing intent package, you can receive text & media files in closed as well as opened application.

Below code snippet to receive intent in closed application,

// For sharing images coming from outside the app while the app is closed
    ReceiveSharingIntent.getInitialMedia().then((List<SharedMediaFile> value) {
      setState(() {
        _sharedFiles = value;
      });
    });

You can go through this link for further understanding on how to receive intent in already opened & closed application.


问:
If else statement not outputting correctly?
I'm a beginner to Python and am struggling with a project I am working on. The program takes monthly income, fixed monthly expenses, asks for any additional expenses, and then outputs with an if else statement. My issue is in this function:

```<code>def spending(income, totals):

  finalTotal = income - totals

  if income > finalTotal:

    print("You saved $", "%.2f"%finalTotal, "this month!")
  elif finalTotal > income:

    print("You overspent by $", "%.2f"%finalTotal, "this month!")

  else:

    print("You broke even this month!")
</code>```

It is printing:

```<code>You saved $ -805.00 this month!
</code>```

When I'd like it to print:

```<code>You overspent by $ 805.00 this month!
</code>```

Any feedback would be greatly appreciated!!

Here is my code:
https://replit.com/@ashleyshubin/BudgetProgram#main.py

答:
Your checks are wrong. You can do the following:</p>
```<code>def spending(income, totals):
  finalTotal = income - totals
  if income > totals:
    print("You saved $", "%.2f"%finalTotal, "this month!")
  elif totals > income:
    print("You overspent by $", "%.2f"%-finalTotal, "this month!")
  else:
    print("You broke even this month!")
</code>```

Body:
I'm a beginner to Python and am struggling with a project I am working on. The program takes monthly income, fixed monthly expenses, asks for any additional expenses, and then outputs with an if else statement. My issue is in this function:

def spending(income, totals):

  finalTotal = income - totals

  if income > finalTotal:

    print("You saved $", "%.2f"%finalTotal, "this month!")
  elif finalTotal > income:

    print("You overspent by $", "%.2f"%finalTotal, "this month!")

  else:

    print("You broke even this month!")

It is printing:

You saved $ -805.00 this month!

When I'd like it to print:

You overspent by $ 805.00 this month!

Any feedback would be greatly appreciated!!

Here is my code:
https://replit.com/@ashleyshubin/BudgetProgram#main.py

Body:
Your checks are wrong. You can do the following:

def spending(income, totals):
  finalTotal = income - totals
  if income > totals:
    print("You saved $", "%.2f"%finalTotal, "this month!")
  elif totals > income:
    print("You overspent by $", "%.2f"%-finalTotal, "this month!")
  else:
    print("You broke even this month!")


问:
textFieldDidBeginEditing and textFieldDidEndEditing in SwiftUI
how can I use the methods textFieldDidBeginEditing and textFieldDidEndEditing with the default TextField struct by apple.

答:
SwiftUI 2

ios15 and above

The syntax has changed for swiftui2
a modifier onChange is triggered when a property value has changed and onSubmit is triggered when form is submitted ie you press enter

TextField("search", text: $searchQuery)
    .onChange(of: searchQuery){ newValue in
         print("textChanged")
    }
    .onSubmit {
         print("textSubmitted")
    }
```


答:
This section is where it is going wrong:

```<code>finalTotal = income - totals
  if income > finalTotal:
    print("You saved $", "%.2f"%finalTotal, "this month!")
</code>```

It looks like you're comparing the wrong variables in your "if" statement. your "finalTotal" variable already includes your income. Think of it like alegbra, and replace "finalTotal" with "income - totals", and your if statement now looks like:

```<code>    if income > (income - totals):
</code>```

this statement will always evaluate to true, no matter what values you are using. You probably want to rewrite your if statements to compare "income > totals", rather than finalTotal.

Title: If else statement not outputting correctly?

Body:
This section is where it is going wrong:

finalTotal = income - totals
  if income > finalTotal:
    print("You saved $", "%.2f"%finalTotal, "this month!")

It looks like you're comparing the wrong variables in your "if" statement. your "finalTotal" variable already includes your income. Think of it like alegbra, and replace "finalTotal" with "income - totals", and your if statement now looks like:

    if income > (income - totals):

this statement will always evaluate to true, no matter what values you are using. You probably want to rewrite your if statements to compare "income > totals", rather than finalTotal.


答:
your comparison shoud be based on finaltotal , as fianaltotal is finalTotal = income - totals, also else  never runs based on the other conditions in your code:

```<code>def spending(income, totals):
    finalTotal = income - totals
    if finalTotal > 0:
        print("You saved $", "%.2f" % finalTotal, "this month!")
    else:
        print("You overspent by $", "%.2f" % abs(finalTotal), "this month!")
</code>```

Body:
your comparison shoud be based on finaltotal , as fianaltotal is finalTotal = income - totals, also else  never runs based on the other conditions in your code:

def spending(income, totals):
    finalTotal = income - totals
    if finalTotal > 0:
        print("You saved $", "%.2f" % finalTotal, "this month!")
    else:
        print("You overspent by $", "%.2f" % abs(finalTotal), "this month!")


问:
Isn't the time complexity for combinations in Python O(n)?
I was curious about the time complexity of Python's itertools.combinations function. I did some searching and it seems that many resources claim the time complexity is O(n!) or O(nCr).

However, for the two extremes of when r = 1 and r = n, the formula nCr reduces to n and 1, respectively. Does this mean we can conclude that the time complexity of itertools.combinations is O(n)?

答: r=1 and r=n rather are (almost) best cases (actually r=0 is the lower extreme), not worst cases. Worst case, at least for number of combinations, is r=n/2. So if you do want to express the complexity in terms of just n, it's O(nC(n/2)) or O(n × nC(n/2)), depending on what you do with the tuples.


问:
How can I compare two arrays and run a function depending on the number of matching items (regardless of index)?
I had a previous solution with .forEach that didn't consider the fact that the answers can be selected in the wrong order, so the items at to be at the same exact index. If it was selected in the wrong order it wouldn't match (even though it was the right answer).

Now I'm trying a solution with .every, but it's not changing score when the button "check answers" is clicked. In case you'd like to check the entire code here it is (it's a bit too much to type in - I'm new to stackoverflow so lmk if a better method is suggested to share multiple components): https://replit.com/@arshia93/Quizzical#sections/QuizData.jsx

```<code>function scoreQuiz(allCorrectAnswers, selections) {
  let totalScore = 0;
  if(allCorrectAnswers.length === selections.length) {
    return allCorrectAnswers.every((element, index) => {
      element === selections[index] ? totalScore++ : totalScore
    })
    setScore(totalScore)
  }
  setFinished(!finished)
}
</code>```

答: I looked at your code in the replit you linked. I think the issue is at line 41 where you return the result of calling every method on your allCorrectAnswers array. So, after the every method is done executing you return the value true or false and you exit the scoreQuiz function before you reach the next line where you would have setScore for your quiz. So, you should remove the return statement and let the setScore and setFinished hooks execute.

Body:
I had a previous solution with .forEach that didn't consider the fact that the answers can be selected in the wrong order, so the items at to be at the same exact index. If it was selected in the wrong order it wouldn't match (even though it was the right answer).

Now I'm trying a solution with .every, but it's not changing score when the button "check answers" is clicked. In case you'd like to check the entire code here it is (it's a bit too much to type in - I'm new to stackoverflow so lmk if a better method is suggested to share multiple components): https://replit.com/@arshia93/Quizzical#sections/QuizData.jsx

function scoreQuiz(allCorrectAnswers, selections) {
  let totalScore = 0;
  if(allCorrectAnswers.length === selections.length) {
    return allCorrectAnswers.every((element, index) => {
      element === selections[index] ? totalScore++ : totalScore
    })
    setScore(totalScore)
  }
  setFinished(!finished)
}


问:
'<=' not supported between instances of 'int' (line 11) and 'str' and can't multiply sequence by non-int of type 'str' (line12 )
```<code>x = input("xres\n")
y = input("yres\n")
operation = input("* or /\n")
times = input("amount\n")
int(times)
int(x)
int(y)
increment = 1
while(increment) <= (times) and (operation) == ("*"): #TypeError: '<=' not supported between instances of 'int' and 'str'
    print((x) * (increment), (y) * (increment)) #TypeError: can't multiply sequence by non-int of type 'str'
    increment = (increment) + (1)
</code>```

I'm pretty sure that (x) and (increment) are integers, why are these errors occurring?

答:
replaced int(x) with x = int(x).
comments helped.</p>

Body:
x = input("xres\n")
y = input("yres\n")
operation = input("* or /\n")
times = input("amount\n")
int(times)
int(x)
int(y)
increment = 1
while(increment) <= (times) and (operation) == ("*"): #TypeError: '<=' not supported between instances of 'int' and 'str'
    print((x) * (increment), (y) * (increment)) #TypeError: can't multiply sequence by non-int of type 'str'
    increment = (increment) + (1)

I'm pretty sure that (x) and (increment) are integers, why are these errors occurring?


答:
you should be comparing Income with total spends.</p>
```<code>def spending(income, totals):

  finalTotal = abs(income - totals)

  if totals < income:

    print("You saved $", "%.2f"%finalTotal, "this month!")
  elif totals > income:

    print("You overspent by $", "%.2f"%finalTotal, "this month!")

  else:

    print("You broke even this month!")
</code>```

Body:
you should be comparing Income with total spends.

def spending(income, totals):

  finalTotal = abs(income - totals)

  if totals < income:

    print("You saved $", "%.2f"%finalTotal, "this month!")
  elif totals > income:

    print("You overspent by $", "%.2f"%finalTotal, "this month!")

  else:

    print("You broke even this month!")


问:
What to set as the Provider's value using react typescript
I'm trying to learn how to use hooks and context in React, but need to work with TypeScript (new to that as well).

I am confused about what to set provider value on my below code. I have created a hook useFirebase it will return some functions like RegisterUser, SignIn, user(it's a state), logout.

First I created UseAuth.tsx hook, using this hook I want to import the above functions which I mentioned.

```<code>import { useContext } from 'react';
import { AuthContext } from '../context/AuthProvider';

const UseAuth = () => {
    const auth = useContext(AuthContext)
    return auth
};

export default UseAuth;
</code>```

Everything is ok but I am getting an error on the provider value. The error is (JSX attribute) React.ProviderProps<null>.value: null Type '{ RegisterUser: RegisterUserFunction; SignIn: SignInUserFunction; user: userState; logout: () => void; }' is not assignable to type 'null'. The expected type comes from property 'value' which is declared here on type 'IntrinsicAttributes & ProviderProps<null>' I have created an interface IAuth but where I need to define it I am confused.

```<code>import React, { createContext } from 'react';
import { UseFirebase } from '../hooks/UseFirebase';

export const AuthContext = createContext(null)

export interface IAuth {
    RegisterUser: () => void;
    SignIn : () => void;
    user : any
    logout : () => void;

}

const AuthProvider = ({ children } :any) => {
    const allContext = UseFirebase()
    return (
        <AuthContext.Provider value={allContext}>
            {children}
        </AuthContext.Provider>
    );
};

export default AuthProvider;
</code>```

答:
The problem is in

```<code>export const AuthContext = createContext(null)
</code>```

You need to pass a proper type to it, so it won't complain when trying to assign any value.

Try something like

```<code> React.createContext<IAuth>(initialValue);

</code>```

For a more detailed explanation check out this article react-context-with-typescrip

Body:
I'm trying to learn how to use hooks and context in React, but need to work with TypeScript (new to that as well).

I am confused about what to set provider value on my below code. I have created a hook useFirebase it will return some functions like RegisterUser, SignIn, user(it's a state), logout.

First I created UseAuth.tsx hook, using this hook I want to import the above functions which I mentioned.

import { useContext } from 'react';
import { AuthContext } from '../context/AuthProvider';

const UseAuth = () => {
    const auth = useContext(AuthContext)
    return auth
};

export default UseAuth;

Everything is ok but I am getting an error on the provider value. The error is (JSX attribute) React.ProviderProps<null>.value: null Type '{ RegisterUser: RegisterUserFunction; SignIn: SignInUserFunction; user: userState; logout: () => void; }' is not assignable to type 'null'. The expected type comes from property 'value' which is declared here on type 'IntrinsicAttributes & ProviderProps<null>' I have created an interface IAuth but where I need to define it I am confused.

import React, { createContext } from 'react';
import { UseFirebase } from '../hooks/UseFirebase';

export const AuthContext = createContext(null)

export interface IAuth {
    RegisterUser: () => void;
    SignIn : () => void;
    user : any
    logout : () => void;

}

const AuthProvider = ({ children } :any) => {
    const allContext = UseFirebase()
    return (
        <AuthContext.Provider value={allContext}>
            {children}
        </AuthContext.Provider>
    );
};

export default AuthProvider;

Body:
The problem is in

export const AuthContext = createContext(null)

You need to pass a proper type to it, so it won't complain when trying to assign any value.

Try something like

 React.createContext<IAuth>(initialValue);

For a more detailed explanation check out this article react-context-with-typescrip


问:
Reduce boolean Iterator
How can I reduce an Iterator of booleans using the && operator? Here is an example (just the relevant part):

let row: Vec<(u32, bool)> = vec![(12, true), (13, false), (15, true)];

row.iter()
    .map(|it| {
        let (_, marked) = it;
        marked
    })
    .reduce(|acc, mk | acc && mk);
```

The compiler recommends dereferencing acc first, then dereferencing mk, and finally borrowing the whole expression. It's a quite simple operation but I'm unable to find the Rustacean way to do it.

答:
Because There are three common methods which can create iterators from a collection;

```<code>iter(), which iterates over &T.
iter_mut(), which iterates over &mut T.
into_iter(), which iterates over T.
</code>```

Your code uses iter (), so the iteration is & type, so you need to use & to extract value

Maybe you can do it like this:

```<code>    let row: Vec<(u32, bool)> = vec![(12, true), (13, false), (15, true)];

    let op = row.iter()
        .map(|&it| {
            let (_, marked) = it;
            marked // No dereference is required
        })
        .reduce(|acc, mk| acc && mk);
    println!("{:?}",op);
</code>```

or

```<code>    let row: Vec<(u32, bool)> = vec![(12, true), (13, false), (15, true)];

    let op = row.into_iter()
        .map(|it| {
            let (_, marked) = it;
            marked // No dereference is required
        })
        .reduce(|acc, mk| acc && mk);
    println!("{:?}",op);
</code>```

Title: Reduce boolean Iterator

Body:
How can I reduce an Iterator of booleans using the && operator? Here is an example (just the relevant part):

let row: Vec<(u32, bool)> = vec![(12, true), (13, false), (15, true)];

row.iter()
    .map(|it| {
        let (_, marked) = it;
        marked
    })
    .reduce(|acc, mk | acc && mk);

The compiler recommends dereferencing acc first, then dereferencing mk, and finally borrowing the whole expression. It's a quite simple operation but I'm unable to find the Rustacean way to do it.

Body:
Because There are three common methods which can create iterators from a collection;

iter(), which iterates over &T.
iter_mut(), which iterates over &mut T.
into_iter(), which iterates over T.

Your code uses iter (), so the iteration is & type, so you need to use & to extract value

Maybe you can do it like this:

    let row: Vec<(u32, bool)> = vec![(12, true), (13, false), (15, true)];

    let op = row.iter()
        .map(|&it| {
            let (_, marked) = it;
            marked // No dereference is required
        })
        .reduce(|acc, mk| acc && mk);
    println!("{:?}",op);

or

    let row: Vec<(u32, bool)> = vec![(12, true), (13, false), (15, true)];

    let op = row.into_iter()
        .map(|it| {
            let (_, marked) = it;
            marked // No dereference is required
        })
        .reduce(|acc, mk| acc && mk);
    println!("{:?}",op);


问:
AJAX-generated
 becomes just the text content in firefox/chrome
First, I request some HTML via AJAX.

Example response:

```<code><tr class="recordRow">
  <td class="first recordType" id="recordType">holder</td>
  <td class="recordAmount" id="recordAmount">holder</td>
  <td class="recordDescription" id="recordDescription">holder</td>
  <td class="last recordDate" id="recordDate">holder</td>
</tr>
</code>```

And I'm trying to make a DOM Object.

```<code>var d = document.createElement("div");
d.innerHTML = templateListItem;
alert(d.innerHTML);
alert(d.firstChild);
</code>```

I thought this should add the row to the
, but I only get the text. When I append the response to an element, I only get the text content, e.g holder holder holder holder.

Why does the HTML seem to get squashed in firefox and chrome?

Added:
If example response are like:

```<code><tr><td><span>something here..</span></td></tr>
</code>```

It will alert "HTMLSpanElement"  in firefox. All tags like tr/td/ are removed.

答:
If you're dragging that response from a server somewhere, it will just be text, as you've found out. If you can, you could change the AJAX code to return JSON, decode that, and turn it into an object.

In relation to the tags being removed, I read somewhere about browsers doing that, but it's very likely to be wrong; AJAX would fail miserably in that case.

ContentLicense: CC BY-SA 3.0

Title: AJAX-generated <tr> becomes just the text content in firefox/chrome

Body:
First, I request some HTML via AJAX.

Example response:

  holder
  holder
  holder
  holder

And I'm trying to make a DOM Object.

var d = document.createElement("div");
d.innerHTML = templateListItem;
alert(d.innerHTML);
alert(d.firstChild);

I thought this should add the row to the
, but I only get the text. When I append the response to an element, I only get the text content, e.g holder holder holder holder.

Why does the HTML seem to get squashed in firefox and chrome?

Added:
If example response are like:

something here..

It will alert "HTMLSpanElement"  in firefox. All tags like tr/td/ are removed.


问:
incorrect value outputting from while loop
Here is my code, why is 0 outputting instead of entered value?</p>
```<code>cube = 0
value = int(input("Enter a value to be cubed or 0 to quit: "))

while value != 0:
    cube = value **3
    value = int(input("Enter a value to be cubed or 0 to quit: "))

print (value, "cubed is", cube)
</code>```

答:
First thing you want to do is indent that print, so that it refers to the values inside the loop:

```<code>cube = 0
value = int(input("Enter a value to be cubed or 0 to quit: "))

while value != 0:
    cube = value **3
    value = int(input("Enter a value to be cubed or 0 to quit: "))
    print (value, "cubed is", cube)
</code>```

But now every time you print the result, cube refers to the previous round. So you want to change the order:

```<code># no need to do cube = 0, it contributes nothing
value = int(input("Enter a value to be cubed or 0 to quit: "))

while value != 0:
    cube = value**3
    print (value, "cubed is", cube)
    value = int(input("Enter a value to be cubed or 0 to quit: "))
</code>```

Body:
Here is my code, why is 0 outputting instead of entered value?

cube = 0
value = int(input("Enter a value to be cubed or 0 to quit: "))

while value != 0:
    cube = value **3
    value = int(input("Enter a value to be cubed or 0 to quit: "))

print (value, "cubed is", cube)

Body:
First thing you want to do is indent that print, so that it refers to the values inside the loop:

cube = 0
value = int(input("Enter a value to be cubed or 0 to quit: "))

while value != 0:
    cube = value **3
    value = int(input("Enter a value to be cubed or 0 to quit: "))
    print (value, "cubed is", cube)

But now every time you print the result, cube refers to the previous round. So you want to change the order:

# no need to do cube = 0, it contributes nothing
value = int(input("Enter a value to be cubed or 0 to quit: "))

while value != 0:
    cube = value**3
    print (value, "cubed is", cube)
    value = int(input("Enter a value to be cubed or 0 to quit: "))


问:
When using a specific button on discord my bot crashes
When I use a specific button on discord it crashes the bot and gives this error:

```<code>E:\TicketBot\node_modules\discord.js\src\rest\RequestHandler.js:350
      throw new DiscordAPIError(data, res.status, request);
            ^

DiscordAPIError: Interaction has already been acknowledged.
    at RequestHandler.execute (E:\TicketBot\node_modules\discord.js\src\rest\RequestHandler.js:350:13)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async RequestHandler.push (E:\TicketBot\node_modules\discord.js\src\rest\RequestHandler.js:51:14)
    at async ButtonInteraction.reply (E:\TicketBot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:99:5)
    at async Object.execute (E:\TicketBot\events\interactionCreate2.js:82:21) {
</code>```

This is the code for the embed and button that I use when it crashes

const embed = new client.discord.MessageEmbed()
    .setColor('FF0000')
    .setAuthor({name: `${interaction.user.username}'s Ticket`, iconURL: 'https://cdn.discordapp.com/attachments/764964854087417899/941868628138135622/Hecker.png'})
    .setDescription('Test')
    .setTimestamp();

const row = new client.discord.MessageActionRow()
    .addComponents(
        new client.discord.MessageButton()
    .setCustomId('close-ticket')
    .setLabel('Close')
    .setEmoji('')
    .setStyle('DANGER'),
);
```

答: Using the same interaction twice causes this issue.</p>

Body:
When I use a specific button on discord it crashes the bot and gives this error:

E:\TicketBot\node_modules\discord.js\src\rest\RequestHandler.js:350
      throw new DiscordAPIError(data, res.status, request);
            ^

DiscordAPIError: Interaction has already been acknowledged.
    at RequestHandler.execute (E:\TicketBot\node_modules\discord.js\src\rest\RequestHandler.js:350:13)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async RequestHandler.push (E:\TicketBot\node_modules\discord.js\src\rest\RequestHandler.js:51:14)
    at async ButtonInteraction.reply (E:\TicketBot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:99:5)
    at async Object.execute (E:\TicketBot\events\interactionCreate2.js:82:21) {

This is the code for the embed and button that I use when it crashes

const embed = new client.discord.MessageEmbed()
    .setColor('FF0000')
    .setAuthor({name: `${interaction.user.username}'s Ticket`, iconURL: 'https://cdn.discordapp.com/attachments/764964854087417899/941868628138135622/Hecker.png'})
    .setDescription('Test')
    .setTimestamp();

const row = new client.discord.MessageActionRow()
    .addComponents(
        new client.discord.MessageButton()
    .setCustomId('close-ticket')
    .setLabel('Close')
    .setEmoji('')
    .setStyle('DANGER'),
);


问:
How to insert selected SVG elements in a group with javascript
I am creating some svg elements with javascript, e.g.

const svg = document.querySelector('svg');

// variable for the namespace
const svgns = "http://www.w3.org/2000/svg"

//assigning svg element attribute
svg.setAttribute('class', 'layer1');
svg.setAttribute('xmlns', svgns);
svg.setAttribute('width', '400');
svg.setAttribute('height', '200');
svg.setAttribute('viewBox', '0 0 400 200');

//make background
var fill1 = '#e6e6e6';
//var fill2 = 'transparent';

let bg = document.createElementNS(svgns, 'rect');
bg.setAttribute('class', 'bg');
bg.setAttribute('id', 'bg');
bg.setAttribute('width', '200');
bg.setAttribute('height', '200');
bg.setAttribute('fill', fill1);

// append the new rectangle to the svg
svg.appendChild(bg);

function createRect(a) {

    //create element
    var rect1 = document.createElementNS(svgns, 'rect');
    rect1.setAttribute('class', 'cl' + a);
    rect1.setAttribute('id', 'id' + a);
    rect1.setAttribute('x', '10');
    rect1.setAttribute('y', '20');
    rect1.setAttribute('width', '30');
    rect1.setAttribute('height', '30');
    //rect1.setAttribute("rx", "20");
    rect1.setAttribute('fill', 'red');

    svg.appendChild(rect1);
};

//create an array from  1 to 5
var bigArray = [];
for (var i = 0; i < 5; i++) {
    bigArray[i] = i + 1;
};

//create Rect for each element of the array
for (const el of bigArray) {
    createRect(el);
}

//create group
var group = document.createElementNS(svgns, 'g');
group.setAttribute('class', 'allRect');
group.setAttribute('id', 'allRect');

svg.appendChild(group);

var x = document.querySelectorAll('[class^=cl]');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <svg>
    </svg>
</body>

</html></code>```

How can I ask javascript to insert a custom selected elements document.querySelectorAll('[class^=cl]') (all 5 Rects) in a group allRect

答:
I'm not sure I understood the question (rough translation for me)

Is this what you are looking for?

const
  svgns = 'http://www.w3.org/2000/svg'
, fill1 = '#e6e6e6'
, svg   = document.querySelector('svg')
, bg    = svg.appendChild( document.createElementNS(svgns, 'rect') )
, setSvgAttr = (el,attrs) =>
    Object.entries(attrs).forEach(([k,v]) =>
      el.setAttribute(k,v))
  ;

setSvgAttr(svg, { class: 'layer1', xmlns: svgns, width: 400, height: 200, viewBox: '0 0 400 200' })
setSvgAttr(bg, { class: 'bg', id: 'bg', width: 200, height: 200, fill: fill1 })

function createRect(a)
  {
  let rectN = svg.appendChild( document.createElementNS(svgns, 'rect'))
  setSvgAttr(rectN, { class: 'cl'+a, id: 'id'+a, x:a*30, y:a*20, width: 30, height: 30, fill: 'red' })
  }

//create an array from  1 to 5
var bigArray = Array.from({length:5},(_,i)=>++i);

//create Rect for each element of the array
for (const el of bigArray) {  createRect(el) }

//create group
var group = svg.appendChild( document.createElementNS(svgns, 'g'))

setSvgAttr(bg, { class: 'allRect', id: 'allRect' })

document.querySelectorAll('[class^=cl]').forEach( elSVG => group.appendChild(elSVG))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg></svg></code>```

Body:
I am creating some svg elements with javascript, e.g.

const svg = document.querySelector('svg');

// variable for the namespace
const svgns = "http://www.w3.org/2000/svg"

//assigning svg element attribute
svg.setAttribute('class', 'layer1');
svg.setAttribute('xmlns', svgns);
svg.setAttribute('width', '400');
svg.setAttribute('height', '200');
svg.setAttribute('viewBox', '0 0 400 200');

//make background
var fill1 = '#e6e6e6';
//var fill2 = 'transparent';

let bg = document.createElementNS(svgns, 'rect');
bg.setAttribute('class', 'bg');
bg.setAttribute('id', 'bg');
bg.setAttribute('width', '200');
bg.setAttribute('height', '200');
bg.setAttribute('fill', fill1);

// append the new rectangle to the svg
svg.appendChild(bg);

function createRect(a) {

    //create element
    var rect1 = document.createElementNS(svgns, 'rect');
    rect1.setAttribute('class', 'cl' + a);
    rect1.setAttribute('id', 'id' + a);
    rect1.setAttribute('x', '10');
    rect1.setAttribute('y', '20');
    rect1.setAttribute('width', '30');
    rect1.setAttribute('height', '30');
    //rect1.setAttribute("rx", "20");
    rect1.setAttribute('fill', 'red');

    svg.appendChild(rect1);
};

//create an array from  1 to 5
var bigArray = [];
for (var i = 0; i < 5; i++) {
    bigArray[i] = i + 1;
};

//create Rect for each element of the array
for (const el of bigArray) {
    createRect(el);
}

//create group
var group = document.createElementNS(svgns, 'g');
group.setAttribute('class', 'allRect');
group.setAttribute('id', 'allRect');

svg.appendChild(group);

var x = document.querySelectorAll('[class^=cl]');

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <svg>
    </svg>

How can I ask javascript to insert a custom selected elements document.querySelectorAll('[class^=cl]') (all 5 Rects) in a group allRect

Body:
I'm not sure I understood the question (rough translation for me)

Is this what you are looking for?

const
  svgns = 'http://www.w3.org/2000/svg'
, fill1 = '#e6e6e6'
, svg   = document.querySelector('svg')
, bg    = svg.appendChild( document.createElementNS(svgns, 'rect') )
, setSvgAttr = (el,attrs) =>
    Object.entries(attrs).forEach(([k,v]) =>
      el.setAttribute(k,v))
  ;

setSvgAttr(svg, { class: 'layer1', xmlns: svgns, width: 400, height: 200, viewBox: '0 0 400 200' })
setSvgAttr(bg, { class: 'bg', id: 'bg', width: 200, height: 200, fill: fill1 })

function createRect(a)
  {
  let rectN = svg.appendChild( document.createElementNS(svgns, 'rect'))
  setSvgAttr(rectN, { class: 'cl'+a, id: 'id'+a, x:a*30, y:a*20, width: 30, height: 30, fill: 'red' })
  }

//create an array from  1 to 5
var bigArray = Array.from({length:5},(_,i)=>++i);

//create Rect for each element of the array
for (const el of bigArray) {  createRect(el) }

//create group
var group = svg.appendChild( document.createElementNS(svgns, 'g'))

setSvgAttr(bg, { class: 'allRect', id: 'allRect' })

document.querySelectorAll('[class^=cl]').forEach( elSVG => group.appendChild(elSVG))

<svg></svg>


问:
Is there any char data type alternative ( 1-byte value ) to represent numeric values?
I've this issue:

```<code>#include <iostream>
int main() {
    unsigned char little_number_from_0_to_255 = 0;
    std::cout << "How old are you (for example)? _";
    std::cin >> little_number_from_0_to_255;
    std::cout << "You are " << little_number_from_0_to_255 << " year/s old.";
}
</code>```

In brief,
even if in this case what follows would'nt care much,
i'd like to avoid the waste of 1 byte (if compared to a short int type) for each variable i need to store when its value is so tiny,
but in all my attempts the un/signed char type variable is always interpreted as the ASCII representation of the first digit of the number I input the un/signed into.

Is there in C++ any good way to have a 1 byte data type, the value of could be only numeric (with all the arithmetic etc., like un/signed char) but without having to deal with the automatic ASCII representation (unlike un/signed char)?

If not, how could i "circumvent" the problem?

Is there a way to avoid that, even if I say that I'm 61, in the variable there will be 54 (decimal) and i will realize that i'm a liar 'cause in reality i'm only 6?

A way to say the computer that it has to grab the whole number and that it hasn't to look only at the first character input?

--I've already read of '+' just before the char variable, but this works only for output, and isn't my case.

答:
Is there in C++ any good way to have a 1 byte data type, the value of could be only numeric (with all the arithmetic etc., like un/signed char) but without having to deal with the automatic ASCII representation (unlike un/signed char)?

You could define a wrapper class that stores a single byte integer type such as std::int8_t as a member, and implicitly converts to a non-character integer type such as int. Whether this is "good" is subjective and depends on use case.

If not, how could i "circumvent" the problem?

You can use an intermediate variable of non-character integer type when dealing with character streams:

```<code>std::uint8_t little_number_from_0_to_255 = 0;

// input
unsigned input;
std::cout << "How old are you (for example)? _";
std::cin >> input;
little_number_from_0_to_255 = input;

// output
unsigned output = little_number_from_0_to_255
std::cout << "You are " << output << " year/s old.";
</code>```

Body:
I've this issue:

#include <iostream>
int main() {
    unsigned char little_number_from_0_to_255 = 0;
    std::cout << "How old are you (for example)? _";
    std::cin >> little_number_from_0_to_255;
    std::cout << "You are " << little_number_from_0_to_255 << " year/s old.";
}

In brief,
even if in this case what follows would'nt care much,
i'd like to avoid the waste of 1 byte (if compared to a short int type) for each variable i need to store when its value is so tiny,
but in all my attempts the un/signed char type variable is always interpreted as the ASCII representation of the first digit of the number I input the un/signed into.

Is there in C++ any good way to have a 1 byte data type, the value of could be only numeric (with all the arithmetic etc., like un/signed char) but without having to deal with the automatic ASCII representation (unlike un/signed char)?

If not, how could i "circumvent" the problem?

Is there a way to avoid that, even if I say that I'm 61, in the variable there will be 54 (decimal) and i will realize that i'm a liar 'cause in reality i'm only 6?

A way to say the computer that it has to grab the whole number and that it hasn't to look only at the first character input?

--I've already read of '+' just before the char variable, but this works only for output, and isn't my case.

Body:
Is there in C++ any good way to have a 1 byte data type, the value of could be only numeric (with all the arithmetic etc., like un/signed char) but without having to deal with the automatic ASCII representation (unlike un/signed char)?

You could define a wrapper class that stores a single byte integer type such as std::int8_t as a member, and implicitly converts to a non-character integer type such as int. Whether this is "good" is subjective and depends on use case.

If not, how could i "circumvent" the problem?

You can use an intermediate variable of non-character integer type when dealing with character streams:

std::uint8_t little_number_from_0_to_255 = 0;

// input
unsigned input;
std::cout << "How old are you (for example)? _";
std::cin >> input;
little_number_from_0_to_255 = input;

// output
unsigned output = little_number_from_0_to_255
std::cout << "You are " << output << " year/s old.";


问:
Delete Stackblitz Project?
I took a screenshot.  I want to delete the project that says "Delete this project".  The button no longer appears.  It used to be something that appeared when we hovered over the link to the project (I hovered over it in the screenshot, but the mouse was not captured):

答:
Now there seem to be certain places to delete the project..

View Profile > kebab menu (3-verticaldots) > delete project

 Or else you can go to Project settings > Delete

Basically, for the people like me who kinda are looking for ' Where is the delete option..?'

Title: Delete Stackblitz Project?


问:
reuse AsiHttpRequest credentials to with UIWebView with loadRequest
I am building an ASIHttpRequest to set the credentials.

My next step is to reuse this request und load an HTML Site with:

```<code>[webView loadRequest:<#(NSURLRequest *)#>]
</code>```

But this is not working with ASIHTTPRequest...

Also I tried to this:

```<code>[self.webView loadData:[asiRequestWebView responseData] MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:targetURL];
</code>```

But still its not working.

And I can't use the ASIWebpageRequest because its not very stable....

Please I need some ideas..

EDIT:

@gardenofwine

Thank you very much.
I ended up doing what you said:

[webView loadRequest:[NSURLRequest  requestWithURL:[asihttprequest url]]];

But told the request before:

asiRequest.useKeychainPersistence = YES;

Now it works like a charm thank you very much!

答:
Can you further explain what exactly did not work, and supply the console log? (compile error, runtime error, crash?)

Can you explain why the following code does not do what you need?

```<code>[webView loadRequest:[NSURLRequest  requestWithURL:[asihttprequest.url]]];
</code>```

Body:
I am building an ASIHttpRequest to set the credentials.

My next step is to reuse this request und load an HTML Site with:

[webView loadRequest:<#(NSURLRequest *)#>]

But this is not working with ASIHTTPRequest...

Also I tried to this:

[self.webView loadData:[asiRequestWebView responseData] MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:targetURL];

But still its not working.

And I can't use the ASIWebpageRequest because its not very stable....

Please I need some ideas..

EDIT:

@gardenofwine

Thank you very much.
I ended up doing what you said:

[webView loadRequest:[NSURLRequest  requestWithURL:[asihttprequest url]]];

But told the request before:

asiRequest.useKeychainPersistence = YES;

Now it works like a charm thank you very much!

Body:
Can you further explain what exactly did not work, and supply the console log? (compile error, runtime error, crash?)

Can you explain why the following code does not do what you need?

[webView loadRequest:[NSURLRequest  requestWithURL:[asihttprequest.url]]];


问:
Flutter - Expected: should do the following in order: emits an event Empty, NumberTriviaError, Actual: Empty: Which was not a Stream or a SteamQue
I'm doing Flutter Clean Architecture TDD course from closely 20days. I'm writing unit test of Stream (mapEventToState) here is my Test code :

```<code>test(
  'should emit [Error] when the input is invalid',
      () async {
    // arrange
    when(mockInputConverter!.stringToUnsignedInteger(SIGNED_STRINGS))
        .thenReturn(Left(InvalidInputFailure()));
    // assert later
    final expected = [
      // The initial state is always emitted first
      NumberTriviaEmpty(),
      NumberTriviaError(message: INVALID_INPUT_FAILURE_MESSAGE),
    ];
    expectLater(bloc!.state, emitsInOrder(expected));
    // act
    bloc!.add(GetTriviaForConcreteNumber(tNumberString));
  },
);
</code>```

Just forget all about (when), because It's fine I've mocked all classes and simply return a Left of Either which is obviously a Failure. So the problem rise in expected data, I just created list of expected and passed it inside the method the "expectLater" in order "emitsInOrder".

My Implementation code of Stream is is here :

```<code>@override
Stream<NumberTriviaState> mapEventToState(NumberTriviaEvent event,) async* {
if (event is GetTriviaForConcreteNumber) {
  final inputEither =
  inputConverter.stringToUnsignedInteger(event.numberString);

  yield* inputEither!.fold(
        (failure) async* {
      yield NumberTriviaError(message: INVALID_INPUT_FAILURE_MESSAGE);
    },
    // Although the "success case" doesn't interest us with the current test,
    // we still have to handle it somehow.
        (integer) => throw UnimplementedError(),
  );
}
</code>```

The [ Error ] I have put in the Title isn't completed because It's a little bit long I'm sharing it here please take a look upon It what actually I'm doing wrong.

```<code>Expected: should do the following in order:
      • emit an event that NumberTriviaEmpty:<NumberTriviaEmpty()>
      • emit an event that NumberTriviaError:<NumberTriviaError(Invalid Input - The number must be a positive integer or zero.)>
 Actual: NumberTriviaEmpty:<NumberTriviaEmpty()>
 Which: was not a Stream or a StreamQueue
</code>```

I have done all these the same, what it expect from me but still it's throwing this exception. I stuck in this error about 4 days I search everywhere but I didn't find any fix, Kindly If I'm doing something wrong just throw your recommendation in the comment section or Answer. Thank you :)

答:
In addition to changing 'bloc!.state' to 'bloc' (per QuangNV and ouflak), try also changing the 'async' in your test to the asynchronous generator, 'async*', to match to the code used in your Stream implementation.</p>
```<code>test(
  'should emit [Error] when the input is invalid',
      () async* {
    // arrange
</code>```

Body:
I'm doing Flutter Clean Architecture TDD course from closely 20days. I'm writing unit test of Stream (mapEventToState) here is my Test code :

test(
  'should emit [Error] when the input is invalid',
      () async {
    // arrange
    when(mockInputConverter!.stringToUnsignedInteger(SIGNED_STRINGS))
        .thenReturn(Left(InvalidInputFailure()));
    // assert later
    final expected = [
      // The initial state is always emitted first
      NumberTriviaEmpty(),
      NumberTriviaError(message: INVALID_INPUT_FAILURE_MESSAGE),
    ];
    expectLater(bloc!.state, emitsInOrder(expected));
    // act
    bloc!.add(GetTriviaForConcreteNumber(tNumberString));
  },
);

Just forget all about (when), because It's fine I've mocked all classes and simply return a Left of Either which is obviously a Failure. So the problem rise in expected data, I just created list of expected and passed it inside the method the "expectLater" in order "emitsInOrder".

My Implementation code of Stream is is here :

@override
Stream<NumberTriviaState> mapEventToState(NumberTriviaEvent event,) async* {
if (event is GetTriviaForConcreteNumber) {
  final inputEither =
  inputConverter.stringToUnsignedInteger(event.numberString);

  yield* inputEither!.fold(
        (failure) async* {
      yield NumberTriviaError(message: INVALID_INPUT_FAILURE_MESSAGE);
    },
    // Although the "success case" doesn't interest us with the current test,
    // we still have to handle it somehow.
        (integer) => throw UnimplementedError(),
  );
}

The [ Error ] I have put in the Title isn't completed because It's a little bit long I'm sharing it here please take a look upon It what actually I'm doing wrong.

Expected: should do the following in order:
      • emit an event that NumberTriviaEmpty:<NumberTriviaEmpty()>
      • emit an event that NumberTriviaError:<NumberTriviaError(Invalid Input - The number must be a positive integer or zero.)>
 Actual: NumberTriviaEmpty:<NumberTriviaEmpty()>
 Which: was not a Stream or a StreamQueue

I have done all these the same, what it expect from me but still it's throwing this exception. I stuck in this error about 4 days I search everywhere but I didn't find any fix, Kindly If I'm doing something wrong just throw your recommendation in the comment section or Answer. Thank you :)

Body:
In addition to changing 'bloc!.state' to 'bloc' (per QuangNV and ouflak), try also changing the 'async' in your test to the asynchronous generator, 'async*', to match to the code used in your Stream implementation.

test(
  'should emit [Error] when the input is invalid',
      () async* {
    // arrange


问:
Optimizing for update only files of size 4-20kb on restricted NVMe AWS disks (Low bandwidth, low latency)
Working on a problem statement where we can't use a DB, instead, we have to implement our own.

Problem statement:-

A request is made to the server with blob (4KB avg, 20KB max) with a UUID and store the blob on disk, sounds perfect use-case for key-pair blobfs, but the catch is, a request from the same UUID will be made again and we'll have to replace the previously written data with a new one, i.e at any point of time we're only concerned with the latest blob.

Request from the same UUID will be made every 10 seconds.

SIGKILL could be made to the server to check the integrity of files. It's okay to lose data of requests made in the last 3 seconds. However, we'd want to make this time as low as possible.

Number of writes is way more than the number of reads

We want to know the maximum number of UUIDs we can support on the given infrastructure.

Infrastructure:-

We have a c6gd.large AWS instance which comes with 4GB RAM, 2 CPUs, 120GB NVMe. But the problem with NVMe is that the bandwidth is restricted by AWS (source), however, we do get low latency (within 150 microseconds).

As shown below, we get more bandwidth while storing in bs of 5kb than 1GB. Also creating a new file is faster than overwriting an existing one.

What I've tried so far:-

Because of the above benchmarks, for each request, I create/update a file with each UUID and write the blob to it.

I've tried both xfs and ext4 filesystem and ext4 performs a bit better and is giving around 8.5k Requests/Second for a 2 hour test. Which means we can support 85k probes as each probe will send request only once every 10 seconds.

I've tested using wrk and noticed that CPU usage on average is around 70-80% and RAM usage is around 3GB (out of 4GB)

I've mounted the disk with ext4 with rw,seclabel,noatime,nodiratime,journal_async_commit,nobarrier these mount options.

NOTE: I've benchmarked the http server alone and it's supporting 100k Req/sec, hence it won't be a bottleneck.

I've used golang for it and this is how I'm writing to file.

I've read about RocksDB architecture, and LSM trees looks promising however I'm of the opinion that compaction process won't give us a huge benefit given that badwidth is just around 100MBps. Am I wrong to think that?

Another question that's in mind is when there are say 1000 writes in a batch to go on disk, I'm assuming that the fs (ext4) journaling will sort these operations. Is this assumpting correct? If not is there a way to enforce this? Also can I batch these write requests to be processed every say 100ms?

Are there any other ideas which I can try?

答:
ideas

buffer requests(go channel, unix datagram socket, redis, ...)

bulk upsert every 100ms

tried

badger db & go channel

rocks db  & unix datagram socket

sqlite3   & unix datagram socket

not tried

RabbitMQ

Kafka

Nats

PostgreSQL

Redis

front
communication
db
result

net/http(go)
go channel
badger(go)
killed(OOM)

net/http(go)
unix datagram socket
rocksdb(rust)
many timeouts

net/http(go)
unix datagram socket
sqlite3(rust)
18,000 rps

benchmark result

latency distribution(ms) and requests per second

50%
75%
90%
99%
rps
description

0.6
0.7
1.2
9.9
176k
1. create files(direct)

2.4
4.5
7.1
14
54k
2. create files(indirect)

6.9
13
19
71
18k
3. sqlite3

10
18
24
46
13k
4. upsert files(dirty)

339
350
667
1320
0.4k
5. upsret files(fdatasync)

connections: 128

threads: 128

duration: 60 seconds

1. create files(direct)

wrk -> GET request

GET request -> actix web server

create empty files

2. create files(indirect)

wrk -> GET request

GET request -> net/http server

data(4k) -> unix datagram socket

unix datagram socket -> create empty files

3. sqlite3

wrk -> GET request

GET request -> net/http server

data(4k) -> unix datagram socket

unix datagram socket -> channel(buffer=128)

channel -> sqlite3(bulk upserts, every 100 ms)

4. upsert files(dirty)

wrk -> GET request

GET request -> net/http server

data(4k) -> unix datagram socket

unix datagram socket -> ext4(without fdatasync)

5. upsret files(fdatasync)

wrk -> GET request

GET request -> net/http server

data(4k) -> unix datagram socket

unix datagram socket -> ext4(temp file)

fdatasync

rename

local pc info

storage

cat /etc/fstab

```<code>LABEL=cloudimg-rootfs   /        ext4   defaults        0 1
</code>```

cpuinfo

fgrep 'model name' /proc/cpuinfo|cat -n

```<code>     1  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
     2  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
     3  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
     4  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
     5  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
     6  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
     7  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
     8  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
     9  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
    10  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
    11  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
    12  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
</code>```

dd

```<code>% dd if=/dev/zero of=./zeros.dat bs=4096 count=262144
262144+0 records in
262144+0 records out
1073741824 bytes (1.1 GB, 1.0 GiB) copied, 2.67881 s, 401 MB/s

% dd if=/dev/zero of=./zeros.dat bs=4096 count=262144 conv=fdatasync
262144+0 records in
262144+0 records out
1073741824 bytes (1.1 GB, 1.0 GiB) copied, 1.02852 s, 1.0 GB/s

% dd if=/dev/zero of=./zeros.dat bs=4096 count=262144 conv=fsync
262144+0 records in
262144+0 records out
1073741824 bytes (1.1 GB, 1.0 GiB) copied, 0.875749 s, 1.2 GB/s
</code>```

Body:
ideas

buffer requests(go channel, unix datagram socket, redis, ...)

bulk upsert every 100ms

tried

badger db & go channel

rocks db  & unix datagram socket

sqlite3   & unix datagram socket

not tried

RabbitMQ

Kafka

Nats

PostgreSQL

Redis

front
communication
db
result

net/http(go)
go channel
badger(go)
killed(OOM)

net/http(go)
unix datagram socket
rocksdb(rust)
many timeouts

net/http(go)
unix datagram socket
sqlite3(rust)
18,000 rps

benchmark result

latency distribution(ms) and requests per second

50%
75%
90%
99%
rps
description

0.6
0.7
1.2
9.9
176k
1. create files(direct)

2.4
4.5
7.1
14
54k
2. create files(indirect)

6.9
13
19
71
18k
3. sqlite3

10
18
24
46
13k
4. upsert files(dirty)

339
350
667
1320
0.4k
5. upsret files(fdatasync)

connections: 128

threads: 128

duration: 60 seconds

1. create files(direct)

wrk -> GET request

GET request -> actix web server

create empty files

2. create files(indirect)

wrk -> GET request

GET request -> net/http server

data(4k) -> unix datagram socket

unix datagram socket -> create empty files

3. sqlite3

wrk -> GET request

GET request -> net/http server

data(4k) -> unix datagram socket

unix datagram socket -> channel(buffer=128)

channel -> sqlite3(bulk upserts, every 100 ms)

4. upsert files(dirty)

wrk -> GET request

GET request -> net/http server

data(4k) -> unix datagram socket

unix datagram socket -> ext4(without fdatasync)

5. upsret files(fdatasync)

wrk -> GET request

GET request -> net/http server

data(4k) -> unix datagram socket

unix datagram socket -> ext4(temp file)

fdatasync

rename

local pc info

storage

cat /etc/fstab

LABEL=cloudimg-rootfs   /        ext4   defaults        0 1

cpuinfo

fgrep 'model name' /proc/cpuinfo|cat -n

     1  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
     2  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
     3  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
     4  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
     5  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
     6  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
     7  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
     8  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
     9  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
    10  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
    11  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
    12  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz

dd

% dd if=/dev/zero of=./zeros.dat bs=4096 count=262144
262144+0 records in
262144+0 records out
1073741824 bytes (1.1 GB, 1.0 GiB) copied, 2.67881 s, 401 MB/s

% dd if=/dev/zero of=./zeros.dat bs=4096 count=262144 conv=fdatasync
262144+0 records in
262144+0 records out
1073741824 bytes (1.1 GB, 1.0 GiB) copied, 1.02852 s, 1.0 GB/s

% dd if=/dev/zero of=./zeros.dat bs=4096 count=262144 conv=fsync
262144+0 records in
262144+0 records out
1073741824 bytes (1.1 GB, 1.0 GiB) copied, 0.875749 s, 1.2 GB/s


问:
socket.io 'disconnect' not called if page refreshed fast enough
I have the following abridged code:

```<code>io.on('connection', function(client) {
    client.uuid = uuid.v4();
    // add client object to server...

    console.log('socket.io:: client connected ' + client.uuid );

    client.on('disconnect', function() {
        console.log('socket.io:: client disconnected ' + client.uuid );
        // remove client object from server...
    });
});
</code>```

If I open up this page in the browser, everything seems fine. If I refresh the page, it will fire disconnect and then connection. However, if I refresh fast enough, there are times where disconnect doesn't get called and thus client data doesn't get cleaned from the server. Is there any way to protect from this?

Edit: reword reconnect -> connection

答:
The same question was answered here.

TL;DR
You can use those options on the client:

const socket = io({
  transports: ['websocket'],
  upgrade: false
});
```

This will prevent socket.io from using the HTTP polling method at all, which causes the issues. I used this trick successfully on v4.

Body:
I have the following abridged code:

io.on('connection', function(client) {
    client.uuid = uuid.v4();
    // add client object to server...

    console.log('socket.io:: client connected ' + client.uuid );

    client.on('disconnect', function() {
        console.log('socket.io:: client disconnected ' + client.uuid );
        // remove client object from server...
    });
});

If I open up this page in the browser, everything seems fine. If I refresh the page, it will fire disconnect and then connection. However, if I refresh fast enough, there are times where disconnect doesn't get called and thus client data doesn't get cleaned from the server. Is there any way to protect from this?

Edit: reword reconnect -> connection

Body:
The same question was answered here.

TL;DR
You can use those options on the client:

const socket = io({
  transports: ['websocket'],
  upgrade: false
});

This will prevent socket.io from using the HTTP polling method at all, which causes the issues. I used this trick successfully on v4.


问:
lines() not showing in r
I was trying to do the forecast for time series. But the confidence interval and predicted value won't show up on the time series plot. I her posted all of my code below, although some might not be relevant to my question.</p>
```<code>ap = scan("airpass.txt")
tsap = ts(ap)
log.ap = log(ap)
par(mfrow = c(1,2))
plot.ts(ap,ylab = "airpass")
plot.ts(log.ap, ylab = "log of airpass")

n = length(log.ap)
tt = seq(1,n)
tt2 = tt^2
cos12 = cos(2*pi*tt/12)
sin12 = sin(2*pi*tt/12)
cos6 = cos(2*pi*tt/6)
sin6 = sin(2*pi*tt/6)
cos4 = cos(2*pi*tt/4)
sin4 = sin(2*pi*tt/4)
rg <- lm(log.ap ~ tt + tt2 + cos12 + sin12 + cos6 + sin6 + cos4 + sin4)
summary(rg)

plot.ts(log.ap)
lines(fitted.values(rg),col="red")

res = residuals(rg)
par(mfrow = c(1,2))
plot.ts(res)
acf(res, lag.max = 20, ylim = c(-1,1))

library(forecast)
ar.res = auto.arima(res,max.p=5,max.q = 0,ic="aic",allowmean = FALSE)
res.res = residuals(ar.res)

h = 5
ar.pre = predict(ar.res,h)
fy = 145:149
# trend forecast
fct = rg$coef[1]+rg$coef[2]*fy+rg$coef[2]*fy+rg$coef[3]*(fy^2)+rg$coef[4]*(cos(2*pi*fy/12))
     +rg$coef[5]*(sin(2*pi*fy/12))+rg$coef[6]*(cos(2*pi*fy/6))+rg$coef[7]*(sin(2*pi*fy/6))
# trend+ar forecast
mean = exp(fct+ar.pre$pred)
# interval
bdr = 1.96*ar.pre$se
upper = exp(fct+ar.pre$pred+bdr)
lower = exp(fct+ar.pre$pred-bdr)

plot(tsap,xlim= c(0,150))
lines(fy, c(mean), lty=1, lwd=2)
lines(fy, c(lower), lty=2, lwd=2)
lines(fy, c(upper), lty=2, lwd=2)
title("Forecasts for the time series")
</code>```

答:
I've just recreated the code using sampling to mimic what you obtained:

```<code>fy = 145:149

tsap <- tibble(x=sample(1:200,100),y=sample(1:200,100))

plot(tsap,xlim= c(0,150))
lines(fy, sample(1:200,5), lty=1, lwd=2)
lines(fy, sample(1:200,5), lty=2, lwd=2)
lines(fy, sample(1:200,5), lty=2, lwd=2)

</code>```

I can see the lines. Perhaps your problem is in the model fitting and posterior predictions. Maybe if you share the data I can help more.

Title: lines() not showing in r

Body:
I was trying to do the forecast for time series. But the confidence interval and predicted value won't show up on the time series plot. I her posted all of my code below, although some might not be relevant to my question.

ap = scan("airpass.txt")
tsap = ts(ap)
log.ap = log(ap)
par(mfrow = c(1,2))
plot.ts(ap,ylab = "airpass")
plot.ts(log.ap, ylab = "log of airpass")

n = length(log.ap)
tt = seq(1,n)
tt2 = tt^2
cos12 = cos(2*pi*tt/12)
sin12 = sin(2*pi*tt/12)
cos6 = cos(2*pi*tt/6)
sin6 = sin(2*pi*tt/6)
cos4 = cos(2*pi*tt/4)
sin4 = sin(2*pi*tt/4)
rg <- lm(log.ap ~ tt + tt2 + cos12 + sin12 + cos6 + sin6 + cos4 + sin4)
summary(rg)

plot.ts(log.ap)
lines(fitted.values(rg),col="red")

res = residuals(rg)
par(mfrow = c(1,2))
plot.ts(res)
acf(res, lag.max = 20, ylim = c(-1,1))

library(forecast)
ar.res = auto.arima(res,max.p=5,max.q = 0,ic="aic",allowmean = FALSE)
res.res = residuals(ar.res)

h = 5
ar.pre = predict(ar.res,h)
fy = 145:149
# trend forecast
fct = rg$coef[1]+rg$coef[2]*fy+rg$coef[2]*fy+rg$coef[3]*(fy^2)+rg$coef[4]*(cos(2*pi*fy/12))
     +rg$coef[5]*(sin(2*pi*fy/12))+rg$coef[6]*(cos(2*pi*fy/6))+rg$coef[7]*(sin(2*pi*fy/6))
# trend+ar forecast
mean = exp(fct+ar.pre$pred)
# interval
bdr = 1.96*ar.pre$se
upper = exp(fct+ar.pre$pred+bdr)
lower = exp(fct+ar.pre$pred-bdr)

plot(tsap,xlim= c(0,150))
lines(fy, c(mean), lty=1, lwd=2)
lines(fy, c(lower), lty=2, lwd=2)
lines(fy, c(upper), lty=2, lwd=2)
title("Forecasts for the time series")

Body:
I've just recreated the code using sampling to mimic what you obtained:

fy = 145:149

tsap <- tibble(x=sample(1:200,100),y=sample(1:200,100))

plot(tsap,xlim= c(0,150))
lines(fy, sample(1:200,5), lty=1, lwd=2)
lines(fy, sample(1:200,5), lty=2, lwd=2)
lines(fy, sample(1:200,5), lty=2, lwd=2)

I can see the lines. Perhaps your problem is in the model fitting and posterior predictions. Maybe if you share the data I can help more.


问:
FTP as folder/webdisk
Is there any way for filezilla(or any other program) to make a folder that is a live ftp folder and any changes I make automatically go to the website.</p>

答:
On mac:
Get server IP address,
In browser type
ftp://IP_ADDRESS_HERE
Hit enter</p>

ContentLicense: CC BY-SA 2.5

Title: FTP as folder/webdisk


问:
Document load event not being called after refresh
I have the following function:

```<code>jQuery(document).ready(function(){
    window.addEventListener("load", function (){
        alert("hello");
});
</code>```

It works on the first run, but then stops working when I hit the refresh button.

If I empty the cache or hard reload, it works again once.

What is going on? How can I fix this?

答:
Try adding the handler outside of jQuery's document.ready():

```<code>window.addEventListener("load", function (){
 ...
});

jQuery(document).ready(function(){
  ...
};
</code>```

On the first run the page might take time to load external resources (such as images). During that time jQuery(document).ready(...) is called.

When it finishes loading the external resources, the load event is fired and the function works correctly.

Weirdly enough, upon refresh, the resources are already cached, so the window.load event is fired so fast and occurs before jQuery(document).ready(), and since you add the event handler after the event was fired, the handler is not called. When you cleared the cache it worked again.

Alternatively, you can check the document for completion first like so:

```<code>function document_loaded(){
    // To be called when the document is loaded.
    ...
};

document.readyState == "complete" ? document_loaded() : window.addEventListener("load", document_loaded);
</code>```

This will work no matter where you place the code.

Body:
I have the following function:

jQuery(document).ready(function(){
    window.addEventListener("load", function (){
        alert("hello");
});

It works on the first run, but then stops working when I hit the refresh button.

If I empty the cache or hard reload, it works again once.

What is going on? How can I fix this?

Body:
Try adding the handler outside of jQuery's document.ready():

window.addEventListener("load", function (){
 ...
});

jQuery(document).ready(function(){
  ...
};

On the first run the page might take time to load external resources (such as images). During that time jQuery(document).ready(...) is called.

When it finishes loading the external resources, the load event is fired and the function works correctly.

Weirdly enough, upon refresh, the resources are already cached, so the window.load event is fired so fast and occurs before jQuery(document).ready(), and since you add the event handler after the event was fired, the handler is not called. When you cleared the cache it worked again.

Alternatively, you can check the document for completion first like so:

function document_loaded(){
    // To be called when the document is loaded.
    ...
};

document.readyState == "complete" ? document_loaded() : window.addEventListener("load", document_loaded);

This will work no matter where you place the code.


问:
How to install pip for Python 3.6 on Ubuntu 16.10?
I'd like to start by pointing out that this question may seem like a duplicate, but it isn't. All the questions I saw here were regarding pip for Python 3 and I'm talking about Python 3.6. The steps used back then don't work for Python 3.6.

I got a clear Ubuntu 16.10 image from the official docker store.

Run apt-get update

Run apt-get install python3.6

Run apt-get install python3-pip

Run pip3 install requests bs4

Run python3.6 script.py

Got ModuleNotFoundError below:

```<code> Traceback (most recent call last):
    File "script.py", line 6, in <module>
     import requests
 ModuleNotFoundError: No module named 'requests'
</code>```

Python's and pip's I have in the machine:

```<code>python3
python3.5
python3.5m
python3.6
python3m
python3-config
python3.5-config
python3.5m-config
python3.6m
python3m-config

pip
pip3
pip3.5
</code>```

答:
Some of the solutions above using the script get-pip.py worked until a couple of weeks ago.

The latest version of this script now requires python3.7 throwing the following error

```<code>ERROR: This script does not work on Python 3.6
The minimun supported Python version is 3.7.
Please use https://bootstrap.pypa.io/pip/3.6/get-pip.py instead.
</code>```

So making the corresponding change works now.

```<code>wget https://bootstrap.pypa.io/pip/3.6/get-pip.py
sudo python3.6 get-pip.py
</code>```

Body:
I'd like to start by pointing out that this question may seem like a duplicate, but it isn't. All the questions I saw here were regarding pip for Python 3 and I'm talking about Python 3.6. The steps used back then don't work for Python 3.6.

I got a clear Ubuntu 16.10 image from the official docker store.

Run apt-get update

Run apt-get install python3.6

Run apt-get install python3-pip

Run pip3 install requests bs4

Run python3.6 script.py

Got ModuleNotFoundError below:

 Traceback (most recent call last):
    File "script.py", line 6, in <module>
     import requests
 ModuleNotFoundError: No module named 'requests'

Python's and pip's I have in the machine:

python3
python3.5
python3.5m
python3.6
python3m
python3-config
python3.5-config
python3.5m-config
python3.6m
python3m-config

pip
pip3
pip3.5

Body:
Some of the solutions above using the script get-pip.py worked until a couple of weeks ago.

The latest version of this script now requires python3.7 throwing the following error

ERROR: This script does not work on Python 3.6
The minimun supported Python version is 3.7.
Please use https://bootstrap.pypa.io/pip/3.6/get-pip.py instead.

So making the corresponding change works now.

wget https://bootstrap.pypa.io/pip/3.6/get-pip.py
sudo python3.6 get-pip.py


问:
SVM performance not consistent with AUC score
I have a dataset that contains information about patients. It includes several variables and their clinical status (0 if they are healthy, 1 if they are sick).
I have tried to implement an SVM model to predict patient status based on these variables.

```<code>library(e1071)

Index <-
  order(Ytrain, decreasing = FALSE)

SVMfit_Var <-
  svm(Xtrain[Index, ], Ytrain[Index],
      type = "C-classification", gamma = 0.005, probability = TRUE, cost = 0.001, epsilon = 0.1)

preds1 <-
  predict(SVMfit_Var, Xtest, probability = TRUE)
preds1 <-
  attr(preds1, "probabilities")[,1]

samples <- !is.na(Ytest)
  pred <- prediction(preds1[samples],Ytest[samples])
  AUC<-performance(pred,"auc")@y.values[[1]]

prediction <- predict(SVMfit_Var, Xtest)
xtab <- table(Ytest, prediction)

</code>```

To test the performance of the model, I have calculated the ROC AUC, and with the validation set I obtain an AUC = 0.997.
But when I view the predictions, all the patients have been assigned as healthy.

```<code>AUC = 0.997
> xtab
     prediction
Ytest  0  1
    0 72  0
    1 52  0
</code>```

Can anyone help me with this problem?

答:
Did you look at the probabilities versus the fitted values? You can read about how probability works with SVM here.

If you want to look at the performance you can use the library DescTools and the function Conf or with the library caret and the function confusionMatrix. (They provide the same output.)

```<code>library(DescTools)
library(caret)

# for the training performance with DescTools
Conf(table(SVMfit_Var$fitted, Ytrain[Index]))
       # svm.model$fitted, y-values for training

# training performance with caret
confusionMatrix(SVMfit_Var$fitted, as.factor(Ytrain[Index]))
             # svm.model$fitted, y-values
                       # if y.values aren't factors, use as.factor()

# for testing performance with DescTools
    # with `table()` in your question, you must flip the order:
         # predicted first, then actual values
Conf(table(prediction, Ytest))

# and for caret
confusionMatrix(prediction, as.factor(Ytest))
</code>```

Your question isn't reproducible, so I went through this with iris data. The probability was the same for every observation. I included this, so you can see this with another data set.

```<code>library(e1071)
library(ROCR)
library(caret)

data("iris")

# make it binary
df1 <- iris %>% filter(Species != "setosa") %>% droplevels()
# check the subset
summary(df1)

set.seed(395) # keep the sample repeatable
tr <- sample(1:nrow(df1), size = 70, # 70%
             replace = F)

# create the model
svm.fit <- svm(df1[tr, -5], df1[tr, ]$Species,
               type = "C-classification",
               gamma = .005, probability = T,
               cost = .001, epsilon = .1)

# look at probabilities
pb.fit <- predict(svm.fit, df1[-tr, -5], probability = T)
            # this shows EVERY row has the same outcome probability distro
pb.fit <- attr(pb.fit, "probabilities")[,1]

# look at performance
performance(prediction(pb.fit, df1[-tr, ]$Species), "auc")@y.values[[1]]
# [1] 0.03555556  that's abysmal!!

# test the model
p.fit = predict(svm.fit, df1[-tr, -5])
confusionMatrix(p.fit, df1[-tr, ]$Species)
# 93% accuracy with NIR at 50%... the AUC score was not useful

# check the trained model performance
confusionMatrix(svm.fit$fitted, df1[tr, ]$Species)
# 87%, with NIR at 50%... that's really good
</code>```

Body:
I have a dataset that contains information about patients. It includes several variables and their clinical status (0 if they are healthy, 1 if they are sick).
I have tried to implement an SVM model to predict patient status based on these variables.

library(e1071)

Index <-
  order(Ytrain, decreasing = FALSE)

SVMfit_Var <-
  svm(Xtrain[Index, ], Ytrain[Index],
      type = "C-classification", gamma = 0.005, probability = TRUE, cost = 0.001, epsilon = 0.1)

preds1 <-
  predict(SVMfit_Var, Xtest, probability = TRUE)
preds1 <-
  attr(preds1, "probabilities")[,1]

samples <- !is.na(Ytest)
  pred <- prediction(preds1[samples],Ytest[samples])
  AUC<-performance(pred,"auc")@y.values[[1]]

prediction <- predict(SVMfit_Var, Xtest)
xtab <- table(Ytest, prediction)

To test the performance of the model, I have calculated the ROC AUC, and with the validation set I obtain an AUC = 0.997.
But when I view the predictions, all the patients have been assigned as healthy.

AUC = 0.997
> xtab
     prediction
Ytest  0  1
    0 72  0
    1 52  0

Can anyone help me with this problem?

Body:
Did you look at the probabilities versus the fitted values? You can read about how probability works with SVM here.

If you want to look at the performance you can use the library DescTools and the function Conf or with the library caret and the function confusionMatrix. (They provide the same output.)

library(DescTools)
library(caret)

# for the training performance with DescTools
Conf(table(SVMfit_Var$fitted, Ytrain[Index]))
       # svm.model$fitted, y-values for training

# training performance with caret
confusionMatrix(SVMfit_Var$fitted, as.factor(Ytrain[Index]))
             # svm.model$fitted, y-values
                       # if y.values aren't factors, use as.factor()

# for testing performance with DescTools
    # with `table()` in your question, you must flip the order:
         # predicted first, then actual values
Conf(table(prediction, Ytest))

# and for caret
confusionMatrix(prediction, as.factor(Ytest))

Your question isn't reproducible, so I went through this with iris data. The probability was the same for every observation. I included this, so you can see this with another data set.

library(e1071)
library(ROCR)
library(caret)

data("iris")

# make it binary
df1 <- iris %>% filter(Species != "setosa") %>% droplevels()
# check the subset
summary(df1)

set.seed(395) # keep the sample repeatable
tr <- sample(1:nrow(df1), size = 70, # 70%
             replace = F)

# create the model
svm.fit <- svm(df1[tr, -5], df1[tr, ]$Species,
               type = "C-classification",
               gamma = .005, probability = T,
               cost = .001, epsilon = .1)

# look at probabilities
pb.fit <- predict(svm.fit, df1[-tr, -5], probability = T)
            # this shows EVERY row has the same outcome probability distro
pb.fit <- attr(pb.fit, "probabilities")[,1]

# look at performance
performance(prediction(pb.fit, df1[-tr, ]$Species), "auc")@y.values[[1]]
# [1] 0.03555556  that's abysmal!!

# test the model
p.fit = predict(svm.fit, df1[-tr, -5])
confusionMatrix(p.fit, df1[-tr, ]$Species)
# 93% accuracy with NIR at 50%... the AUC score was not useful

# check the trained model performance
confusionMatrix(svm.fit$fitted, df1[tr, ]$Species)
# 87%, with NIR at 50%... that's really good


问:
Spring boot stops right after "Started <app_name> in X seconds (JVM running for Y)
I am using Eclipse 14.4.0 on Ubuntu 20.04.3. I've loaded "Spring Tools 3" and a Lombok plugin.

Here's my pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.test</groupId>
    <artifactId>test</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>test</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>13</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

The TestApplication class:

```<code>package com.test.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

}
</code>```

And the DemoController class:

```<code>package com.test.test.controller;

//Importing required classes
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

// Annotation
@Controller

// Class
public class DemoController {

    @RequestMapping("/hello")
    @ResponseBody

    // Method
    public String helloWorld()
    {

        // Print statement
        return "Hello World!";
    }
}
</code>```

To run the program, I right-click on it and select Run As --> Java Application. From the "Select Java Application" popup that's generated, I select "TestApplication - com.test.test".

Spring Boot loads and runs until it gets to the final line of code below, after which nothing happens.

```<code>  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.6.3)

2022-02-12 16:21:21.779  INFO 166442 --- [           main] com.test.test.TestApplication            : Starting TestApplication using Java 13.0.2 on ubuntu with PID 166442 (/home/oleh/Downloads/test/target/classes started by oleh in /home/oleh/Downloads/test)
2022-02-12 16:21:21.849  INFO 166442 --- [           main] com.test.test.TestApplication            : No active profile set, falling back to default profiles: default
2022-02-12 16:21:58.814  INFO 166442 --- [           main] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port 8080
2022-02-12 16:21:59.033  INFO 166442 --- [           main] com.test.test.TestApplication            : Started TestApplication in 43.693 seconds (JVM running for 51.954)
</code>```

If I open a web browser and search the localhost:8080 URL, I'm given an error that says "Whitelable Error Page".

I've tried updating Maven dependencies and cleaning the project. I've also tried many variations of this project, all of which ended the same way. I'm not sure what to verify and debug because the console does not print any errors.

Can anyone help explain what is missing for the browser window to open and "Hello World!" to be displayed on it?

Many thanks.

答: Please try localhost:8080/hello</p>

Body:
I am using Eclipse 14.4.0 on Ubuntu 20.04.3. I've loaded "Spring Tools 3" and a Lombok plugin.

Here's my pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath/>
    </parent>
    <groupId>com.test</groupId>
    <artifactId>test</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>test</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>13</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

The TestApplication class:

package com.test.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

}

And the DemoController class:

package com.test.test.controller;

//Importing required classes
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

// Annotation
@Controller

// Class
public class DemoController {

    @RequestMapping("/hello")
    @ResponseBody

    // Method
    public String helloWorld()
    {

        // Print statement
        return "Hello World!";
    }
}

To run the program, I right-click on it and select Run As --> Java Application. From the "Select Java Application" popup that's generated, I select "TestApplication - com.test.test".

Spring Boot loads and runs until it gets to the final line of code below, after which nothing happens.

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.6.3)

2022-02-12 16:21:21.779  INFO 166442 --- [           main] com.test.test.TestApplication            : Starting TestApplication using Java 13.0.2 on ubuntu with PID 166442 (/home/oleh/Downloads/test/target/classes started by oleh in /home/oleh/Downloads/test)
2022-02-12 16:21:21.849  INFO 166442 --- [           main] com.test.test.TestApplication            : No active profile set, falling back to default profiles: default
2022-02-12 16:21:58.814  INFO 166442 --- [           main] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port 8080
2022-02-12 16:21:59.033  INFO 166442 --- [           main] com.test.test.TestApplication            : Started TestApplication in 43.693 seconds (JVM running for 51.954)

If I open a web browser and search the localhost:8080 URL, I'm given an error that says "Whitelable Error Page".

I've tried updating Maven dependencies and cleaning the project. I've also tried many variations of this project, all of which ended the same way. I'm not sure what to verify and debug because the console does not print any errors.

Can anyone help explain what is missing for the browser window to open and "Hello World!" to be displayed on it?

Many thanks.

Body: Please try localhost:8080/hello


问:
Swipe between multiple CollectionViews in iOS Swift
I hope someone can help me.

I would like to swipe left and right between several CollectionViews and add another CollectionView in Runtime with a button on the last page.

How could I build up the structure?

My purpose: The user can create his own smart grid to create different shortcuts in each CollectionView item. I want to add more "pages" now.

Thank you!

>> I have attached a picture of how it should work <<

EDIT: I found something helpful for my case:
https://www.youtube.com/watch?v=hIMRn_LdvOg

答: There is a number of ways you can do that. One way is to use UIPageViewController where each UICollectionView is hosted by a UIViewController (or UICollectionViewController)</p>


问:
CSS problem, 100% width keeps moving out of position
I'm currently working on this website,
http://no-illusions.nl
It's going fine but I found a pretty stupid thing that I can't resolve.

I have an div (wrapper) with an width of 500px and inside I have different div's containing images and text. Now the problem is that the text is dynamic in width, on some parts it could be 200px width and on some pages it could be 350px.

So I put the width on 100% but now the part just floats underneath where I want it!

This is how it should look,
![how it should look][1]

But this is how it looks,

I hope you guys can give me a push in the right direction.

答: You can set a max-width of 330px on your .update_respond class.</p>


问:
convert emoji unicode to TEXT in python
I have an application made in python (yowsup), I receive text and emoji in my bot...
I manage to get the 😀 to convert to "\U0001F600" code...

now i need to convert u"\U0001F600" to :grinning: TEXT or GRINNING FACE

got some source from this page....
http://www.fileformat.info/info/unicode/char/1F600/index.htm

```<code>@signals.message_received.connect
def handle(message):
    #message.log() to see message object properties
    #print(message.log())
    params = {}
    params_upload = {}
    zapsend_host = config.config_variables['zapsend_host']
    zapsend_port = config.config_variables['zapsend_port']

    # CASE TEXT-MESSAGE AND NOT GROUP
    if helper.is_text_message(message.message_entity) and helper.isGroupJid(message.conversation) == False:
        #converted here....
        params['msg']  = message.text.encode('unicode_escape')
        params['number']  = message.conversation
        params['whatsapp']= config.config_variables['user']
        params['media'] = 'text'
        params['caption'] = ''
        params['name'] = message.who_name
        database_helper.sync_contacts(message.conversation, message.who_name)
        database_helper.save_message_receive(params, message)
        print("MSG FROM CLIENT: "+ message.conversation +" => " + params['msg'])
        requests_helper.request_get(zapsend_host, zapsend_port,'zapsend',params)
</code>```

答:
This approach will handle both:

emojis:

emoticons: :-)) ; 8‑D

Using the emot library and a bit of text manipulation:
Using flashtext as it is much faster than regular expression for exact string find and/or replace.

```<code>from emot.emo_unicode import UNICODE_EMOJI, UNICODE_EMOJI_ALIAS, EMOTICONS_EMO
from flashtext import KeywordProcessor

## formatting
all_emoji_emoticons = {**EMOTICONS_EMO,**UNICODE_EMOJI_ALIAS, **UNICODE_EMOJI_ALIAS}
all_emoji_emoticons = {k:v.replace(":","").replace("_"," ").strip() for k,v in all_emoji_emoticons.items()}

kp_all_emoji_emoticons = KeywordProcessor()
for k,v in all_emoji_emoticons.items():
    kp_all_emoji_emoticons.add_keyword(k, v)
kp_all_emoji_emoticons.replace_keywords('I am an  hehe :-)). Lets try another one . It seems ')

#output==> 'I am an alien hehe Very happy. Lets try another one astonished. It seems ok hand'
</code>```

Title: convert emoji unicode to TEXT in python

Body:
I have an application made in python (yowsup), I receive text and emoji in my bot...
I manage to get the 😀 to convert to "\U0001F600" code...

now i need to convert u"\U0001F600" to :grinning: TEXT or GRINNING FACE

got some source from this page....
http://www.fileformat.info/info/unicode/char/1F600/index.htm

@signals.message_received.connect
def handle(message):
    #message.log() to see message object properties
    #print(message.log())
    params = {}
    params_upload = {}
    zapsend_host = config.config_variables['zapsend_host']
    zapsend_port = config.config_variables['zapsend_port']

    # CASE TEXT-MESSAGE AND NOT GROUP
    if helper.is_text_message(message.message_entity) and helper.isGroupJid(message.conversation) == False:
        #converted here....
        params['msg']  = message.text.encode('unicode_escape')
        params['number']  = message.conversation
        params['whatsapp']= config.config_variables['user']
        params['media'] = 'text'
        params['caption'] = ''
        params['name'] = message.who_name
        database_helper.sync_contacts(message.conversation, message.who_name)
        database_helper.save_message_receive(params, message)
        print("MSG FROM CLIENT: "+ message.conversation +" => " + params['msg'])
        requests_helper.request_get(zapsend_host, zapsend_port,'zapsend',params)

Body:
This approach will handle both:

emojis:

emoticons: :-)) ; 8‑D

Using the emot library and a bit of text manipulation:
Using flashtext as it is much faster than regular expression for exact string find and/or replace.

from emot.emo_unicode import UNICODE_EMOJI, UNICODE_EMOJI_ALIAS, EMOTICONS_EMO
from flashtext import KeywordProcessor

## formatting
all_emoji_emoticons = {**EMOTICONS_EMO,**UNICODE_EMOJI_ALIAS, **UNICODE_EMOJI_ALIAS}
all_emoji_emoticons = {k:v.replace(":","").replace("_"," ").strip() for k,v in all_emoji_emoticons.items()}

kp_all_emoji_emoticons = KeywordProcessor()
for k,v in all_emoji_emoticons.items():
    kp_all_emoji_emoticons.add_keyword(k, v)
kp_all_emoji_emoticons.replace_keywords('I am an  hehe :-)). Lets try another one . It seems ')

#output==> 'I am an alien hehe Very happy. Lets try another one astonished. It seems ok hand'


问:
matplot lib showing strange offset at top
Matplotlib is behaving strangely on some very large values.

I want the graph to show the ACTUAL numbers, in my case 61577 and 61578.

Instead its showing only the 1s place, and doing a +6.15700000e4 at the very top. Is there an option i need to specify to get the graph to show actuals instead of an offset?

There is definitely some kind of scale being applied; when I change the numbers to 1577 and 1578, it looks like you'd expect it to.  So what do I need to turn off?

Simple test case:

```<code>import matplotlib.pyplot as plt
y = [61577,61577,61577,61577,61577,61577,61578,61577,61578,61578,61578,61578,61578,61578,61578,61578,61578,61578,61578]
x = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]

plt.plot(x, y)

plt.xlabel('x - axis')
plt.ylabel('y - axis')

plt.show()
</code>```

答:
This is because the y axis numbers are so big, it changes the range of the graph. +6.15700000e4 is just standard notation for 6,157. It is displaying the first 4 numbers of your data on the y axis "6157" and then the final digit so the graph is easier to see. That is also why the spike looks so large, but in reality it is just a change in 1. Here's one way to change the axis range so it doesn't use scientific notation</p>
```<code>import matplotlib.pyplot as plt
y = [61577,61577,61577,61577,61577,61577,61578,61577,61578,61578,61578,61578,61578,61578,61578,61578,61578,61578,61578]
x = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]

_, ax = plt.subplots()
ax.plot(x, y)
ax.ticklabel_format(useOffset=False)
plt.xlabel('x - axis')
plt.ylabel('y - axis')
plt.show()
</code>```

Body:
Matplotlib is behaving strangely on some very large values.

I want the graph to show the ACTUAL numbers, in my case 61577 and 61578.

Instead its showing only the 1s place, and doing a +6.15700000e4 at the very top. Is there an option i need to specify to get the graph to show actuals instead of an offset?

There is definitely some kind of scale being applied; when I change the numbers to 1577 and 1578, it looks like you'd expect it to.  So what do I need to turn off?

Simple test case:

import matplotlib.pyplot as plt
y = [61577,61577,61577,61577,61577,61577,61578,61577,61578,61578,61578,61578,61578,61578,61578,61578,61578,61578,61578]
x = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]

plt.plot(x, y)

plt.xlabel('x - axis')
plt.ylabel('y - axis')

plt.show()

Body:
This is because the y axis numbers are so big, it changes the range of the graph. +6.15700000e4 is just standard notation for 6,157. It is displaying the first 4 numbers of your data on the y axis "6157" and then the final digit so the graph is easier to see. That is also why the spike looks so large, but in reality it is just a change in 1. Here's one way to change the axis range so it doesn't use scientific notation

import matplotlib.pyplot as plt
y = [61577,61577,61577,61577,61577,61577,61578,61577,61578,61578,61578,61578,61578,61578,61578,61578,61578,61578,61578]
x = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]

_, ax = plt.subplots()
ax.plot(x, y)
ax.ticklabel_format(useOffset=False)
plt.xlabel('x - axis')
plt.ylabel('y - axis')
plt.show()


问:
Getting rid of "There is no source code available for the current location."
OK, this is my own fault, but I can't seem to rescue myself.

Whenever I try to step into a class that has fields with assignments calling into .NET code, I get a dialog box that contains the text "There is no source code available for the current location.":

For instance, stepping into the constructor of the following class would give me the above message:

```<code>public class Test
{
    private Stack<String> _Dummy = new Stack<String>();
    public Test() { }
}
</code>```

I assume this is because at some point I fiddled with the settings for the symbol server, but no matter what I fiddle with now, I can't seem to get rid of that message.

Where has my stupidity forgotten what it did?

Summary of my current options:

[ ] Enable address-level debugging

[x] Enable Just My Code (Managed Only)

[ ] Enable .NET framework source stepping

[ ] Enable source server support

Symbol file .pdb locations - empty

Cache symbols from symbol servers to this directory: C:\temp (empty)

答:
I had this problem in VS 2017 C++

TLDR: It was accesing data beyond the limit

The program finished in debug mode and it showed this message: wntdll.pdb not loaded

After fixing it with this answer it started to show the message: There is no source code available for the current location

But also there was a message that popped saying: app.exe has triggered a breakpoint, but the breakpoint was not in my source code, it was in the source code generated by VS in debug mode, Right click in the source code -> Go to Disassembly and the break point was int 3 instruction

At the end it was just a stack overflow, since the code was accesing data beyond the limit, I just fixed the code and the messages were gone

I guess VS didn't show an error about accesing data outside the limit because I was using Winapi function GetEnvironmentStrings() and in the site says: Treat this memory as read-only; do not modify it directly and I was modifying it :)

OwnerDisplayName: lassevk

Body:
OK, this is my own fault, but I can't seem to rescue myself.

Whenever I try to step into a class that has fields with assignments calling into .NET code, I get a dialog box that contains the text "There is no source code available for the current location.":

For instance, stepping into the constructor of the following class would give me the above message:

public class Test
{
    private Stack<String> _Dummy = new Stack<String>();
    public Test() { }
}

I assume this is because at some point I fiddled with the settings for the symbol server, but no matter what I fiddle with now, I can't seem to get rid of that message.

Where has my stupidity forgotten what it did?

Summary of my current options:

[ ] Enable address-level debugging

[x] Enable Just My Code (Managed Only)

[ ] Enable .NET framework source stepping

[ ] Enable source server support

Symbol file .pdb locations - empty

Cache symbols from symbol servers to this directory: C:\temp (empty)