问:
Problem sending messages at regular intervals for Discord.js
My goal is to create a Discord.js bot to automate sending a message at an interval. But when I run my program, the bot starts fine and connects to Discord but when it needs to send the message according to the given time, the bot disconnects and shows this error message :

channel.send("test");
TypeError: Cannot read properties of undefined (reading 'send').

Here is my code :

```<code>const Discord = require('discord.js')
const client = new Discord.Client({ intents: ["GUILD_MESSAGES"] });
const { Client, Intents } = require('discord.js');

client.on('ready', () => {
  var testChannel = client.channels.cache.find(channel => channel.id === 'ID_CHANNEL');

  console.log("I'm connected !");

  setInterval(() => {
    testChannel.send("test");
  }, 5000);
});

client.login('TOKEN')
</code>```

Thank you in advance for your precious help,

答:
You seem to be lack of some intents. If you provide intents manually bot will not get anything but things that you have included in your client configuration, so testchannel will always be undefined. So you can solve this easily, by adding intents.

```<code>const Discord = require('discord.js')
const { Client, Intents } = require('discord.js');
const client = new Discord.Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MEMBERS, Intents.FLAGS.DIRECT_MESSAGES, Intents.FLAGS.GUILD_MESSAGES] });

client.on('ready', () => {
  var testChannel = client.channels.cache.find(channel => channel.id === 'ID_CHANNEL');

  console.log("I'm connected !");

  setInterval(() => {
    testChannel.send("test");
  }, 5000);
});

client.login('TOKEN')
</code>```

Body:
My goal is to create a Discord.js bot to automate sending a message at an interval. But when I run my program, the bot starts fine and connects to Discord but when it needs to send the message according to the given time, the bot disconnects and shows this error message :

channel.send("test");
TypeError: Cannot read properties of undefined (reading 'send').

Here is my code :

const Discord = require('discord.js')
const client = new Discord.Client({ intents: ["GUILD_MESSAGES"] });
const { Client, Intents } = require('discord.js');

client.on('ready', () => {
  var testChannel = client.channels.cache.find(channel => channel.id === 'ID_CHANNEL');

  console.log("I'm connected !");

  setInterval(() => {
    testChannel.send("test");
  }, 5000);
});

client.login('TOKEN')

Thank you in advance for your precious help,

Body:
You seem to be lack of some intents. If you provide intents manually bot will not get anything but things that you have included in your client configuration, so testchannel will always be undefined. So you can solve this easily, by adding intents.

const Discord = require('discord.js')
const { Client, Intents } = require('discord.js');
const client = new Discord.Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MEMBERS, Intents.FLAGS.DIRECT_MESSAGES, Intents.FLAGS.GUILD_MESSAGES] });

client.on('ready', () => {
  var testChannel = client.channels.cache.find(channel => channel.id === 'ID_CHANNEL');

  console.log("I'm connected !");

  setInterval(() => {
    testChannel.send("test");
  }, 5000);
});

client.login('TOKEN')


来源: stackexchange

问:
How do i solve General error: 1364 - Laravel
Screenshot of the error page

How do i go about this please? I created another table in my db where i generate OTPs and send to the users. in my table i made user_id and id(primary) but due to the nature of my code and how i want the site to function, i set user_id as a reference of id so that whenever OTP is generated, it will be the current user's ID

It seems there's no default value for user_id so i did ;

```<code>UserOTP::create(["user_id"=> auth()->id()]);
</code>```

but its not working, what is wrong with my code please?

```<code>    <?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUserOtpsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {

        Schema::create('user_otps', function (Blueprint $table) {

            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->integer('code');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();

        });

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('user_otps');
    }
}
</code>```

This is the db migration file

答:
It's a SQL error not a PHP one. You're trying to insert a new row without a user_id but there's no default value set for that column, so it doesn't know what to set it as.

In your migration class, try giving it a default value:

```<code>$table->unsignedBigInteger('user_id')->default(null);
</code>```

In any case, it also seems like you're not inserting with a user_id, only code, so you need to probably ensure that field can be persisted.

Edit: Yes, now you've posted your model, the problem is you haven't allowed the user_id field to be fillable:

```<code>// UserOtp.php
protected $fillable = ['code' , 'user_id'];
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Screenshot of the error page

How do i go about this please? I created another table in my db where i generate OTPs and send to the users. in my table i made user_id and id(primary) but due to the nature of my code and how i want the site to function, i set user_id as a reference of id so that whenever OTP is generated, it will be the current user's ID

It seems there's no default value for user_id so i did ;

UserOTP::create(["user_id"=> auth()->id()]);

but its not working, what is wrong with my code please?

    <?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUserOtpsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {

        Schema::create('user_otps', function (Blueprint $table) {

            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->integer('code');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();

        });

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('user_otps');
    }
}

This is the db migration file

Body:
It's a SQL error not a PHP one. You're trying to insert a new row without a user_id but there's no default value set for that column, so it doesn't know what to set it as.

In your migration class, try giving it a default value:

$table->unsignedBigInteger('user_id')->default(null);

In any case, it also seems like you're not inserting with a user_id, only code, so you need to probably ensure that field can be persisted.

Edit: Yes, now you've posted your model, the problem is you haven't allowed the user_id field to be fillable:

// UserOtp.php
protected $fillable = ['code' , 'user_id'];


问:
What does a `workspace:` prefix in a package.json 'dependencies' value mean?
Where can I learn more about what is workspace: prefix in version number?

For example, in Babel:

  "dependencies": {
    "@babel/helper-plugin-utils": "workspace:^7.13.0",
```

source

答:
you could check about this dependency via using this command</p>
```<code>yarn why <dependency-name>
</code>```

Body:
Where can I learn more about what is workspace: prefix in version number?

For example, in Babel:

  "dependencies": {
    "@babel/helper-plugin-utils": "workspace:^7.13.0",

source

Body:
you could check about this dependency via using this command

yarn why <dependency-name>


问:
Android's addJavascriptInterface equivalent in iOS
As you may know, Android's WebView has a method named addJavascriptInterface() which imports an Android JAVA object to Javascript context.

the question is, Is there any equivalent of it on iOS?

答:
UIWebView on iOS doesn't have methods to add interface to DOM.

But you still can talk to your code from javascript assigning something to window.location and handling that request in webView:shouldStartLoadWithRequest:navigationType: delegate method.

ContentLicense: CC BY-SA 3.0


问:
Is there any Excel function that can copy column's (first row's) name if the value matches?
I can't figure out a function that would automatically copy the first row value if the value on another rows matches 1. I would need the red dates to be automated.

Any advice would be very appreciated, thank you!

Excel problem

答:
```<code>=INDEX($E$1:$O$1;1;MATCH(1;E2:O2;0))
</code>```

Replace semicolon with comma if your Excel version needs it.

If you have, you can also use Xlookup, it's a bit easier.

```<code>=XLOOKUP(1;E2:O2;$E$1:$O$1;"not found")
</code>```

Body:
=INDEX($E$1:$O$1;1;MATCH(1;E2:O2;0))

Replace semicolon with comma if your Excel version needs it.

If you have, you can also use Xlookup, it's a bit easier.

=XLOOKUP(1;E2:O2;$E$1:$O$1;"not found")


问:
Paste comma separated content into different cells in google sheets
Say I have the string "1,2,3,4". Is it possible to paste that string into Google Spreadsheets in such a way that each of the comma-separated values goes into a different cell to the right of the selected one?
This is what the spreadsheet would look like after pasting.</p>

答:
First select the cell on of your action and click Data

1st step

Now, select 'split text to column', it will name it a number

2nd step

now, again goto data and select split text to column open it will transfer every comma separated element into individual columns

3rd step


问:
Cleaning up Data with Variably Noisy Signal
I have been running a study where we unexpectedly received a disparate amount of noise in our signal depending on how we collected it. Now, I am trying to learn how to filter out the noise, though I am fairly new signal processing / cleaning. With one method of data collection, we got a lot less noise as shown here:

These are weight measurements on a scale where the object being weighed is removed, manipulated, and then reweighed which results in the "stair step" like pattern. The intent is to use this data in future with a change detection algorithm to identify where the weight changes are (i.e., the "stair steps") for a decently high volume of data that makes doing it by eye untenable. I think what I need is a low pass filter to remove those really brief instances where the signal goes really high. However, with another form of collection we received a lot more noise:

I am literate in python and R, but am just unsure where to begin to clean such disparate looking data and how to save its integrity for  the subsequent change detection analysis. I thought about simply deleting high and low weight values, but this leads to a problem with the change detection algorithm. Any suggestions are appreciated and I've attached sample data.

https://docs.google.com/spreadsheets/d/1qLFmuP3CfU40MjV9-o2zos4ylTXzHcwo/edit?usp=sharing&ouid=100771405497110181259&rtpof=true&sd=true

答:
You could apply a median filter.
It will both remove glitches and fluctuations of the measurements, and has only one parameter to tune, the size of the window.

from scipy.ndimage import median_filter
import matplotlib.pyplot as plt
plt.figure(figsize=(14, 4))
plt.plot(median_filter(x, 10), label='window=10')
plt.plot(median_filter(x, 100), label='window=100')
plt.legend()
plt.grid()
```


问:
loop through html inputs that have an ID
I'm struggling here with some javascript code I need. I have an html document with more than 300 inputs (type text). All inputs have an id, some inputs also have a name (similar to the id). I want to loop through all input tags that have an ID but do not have a name and for each one add a name attribute identical to the ID.

I think it's simple and I know how to find or loop through elements with specific ID but there is something I'm missing and cant figure it out.

答:
You can use querySelectorAll with the attribute selector [attr], loop through and check if it's got a name, if not copy the ID to the name.

eg.

for (const el of document.querySelectorAll('input[id]')) {
  if (!el.getAttribute('name')) {
    el.setAttribute('name', el.getAttribute('id'));
  }
}

console.log(document.querySelector('form').innerHTML);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <input id="bob"/>
  <input id="john"/>
  <input name="gotname"/>
</form></code>```

Body:
You can use querySelectorAll with the attribute selector [attr], loop through and check if it's got a name, if not copy the ID to the name.

eg.

for (const el of document.querySelectorAll('input[id]')) {
  if (!el.getAttribute('name')) {
    el.setAttribute('name', el.getAttribute('id'));
  }
}

console.log(document.querySelector('form').innerHTML);

<form>
  <input id="bob"/>
  <input id="john"/>
  <input name="gotname"/>
</form>


问:
how to click a button if another element contains a text
I am testing an app and have a difficulty to click a button which another element contains a text as seen below.

I want to click on "DETAILS" button which has "UPCOMING" word above it.

I have tried to do it but none of it does the job.

First

```<code>for booking_card in context.driver.find_element_by_xpath("//*(@class='android.view.ViewGroup')"):
        if booking_card.text == "UPCOMING":
            context.driver.find_element_by_xpath("//*[contains(@text, 'DETAILS')]").click()
</code>```

Second

```<code>context.driver.find_element_by_xpath("//*[contains(@text, 'UPCOMING')]//*[@text='DETAILS']").click()
</code>```

Third
I tried to find the details button using the parent, sibling and ancestor method but still failed.

```<code>//*[@class='android.view.ViewGroup']//*[contains(@text, 'UPCOMING')]/following-sibling::*[contains(@text, 'DETAILS')]
</code>```

here is the Hierarchy of the elements:

I really appreciate any help, thank you.
If there's something else I need to explain, let me know.

答:
I have discovered the answer, so the way to do it is to use parent, following-sibling method.
all I did is to make sure the hierarchy of the elements are correct so that I can find what I was looking for.

here's the code that I have done, it's simple.

```<code>isPresent(context, MobileBy.XPATH, "//*[@text='UPCOMING']/parent::*[@class='android.view.ViewGroup']/parent::*[@class='android.view.ViewGroup']/following-sibling::*[@class='android.view.ViewGroup']//*[@text='DETAILS']").click()
</code>```

so the way I did it, to look the 'UPCOMING' word first, and then I need to find the parent element and then click on the DETAILS button.

Body:
I am testing an app and have a difficulty to click a button which another element contains a text as seen below.

I want to click on "DETAILS" button which has "UPCOMING" word above it.

I have tried to do it but none of it does the job.

First

for booking_card in context.driver.find_element_by_xpath("//*(@class='android.view.ViewGroup')"):
        if booking_card.text == "UPCOMING":
            context.driver.find_element_by_xpath("//*[contains(@text, 'DETAILS')]").click()

Second

context.driver.find_element_by_xpath("//*[contains(@text, 'UPCOMING')]//*[@text='DETAILS']").click()

Third
I tried to find the details button using the parent, sibling and ancestor method but still failed.

//*[@class='android.view.ViewGroup']//*[contains(@text, 'UPCOMING')]/following-sibling::*[contains(@text, 'DETAILS')]

here is the Hierarchy of the elements:

I really appreciate any help, thank you.
If there's something else I need to explain, let me know.

Body:
I have discovered the answer, so the way to do it is to use parent, following-sibling method.
all I did is to make sure the hierarchy of the elements are correct so that I can find what I was looking for.

here's the code that I have done, it's simple.

isPresent(context, MobileBy.XPATH, "//*[@text='UPCOMING']/parent::*[@class='android.view.ViewGroup']/parent::*[@class='android.view.ViewGroup']/following-sibling::*[@class='android.view.ViewGroup']//*[@text='DETAILS']").click()

so the way I did it, to look the 'UPCOMING' word first, and then I need to find the parent element and then click on the DETAILS button.


问:
error in replaceAll() method
i have error in String st=str.replaceAll(" ","");
But include the import java.lang.String.*;
After adding this line again same error repeated..
So please anyone help me to solve the error..

```<code>String st=str.replaceAll(" ","");
</code>```

答:
We can't really tell what's wrong without you telling us the error message or giving us more code. Your snippet is missing a semi-colon, and relies on str being a definitely-assigned variable of type String, but that's all.

Sample code that works:

```<code>public class Test {
    public static void main(String args[]) {
        String str = "hello world";
        String st = str.replaceAll(" ", "");
        System.out.println(st); // helloworld
    }
}
</code>```

Now you just need to find the difference between your code and my code...

Title: error in replaceAll() method

Body:
i have error in String st=str.replaceAll(" ","");
But include the import java.lang.String.*;
After adding this line again same error repeated..
So please anyone help me to solve the error..

String st=str.replaceAll(" ","");

Body:
We can't really tell what's wrong without you telling us the error message or giving us more code. Your snippet is missing a semi-colon, and relies on str being a definitely-assigned variable of type String, but that's all.

Sample code that works:

public class Test {
    public static void main(String args[]) {
        String str = "hello world";
        String st = str.replaceAll(" ", "");
        System.out.println(st); // helloworld
    }
}

Now you just need to find the difference between your code and my code...


问:
Load stylesheet with javascript and localStorage
I'm using a Jekyll website, doesn't really matter because this is a static page, I just write it as additional info.

Desired behavior:

I want to load my stylesheet via javascript, so it can depend of a local stored value, let's say dark and light.

I have done a little test of loading it by JS with the following code (which works).

GREEN

```<code><head>
  ...
  <link rel="stylesheet" href="/assets/css/{{'light'}}.css">
  ...
</head>
</code>```

This loads the CSS file called "light" as expected.

But now I want to depend of the localStorage, with a variable theme that has light as value. I tried the following:

RED

```<code><head>
  ...
  <script>
    var storedTheme = window.localStorage.getItem('theme'); //Tested and working in console
    theme = storedTheme ? storedTheme : 'light'; //global variable (also readable in console)
  </script>

  <link rel="stylesheet" href="/assets/css/{{theme}}.css"> <!-- cant read global variable -->
  ...
</head>
</code>```

Using global variables doesn't work, it gives me a 404 error as the stylesheet path is /assets/css/.css.

After that I thought that maybe creating an element would do the trick and I created one manually to test it:

RED

```<code><head>
...
<p id="theme" style="display:none;">dark</p>

<link rel="stylesheet" href="/assets/css/{{document.getElementById('theme').innerHTML}}.css">
...
</head>
</code>```

And nope, the path still appears as: /assets/css/.css

答:
If you change styles on the  you get FOUC (Flash Of Unstyled Content). Try using a close equivalent like   and spread it 100% x 100% and  and  as well, but give them margin and padding of 0 in order to ensure  covers them completely.

The [disabled] attribute for the <link> is the best way of toggling them because they are still loaded but inert. Also, in the example there is a function called loadTheme(e) that is loaded on the 'DOMContentLoaded' event which insures that all of the DOM is loaded before hand. The example below will not work because localStorage is blocked on SO. There is a functioning example on Plunker. To test it:

Click the green Preview button.

Another frame should appear on the right. Within the frame is the webpage example click the ☀ button.

It should be in dark mode now. Next, click the refresh ⟳ button located in the mini-toolbar within the frame or press ctrl+enter for Windows OS or ⌥+return for Mac OS.

The page should still be in dark mode.

/* night.css
main {
  background: #000;
  color: #fff;
}
*/

/* default.css */
:root {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
  font: 1ch/1.5 'Segoe UI';
}

body {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
  font-size: 4ch;
}

main {
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  color: #000;
}

form {
  width: 80vw;
  margin: 20px auto;
}

fieldset {
  width: max-content;
  min-height: 25px;
  margin-left: auto;
  padding: 0 1.5px 1.5px;
  border-radius: 8px;
  background: inherit;
  color: inherit;
}

button {
  display: block;
  width: 100%;
  height: 100%;
  border: 0;
  font-size: 4rem;
  text-align: center;
  background: transparent;
  cursor: pointer;
}

#theme::before {
  content: '☀';
}

.night #theme::before {
  content: '';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta charset='utf-8'>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href='lib/default.css' rel='stylesheet'>
  <link class='night' href='lib/night.css' rel='stylesheet' disabled>
  <style></style>
</head>

<body>
  <main>
    <form id='UI'>
      <fieldset name='box'>
        <legend>Theme</legend>
        <button id='theme' type='button'></button>
      </fieldset>
      <p>Click the "Theme" switch to toggle between `disabled` `true` and `false` on `night.css` and `light.css` `
        <link>`s.</p>
    </form>
  </main>
  <script>
    const UI = document.forms.UI;
    const M = document.querySelector('main');
    const L = document.querySelector('.night')

    const switchTheme = e => {
      const clk = e.target;
      if (clk.matches('button')) {
        M.classList.toggle('night');
        L.toggleAttribute('disabled');
      }
      let status = M.className === 'night' ? 'on' : 'off';
      localStorage.setItem('theme', status);
    };

    const loadTheme = e => {
      let cfg = localStorage.getItem('theme');
      if (cfg === 'on') {
        M.classList.add('night');
        L.removeAttribute('disabled');
      } else {
        M.classList.remove('night');
        L.setAttribute('disabled', true);
      }
    };

    UI.addEventListener('click', switchTheme);
    document.addEventListener('DOMContentLoaded', loadTheme);
  </script>
</body>

</html></code>```

Body:
I'm using a Jekyll website, doesn't really matter because this is a static page, I just write it as additional info.

Desired behavior:

I want to load my stylesheet via javascript, so it can depend of a local stored value, let's say dark and light.

I have done a little test of loading it by JS with the following code (which works).

GREEN

  ...
  <link rel="stylesheet" href="/assets/css/{{'light'}}.css">
  ...

This loads the CSS file called "light" as expected.

But now I want to depend of the localStorage, with a variable theme that has light as value. I tried the following:

RED

  ...

  <link rel="stylesheet" href="/assets/css/{{theme}}.css">
  ...

Using global variables doesn't work, it gives me a 404 error as the stylesheet path is /assets/css/.css.

After that I thought that maybe creating an element would do the trick and I created one manually to test it:

RED

...

dark

<link rel="stylesheet" href="/assets/css/{{document.getElementById('theme').innerHTML}}.css">
...

And nope, the path still appears as: /assets/css/.css

Body:
If you change styles on the <body> you get FOUC (Flash Of Unstyled Content). Try using a close equivalent like <main>  and spread it 100% x 100% and <html> and <body> as well, but give them margin and padding of 0 in order to ensure <main> covers them completely.

The [disabled] attribute for the <link> is the best way of toggling them because they are still loaded but inert. Also, in the example there is a function called loadTheme(e) that is loaded on the 'DOMContentLoaded' event which insures that all of the DOM is loaded before hand. The example below will not work because localStorage is blocked on SO. There is a functioning example on Plunker. To test it:

Click the green Preview button.

Another frame should appear on the right. Within the frame is the webpage example click the ☀ button.

It should be in dark mode now. Next, click the refresh ⟳ button located in the mini-toolbar within the frame or press ctrl+enter for Windows OS or ⌥+return for Mac OS.

The page should still be in dark mode.

/* night.css
main {
  background: #000;
  color: #fff;
}
*/

/* default.css */
:root {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
  font: 1ch/1.5 'Segoe UI';
}

body {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
  font-size: 4ch;
}

main {
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  color: #000;
}

form {
  width: 80vw;
  margin: 20px auto;
}

fieldset {
  width: max-content;
  min-height: 25px;
  margin-left: auto;
  padding: 0 1.5px 1.5px;
  border-radius: 8px;
  background: inherit;
  color: inherit;
}

button {
  display: block;
  width: 100%;
  height: 100%;
  border: 0;
  font-size: 4rem;
  text-align: center;
  background: transparent;
  cursor: pointer;
}

#theme::before {
  content: '☀';
}

.night #theme::before {
  content: '';
}

<!DOCTYPE html>
<html>

<head>
  <meta charset='utf-8'>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href='lib/default.css' rel='stylesheet'>
  <link class='night' href='lib/night.css' rel='stylesheet' disabled>
  <style></style>
</head>

<body>
  <main>
    <form id='UI'>
      <fieldset name='box'>
        <legend>Theme</legend>
        <button id='theme' type='button'></button>
      </fieldset>
      <p>Click the "Theme" switch to toggle between `disabled` `true` and `false` on `night.css` and `light.css` `
        <link>`s.</p>
    </form>
  </main>
  <script>
    const UI = document.forms.UI;
    const M = document.querySelector('main');
    const L = document.querySelector('.night')

    const switchTheme = e => {
      const clk = e.target;
      if (clk.matches('button')) {
        M.classList.toggle('night');
        L.toggleAttribute('disabled');
      }
      let status = M.className === 'night' ? 'on' : 'off';
      localStorage.setItem('theme', status);
    };

    const loadTheme = e => {
      let cfg = localStorage.getItem('theme');
      if (cfg === 'on') {
        M.classList.add('night');
        L.removeAttribute('disabled');
      } else {
        M.classList.remove('night');
        L.setAttribute('disabled', true);
      }
    };

    UI.addEventListener('click', switchTheme);
    document.addEventListener('DOMContentLoaded', loadTheme);
  </script>
</body>

</html>


问:
How to avoid HOME in the url an show only the view name?
Is there a way to avoid showing Home in the URL and only the name of the view?

I mean if I want to open the view About which is in the Home controller my URL will be like this:

www.website.com/Home/About

But I would love to show only

www.website.com/About

How can I do this?

答:
You need to update your route configuration for the Home controller. If you're using Attribute-based routing with the following your Route configuration:

```<code>routes.MapMvcAttributeRoutes();
</code>```

You can do the following in your Home controller:

```<code>// GET: Home
[Route("")]
public ActionResult Index()
{
  ViewBag.Title = "Home Page";

  return View();
}

[Route("about")]
public ActionResult About()
{
  ViewBag.Title = "About Page";
  ViewBag.Message = "About Us";

  return View();
}

That will then remove the controller name from the URLs as required.
</code>```

Body:
You need to update your route configuration for the Home controller. If you're using Attribute-based routing with the following your Route configuration:

routes.MapMvcAttributeRoutes();

You can do the following in your Home controller:

// GET: Home
[Route("")]
public ActionResult Index()
{
  ViewBag.Title = "Home Page";

  return View();
}

[Route("about")]
public ActionResult About()
{
  ViewBag.Title = "About Page";
  ViewBag.Message = "About Us";

  return View();
}

That will then remove the controller name from the URLs as required.


答:
It's because you haven't set user_id field in $fillable property. Hence, Laravel ignored provided value for this field when you are using create() method.

However, before using the create method, you will need to specify
either a fillable or guarded property on your model class. These
properties are required because all Eloquent models are protected
against mass assignment vulnerabilities by default.

Related document

```<code> protected $fillable = ['code' , 'user_id'];
</code>```

Title: How do i solve General error: 1364 - Laravel

Body:
It's because you haven't set user_id field in $fillable property. Hence, Laravel ignored provided value for this field when you are using create() method.

However, before using the create method, you will need to specify
either a fillable or guarded property on your model class. These
properties are required because all Eloquent models are protected
against mass assignment vulnerabilities by default.

Related document

 protected $fillable = ['code' , 'user_id'];


问:
Kotlin arrow-kt, functional way to map a collection of either to an either of a collection
I've been using kotlin arrow quite a bit recently, and I've ran into a specific use case that has me stuck.

Let's say I have a collection of some object that I want to convert to another datatype using a convert function. Let's also say that this convert function has an ability to fail-- but instead of throwing an exception, it will just return an Either, where Either.Left() is a failure and Either.Right() is the mapped object. What is the best way to handle this use case? Some sample code below:

```<code>val list: Collection<Object> // some collection
val eithers: List<Either<ConvertError, NewObject>> = list.map { convert(it) } // through some logic, convert each object in the collection

val desired: Either<ConvertError, Collection<NewObject>> = eithers.map { ??? }

fun convert(o: Object) : Either<ConvertError, NewObject> { ... }
</code>```

Essentially, I'd like to call a mapping function on a collection of data, and if any of the mappings respond with a failure, I'd like to have an Either.Left() containing the error. And then otherwise, I'd like the Either.Right() to contain all of the mapped objects.

Any ideas for a clean way to do this? Ideally, I'd like to make a chain of function calls, but have the ability to percolate an error up through the function calls.

答:
How about arrow.core.IterableKt#sequenceEither?

val desired: Either<ConvertError, Collection<NewObject>> = eithers.sequenceEither()
```

Body:
I've been using kotlin arrow quite a bit recently, and I've ran into a specific use case that has me stuck.

Let's say I have a collection of some object that I want to convert to another datatype using a convert function. Let's also say that this convert function has an ability to fail-- but instead of throwing an exception, it will just return an Either, where Either.Left() is a failure and Either.Right() is the mapped object. What is the best way to handle this use case? Some sample code below:

val list: Collection<Object> // some collection
val eithers: List<Either<ConvertError, NewObject>> = list.map { convert(it) } // through some logic, convert each object in the collection

val desired: Either<ConvertError, Collection<NewObject>> = eithers.map { ??? }

fun convert(o: Object) : Either<ConvertError, NewObject> { ... }

Essentially, I'd like to call a mapping function on a collection of data, and if any of the mappings respond with a failure, I'd like to have an Either.Left() containing the error. And then otherwise, I'd like the Either.Right() to contain all of the mapped objects.

Any ideas for a clean way to do this? Ideally, I'd like to make a chain of function calls, but have the ability to percolate an error up through the function calls.


问:
Making a template function mirror its template argument's signature
I have a template function:

template <??? func>
??? wrapper(??? args) {
    // ... Stuff
    return func(args);
}
```
<p>It should have the same signature as the <code>func</code> non-type template parameter.</p>
<p>The closest I've gotten is using <code>auto</code> in the template declaration and then using some form of function traits to deduce the return type, however, this method does not allow for deducing the parameters as a whole.</p>
<p>Ideally,</p>
<pre class="lang-cpp prettyprint-override"><code>template <typename R, typename... Args, R(*func)(Args...)>
R wrapper(Args&&... args); // ...
</code>```

or some other imaginary syntax would A. be allowed and B. deduce R and Args from func.

func must be specified at compile time and the function may not have any additional parameters (I need to take the address of the wrapper).

At this point I feel like my current solution,

template <auto func, typename... Args>
auto wrapper(Args&&... args) {
    return func(std::forward<Args>(args)...);
}
```

cannot be improved, since it appears impossible to generate "pure" variadic template arguments (getting them back after "storing" them anywhere (e.g. a tuple)). Which is sad, because it forces the Args to be provided manually. But of course I'd love to see someone prove me wrong on this!

答:
You can create traits to extract returs type and parameters. issue would be to handle arity only from function declaration.

If you can wrap in a class/functor, it would be possible:

template <auto func> struct wrapper_t;

template <typename Ret, typename ... Ts, Ret (*func)(Ts...)>
struct wrapper_t<func>
{
    Ret operator() (Ts... args) const { return func(std::forward<Ts>(args)...); }
};

// handle ellipsis functions ala printf
template <typename Ret, typename ... Ts, Ret (*func)(Ts..., ...)>
struct wrapper_t<func>
{
    template <typename ...EllipsisArgs>
    Ret operator() (Ts... args, EllipsisArgs&&... ellipisisArgs) const {
        return func(std::forward<Ts>(args)...,
                    std::forward<EllipsisArgs>(ellipisisArgs)...);
    }
};

template <auto func>
constexpr wrapper_t<func> wrapper{};
```

Demo

Body:
I have a template function:

template <??? func>
??? wrapper(??? args) {
    // ... Stuff
    return func(args);
}

It should have the same signature as the func non-type template parameter.

The closest I've gotten is using auto in the template declaration and then using some form of function traits to deduce the return type, however, this method does not allow for deducing the parameters as a whole.

Ideally,

template <typename R, typename... Args, R(*func)(Args...)>
R wrapper(Args&&... args); // ...

or some other imaginary syntax would A. be allowed and B. deduce R and Args from func.

func must be specified at compile time and the function may not have any additional parameters (I need to take the address of the wrapper).

At this point I feel like my current solution,

template <auto func, typename... Args>
auto wrapper(Args&&... args) {
    return func(std::forward<Args>(args)...);
}

cannot be improved, since it appears impossible to generate "pure" variadic template arguments (getting them back after "storing" them anywhere (e.g. a tuple)). Which is sad, because it forces the Args to be provided manually. But of course I'd love to see someone prove me wrong on this!

Body:
You can create traits to extract returs type and parameters. issue would be to handle arity only from function declaration.

If you can wrap in a class/functor, it would be possible:

template <auto func> struct wrapper_t;

template <typename Ret, typename ... Ts, Ret (*func)(Ts...)>
struct wrapper_t<func>
{
    Ret operator() (Ts... args) const { return func(std::forward<Ts>(args)...); }
};

// handle ellipsis functions ala printf
template <typename Ret, typename ... Ts, Ret (*func)(Ts..., ...)>
struct wrapper_t<func>
{
    template <typename ...EllipsisArgs>
    Ret operator() (Ts... args, EllipsisArgs&&... ellipisisArgs) const {
        return func(std::forward<Ts>(args)...,
                    std::forward<EllipsisArgs>(ellipisisArgs)...);
    }
};

template <auto func>
constexpr wrapper_t<func> wrapper{};

Demo


问:
Update timestamps every 30 seconds using setInterval()
I have a list of posts like so:

```<code><ul>
    <li>
       <p class="post" id="432">This is a post</p>
       <p class="timestamp">5 minutes ago</p>
    </li>
    <li>
       <p class="post" id="589">This is another post on the site</p>
       <p class="timestamp">1 hour ago</p>
    </li>
</ul>
</code>```

I want to update the timestamp every 30 seconds (much like facebook timestamps) using setInterval().

```<code>function update_timestamps(){

    $('.timestamp').ajax({
        type    : 'POST',
        url     : '/ajax/refresh_timestamp',
        data    : { 'post_id' : $(this).closest('li').find('p.post').attr('id') },
        success : function(data){
            $(this).html(data);
        }
    });

}

setInterval(update_timestamps(), 30000);
</code>```

Obviously something is wrong with my .ajax() function, or maybe I shouldn't use ajax() at all?

答:
If you want to show only "time ago" why use ajax at all?

Just use this plugin, timeago

Body:
I have a list of posts like so:

This is a post

5 minutes ago

This is another post on the site

1 hour ago

I want to update the timestamp every 30 seconds (much like facebook timestamps) using setInterval().

function update_timestamps(){

    $('.timestamp').ajax({
        type    : 'POST',
        url     : '/ajax/refresh_timestamp',
        data    : { 'post_id' : $(this).closest('li').find('p.post').attr('id') },
        success : function(data){
            $(this).html(data);
        }
    });

}

setInterval(update_timestamps(), 30000);

Obviously something is wrong with my .ajax() function, or maybe I shouldn't use ajax() at all?


问:
Is enum E { a } e = E(2); valid?
A recent and interesting C language-lawyer question asked:

Is enum { a } e = 1; valid?

This Q&A asks the same question for the similar cases for C++(*): are these valid?

```<code>enum EA { a } ea = EA(2);               // #1
enum EB { b } eb = static_cast<EB>(2);  // #2
</code>```

I've already noted that the variation enum EC { c } ec = EC{2}; is rejected at compile time ("cannot initialize a value of type 'E' with an rvalue of type 'int'), whereas #1 and #2 are accepted, ruling out ill-formed but not ill-formed NDR and UB for #1 and #2.

(*) Posted here as a self-answered Q&A after being prompted to break out overly eager and misplaced C++-focused answer to the original C language-lawyer question.

答:
Unspecified behavior until C++14; undefined behavior since C++17

Whilst the corresponding construct is legal in C—as answered thoroughly in the linked-to C language-lawyer Q&A—due to the stronger "compatible type" requirement, the same does not hold for C++, where "C style" unscoped enums with no fixed underlying type have subtle differences from C.

First of all, we may note that the original C example

```<code>enum E { a } e = 1;
</code>```

is not legal in C++ as C++ does not allow implicit conversion from an integer type to an unscoped enum with no explicit underlying type, thus the slightly modifyed examples of the OP

```<code>// Syntactically legal -> compiles.
enum EA { a } ea = EA(2);               // #1
enum EB { b } eb = static_cast<EB>(2);  // #2
</code>```

As per [dcl.enum]/7,

For an enumeration whose underlying type is fixed, the values of the enumeration are the values of the underlying type. Otherwise, the values of the enumeration are the values representable by a hypothetical integer type with minimal width M such that all enumerators can be represented. The width of the smallest bit-field large enough to hold all the values of the enumeration type is M. [...]

the underlying type of EA and EB is implementation-defined.

As per [expr.static.cast]/10:

A value of integral or enumeration type can be explicitly converted to a complete enumeration type. [...] If the enumeration type does not have a fixed underlying type, the value is unchanged if the original value is within the range of the enumeration values ([dcl.enum]), and otherwise, the behavior is undefined. [...]

#2 above may (depending on the implementation-defined underlying type of the E) lead to

undefined behavior in C++17 and forward, via the resolution of CWG 1766, and

unspecified behavior in C++14 and earlier.

Conceptually, the conversion could possibly cause signed integer overflow (which is UB).

Case #1 is, as per [expr.type.conv], also an explicit (type) conversion, and the same argument as for #2 applies also for this functional cast case.

Title: Is enum E { a } e = E(2); valid?

Body:
A recent and interesting C language-lawyer question asked:

Is enum { a } e = 1; valid?

This Q&A asks the same question for the similar cases for C++(*): are these valid?

enum EA { a } ea = EA(2);               // #1
enum EB { b } eb = static_cast<EB>(2);  // #2

I've already noted that the variation enum EC { c } ec = EC{2}; is rejected at compile time ("cannot initialize a value of type 'E' with an rvalue of type 'int'), whereas #1 and #2 are accepted, ruling out ill-formed but not ill-formed NDR and UB for #1 and #2.

(*) Posted here as a self-answered Q&A after being prompted to break out overly eager and misplaced C++-focused answer to the original C language-lawyer question.

Body:
Unspecified behavior until C++14; undefined behavior since C++17

Whilst the corresponding construct is legal in C—as answered thoroughly in the linked-to C language-lawyer Q&A—due to the stronger "compatible type" requirement, the same does not hold for C++, where "C style" unscoped enums with no fixed underlying type have subtle differences from C.

First of all, we may note that the original C example

enum E { a } e = 1;

is not legal in C++ as C++ does not allow implicit conversion from an integer type to an unscoped enum with no explicit underlying type, thus the slightly modifyed examples of the OP

// Syntactically legal -> compiles.
enum EA { a } ea = EA(2);               // #1
enum EB { b } eb = static_cast<EB>(2);  // #2

As per [dcl.enum]/7,

For an enumeration whose underlying type is fixed, the values of the enumeration are the values of the underlying type. Otherwise, the values of the enumeration are the values representable by a hypothetical integer type with minimal width M such that all enumerators can be represented. The width of the smallest bit-field large enough to hold all the values of the enumeration type is M. [...]

the underlying type of EA and EB is implementation-defined.

As per [expr.static.cast]/10:

A value of integral or enumeration type can be explicitly converted to a complete enumeration type. [...] If the enumeration type does not have a fixed underlying type, the value is unchanged if the original value is within the range of the enumeration values ([dcl.enum]), and otherwise, the behavior is undefined. [...]

#2 above may (depending on the implementation-defined underlying type of the E) lead to

undefined behavior in C++17 and forward, via the resolution of CWG 1766, and

unspecified behavior in C++14 and earlier.

Conceptually, the conversion could possibly cause signed integer overflow (which is UB).

Case #1 is, as per [expr.type.conv], also an explicit (type) conversion, and the same argument as for #2 applies also for this functional cast case.


问:
Write more lines TMemo (Delphi XE)
In a TMemo I must report information on multiple lines:

```<code>procedure TForm1.FormCreate(Sender: TObject);
var
  ids: TidIpWatch;
  Speed: Double;
begin
 ids := TidIpWatch.Create;
 Speed := GetCPUSpeed;
 Memo1.Text := 'IP:' + (ids.LocalIP) + (Tipo_cpu);
 Memo1.Text := 'CPU: ' + (Tipo_cpu) + ' ' + Format('%f', [Speed]);
 ids.Free;
 end;
</code>```

But I don't know how to implement the TMemo function.

答:
Use TMemo.Lines.Add to append a new line.

```<code>procedure TForm1.FormCreate(Sender: TObject);
var
  ids: TidIpWatch;
  Speed: Double;
begin
  ids := TidIpWatch.Create;
  try
    Speed := GetCPUSpeed;
    Memo1.Lines.BeginUpdate();
    try
      Memo1.Lines.Add('IP:' + (ids.LocalIP) + (Tipo_cpu));
      Memo1.Lines.Add('CPU: ' + (Tipo_cpu) + ' ' + Format('%f', [Speed]));
    finally
      Memo1.Lines.EndUpdate();
    end;
  finally
    ids.Free;
  end
 end;
</code>```

Also remember to use try-finally blocks to avoid memory leaks

Title: Write more lines TMemo (Delphi XE)

Body:
In a TMemo I must report information on multiple lines:

procedure TForm1.FormCreate(Sender: TObject);
var
  ids: TidIpWatch;
  Speed: Double;
begin
 ids := TidIpWatch.Create;
 Speed := GetCPUSpeed;
 Memo1.Text := 'IP:' + (ids.LocalIP) + (Tipo_cpu);
 Memo1.Text := 'CPU: ' + (Tipo_cpu) + ' ' + Format('%f', [Speed]);
 ids.Free;
 end;

But I don't know how to implement the TMemo function.

Body:
Use TMemo.Lines.Add to append a new line.

procedure TForm1.FormCreate(Sender: TObject);
var
  ids: TidIpWatch;
  Speed: Double;
begin
  ids := TidIpWatch.Create;
  try
    Speed := GetCPUSpeed;
    Memo1.Lines.BeginUpdate();
    try
      Memo1.Lines.Add('IP:' + (ids.LocalIP) + (Tipo_cpu));
      Memo1.Lines.Add('CPU: ' + (Tipo_cpu) + ' ' + Format('%f', [Speed]));
    finally
      Memo1.Lines.EndUpdate();
    end;
  finally
    ids.Free;
  end
 end;

Also remember to use try-finally blocks to avoid memory leaks


问:
Countdown Timer in Vanilla Javascript without using a function
I have a project where I need to do a countdown timer, However no function can be used. I know that this can be done with a setInterval, however, most of the documentation I have found shows a function being used in conjunction. W3schools has a great example, however, it used a function. I know how I would do it with

I have already written some code, and was able to display the minutes and seconds, however, cannot get it to actually count down. is there a way to do this without a function?

```<code>const timeSpan = document.getElementById('timer');

// Get Time Now
var timeMinutes = 10;
var currentTime = Date.parse(new Date());
var deadline = new Date(currentTime + timeMinutes * 60 * 1000);
var distance = deadline - currentTime;
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);

timeSpan.innerHTML = minutes + 's' + seconds;
</code>```

This shows the minutes and seconds, but without the setInterval or setTimeOut it wont count down like a normal countdown timer. For the project it needs to count down from ten minutes and at the end alert the user that is is expired and that they will need to refresh the page.

答:
```<code><script>
var timer   = (mins) => {

    const timeSpan  = document.getElementById('timer');
    const now       = new Date().getTime();
    const deadline  = mins * 60 * 1000 + now;

    setInterval(() => {
        var currentTime = new Date().getTime();
        var distance = deadline - currentTime;
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);

        timeSpan.innerHTML = minutes + ' min. ' + seconds + ' s.';

        if (minutes <=0 && seconds <=0) {
                alert('Time is over');
                return false;
        }

    }, 1000);
 }

 timer(10);

</script>
<span id="timer"></span>
</code>```

Body:
I have a project where I need to do a countdown timer, However no function can be used. I know that this can be done with a setInterval, however, most of the documentation I have found shows a function being used in conjunction. W3schools has a great example, however, it used a function. I know how I would do it with

I have already written some code, and was able to display the minutes and seconds, however, cannot get it to actually count down. is there a way to do this without a function?

const timeSpan = document.getElementById('timer');

// Get Time Now
var timeMinutes = 10;
var currentTime = Date.parse(new Date());
var deadline = new Date(currentTime + timeMinutes * 60 * 1000);
var distance = deadline - currentTime;
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);

timeSpan.innerHTML = minutes + 's' + seconds;

This shows the minutes and seconds, but without the setInterval or setTimeOut it wont count down like a normal countdown timer. For the project it needs to count down from ten minutes and at the end alert the user that is is expired and that they will need to refresh the page.


问:
How to read both xls and xlsx with Apache Poi library?
I have an app that reads from an excel. The problem is that I only can read xlsx files. I cant read xls files. This is my code:</p>

```<code>FileInputStream file = new FileInputStream(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+"/"+nomeExcel));
                        HSSFWorkbook workbook = new HSSFWorkbook(file);
                        HSSFSheet sheet = workbook.getSheetAt(0);

                        int rowCtr = 34;
                        Row myRow = sheet.getRow(rowCtr++);
                        while (myRow != null) {
                            Cell nif = myRow.getCell(0);
                            Cell marcaexploracao = myRow.getCell(1);
                            Cell numerochip = myRow.getCell(2);
                            Cell marcaauricular = myRow.getCell(3);
                            Cell datanascimento = myRow.getCell(4);

                            bd.addAnimais(numerochip.toString().replace("\u00a0",""),marcaexploracao.toString().trim(),marcaauricular.toString(),datanascimento.toString(),nif.toString(),0,"","","","",0);
                            myRow = sheet.getRow(rowCtr++);
                        }

                    }catch (Exception e){e.printStackTrace(); }

                    Toast.makeText(getApplicationContext(),"Excel importado",Toast.LENGTH_SHORT).show();

                }
            });
</code>```

答:
For reading xlsx file

Workbook workbook = new XSSFWorkbook(inputStream);

For reading xls file (< 2007)

Workbook workbook = new HSSFWorkbook(inputStream);

No other changes required.

Body:
I have an app that reads from an excel. The problem is that I only can read xlsx files. I cant read xls files. This is my code:

FileInputStream file = new FileInputStream(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+"/"+nomeExcel));
                        HSSFWorkbook workbook = new HSSFWorkbook(file);
                        HSSFSheet sheet = workbook.getSheetAt(0);

                        int rowCtr = 34;
                        Row myRow = sheet.getRow(rowCtr++);
                        while (myRow != null) {
                            Cell nif = myRow.getCell(0);
                            Cell marcaexploracao = myRow.getCell(1);
                            Cell numerochip = myRow.getCell(2);
                            Cell marcaauricular = myRow.getCell(3);
                            Cell datanascimento = myRow.getCell(4);

                            bd.addAnimais(numerochip.toString().replace("\u00a0",""),marcaexploracao.toString().trim(),marcaauricular.toString(),datanascimento.toString(),nif.toString(),0,"","","","",0);
                            myRow = sheet.getRow(rowCtr++);
                        }

                    }catch (Exception e){e.printStackTrace(); }

                    Toast.makeText(getApplicationContext(),"Excel importado",Toast.LENGTH_SHORT).show();

                }
            });


问:
How to properly use Hilt with ViewModel using @HiltViewModel?
I have a problem with Hilt and ViewModel. I'm getting RunTimeException:

```<code>MainViewModel> has no zero argument constructor
</code>```

I spent hours to find what is wrong...

Here are sources from my code:

AppModule:

```<code>@Module
@InstallIn(SingletonComponent::class)
object AppModule {

    @Singleton
    @Provides
    fun provideCurrencyApi(): CurrencyApi = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build()
        .create(CurrencyApi::class.java)

    @Singleton
    @Provides
    fun provideMainRepository(api: CurrencyApi): MainRepository = DefaultMainRepository(api)

    @Singleton
    @Provides
    fun provideDispatchers(): DispatcherProvider = object : DispatcherProvider {
        override val main: CoroutineDispatcher
            get() = Dispatchers.Main
        override val io: CoroutineDispatcher
            get() = Dispatchers.IO
        override val default: CoroutineDispatcher
            get() = Dispatchers.Default
        override val unconfined: CoroutineDispatcher
            get() = Dispatchers.Unconfined
    }
}
</code>```

MainActivity:

```<code>@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    private val viewModel: MainViewModel by viewModels()
</code>```

MainViewModel:

```<code>@HiltViewModel
class MainViewModel @Inject constructor(
    private val repository: MainRepository,
    private val dispatchers: DispatcherProvider
) : ViewModel() {
</code>```

MainRepository

```<code>class DefaultMainRepository @Inject constructor(
    private val api: CurrencyApi
) : MainRepository {
</code>```

Hee are Gradle dependencies:

```<code>dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'

    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'com.squareup.okhttp3:okhttp:4.9.0'

    implementation "androidx.activity:activity-ktx:1.4.0"

    implementation 'com.google.dagger:hilt-android:2.40.5'
    kapt 'com.google.dagger:hilt-compiler:2.40.5'
    implementation 'androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03'
    kapt'androidx.hilt:hilt-compiler:1.0.0'

    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0'
    implementation 'androidx.navigation:navigation-fragment-ktx:2.4.0'

    androidTestImplementation  'com.google.dagger:hilt-android-testing:2.40.5'
    kaptAndroidTest 'com.google.dagger:hilt-compiler:2.40.5'
    testImplementation 'com.google.dagger:hilt-android-testing:2.40.5'
    kaptTest 'com.google.dagger:hilt-compiler:2.40.5'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
</code>```

Application:

```<code>@HiltAndroidApp
class CurrencyApplication: Application()
</code>```

Manifest:

```<code>    <application
        android:name=".CurrencyApplication"
</code>```

Im trying to find solution everywhere like here: possible reason

I will be grateful for any help

答:
You have not mentioned here so i think you forgot to add @HiltAndroidApp in your app.

```<code>@HiltAndroidApp
class MyOwnApplication : Application() {

}
</code>```

and then in your manifest file add android:name=".MyOwnApplication" inside your application tag.

Body:
I have a problem with Hilt and ViewModel. I'm getting RunTimeException:

MainViewModel> has no zero argument constructor

I spent hours to find what is wrong...

Here are sources from my code:

AppModule:

@Module
@InstallIn(SingletonComponent::class)
object AppModule {

    @Singleton
    @Provides
    fun provideCurrencyApi(): CurrencyApi = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build()
        .create(CurrencyApi::class.java)

    @Singleton
    @Provides
    fun provideMainRepository(api: CurrencyApi): MainRepository = DefaultMainRepository(api)

    @Singleton
    @Provides
    fun provideDispatchers(): DispatcherProvider = object : DispatcherProvider {
        override val main: CoroutineDispatcher
            get() = Dispatchers.Main
        override val io: CoroutineDispatcher
            get() = Dispatchers.IO
        override val default: CoroutineDispatcher
            get() = Dispatchers.Default
        override val unconfined: CoroutineDispatcher
            get() = Dispatchers.Unconfined
    }
}

MainActivity:

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    private val viewModel: MainViewModel by viewModels()

MainViewModel:

@HiltViewModel
class MainViewModel @Inject constructor(
    private val repository: MainRepository,
    private val dispatchers: DispatcherProvider
) : ViewModel() {

MainRepository

class DefaultMainRepository @Inject constructor(
    private val api: CurrencyApi
) : MainRepository {

Hee are Gradle dependencies:

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'

    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'com.squareup.okhttp3:okhttp:4.9.0'

    implementation "androidx.activity:activity-ktx:1.4.0"

    implementation 'com.google.dagger:hilt-android:2.40.5'
    kapt 'com.google.dagger:hilt-compiler:2.40.5'
    implementation 'androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03'
    kapt'androidx.hilt:hilt-compiler:1.0.0'

    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0'
    implementation 'androidx.navigation:navigation-fragment-ktx:2.4.0'

    androidTestImplementation  'com.google.dagger:hilt-android-testing:2.40.5'
    kaptAndroidTest 'com.google.dagger:hilt-compiler:2.40.5'
    testImplementation 'com.google.dagger:hilt-android-testing:2.40.5'
    kaptTest 'com.google.dagger:hilt-compiler:2.40.5'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

Application:

@HiltAndroidApp
class CurrencyApplication: Application()

Manifest:

    <application
        android:name=".CurrencyApplication"

Im trying to find solution everywhere like here: possible reason

I will be grateful for any help

Body:
You have not mentioned here so i think you forgot to add @HiltAndroidApp in your app.

@HiltAndroidApp
class MyOwnApplication : Application() {

}

and then in your manifest file add android:name=".MyOwnApplication" inside your application tag.


问:
How to collect source files with CMake without globbing?
The CMake documentation explicitly states that file(GLOB ...) is not
recommended to collect source files for a build, but it doesn't
mention what the recommended method actually is.

Specifying every source file manually sounds a little bit too manually
to me. So, what is the right method to collect source files, if not
file(GLOB ...)?

答:
Following douyw's answer, thank you for your answer.

Not a Cmake expert, don't want to be one, I spent a fxxking 3 hours trying to deal with GLOB(disabled) and aux_source_directory(Not even close to GLOB), and douyw save my life.

I add the recursive file walking, and it's working in my project:

Firstly, install the cogapp python module (python -m pip install cogapp)

```<code>set(SRC_FILES "")

# [[[cog
#   import cog, os
#   for root, _, files in os.walk(".", topdown=False):
#       for f in files:
#           if not "_unittest" in f: continue
#           if not f.endswith(".cpp"): continue
#           cog.outl('SET(SRC_FILES ${SRC_FILES} "%s")' % os.path.join(root, f).replace('\\', '/'))
# ]]]
# [[[end]]]
</code>```

run: python -m cogapp -r CMakeLists.txt

The upper lines add all "*_unittest.cpp" to the list

You can change the middle lines to make your own rule, just plain python.
Using regex is better, but simple string searching can do the job on the above situation.

Notice the last line, it needs to replace // to change to the usable universal separator. You may generate your CMakeList.txt in windows.

You may replace SRC_FILES with whatever you want.

The python command may be run under Jenkins/TeamCity, triggered by svn/git commit. Then we can automatically add new files.

Body:
Following douyw's answer, thank you for your answer.

Not a Cmake expert, don't want to be one, I spent a fxxking 3 hours trying to deal with GLOB(disabled) and aux_source_directory(Not even close to GLOB), and douyw save my life.

I add the recursive file walking, and it's working in my project:

Firstly, install the cogapp python module (python -m pip install cogapp)

set(SRC_FILES "")

# [[[cog
#   import cog, os
#   for root, _, files in os.walk(".", topdown=False):
#       for f in files:
#           if not "_unittest" in f: continue
#           if not f.endswith(".cpp"): continue
#           cog.outl('SET(SRC_FILES ${SRC_FILES} "%s")' % os.path.join(root, f).replace('\\', '/'))
# ]]]
# [[[end]]]

run: python -m cogapp -r CMakeLists.txt

The upper lines add all "*_unittest.cpp" to the list

You can change the middle lines to make your own rule, just plain python.
Using regex is better, but simple string searching can do the job on the above situation.

Notice the last line, it needs to replace // to change to the usable universal separator. You may generate your CMakeList.txt in windows.

You may replace SRC_FILES with whatever you want.

The python command may be run under Jenkins/TeamCity, triggered by svn/git commit. Then we can automatically add new files.


问:
indexing keys AND related columns or just keys to increase speed in mysql
So if I have an sql query like these:

```<code>SELECT title, document FROM docs WHERE id = "1" and type = "2"

SELECT title FROM docs WHERE id = "1"

SELECT title FROM docs WHERE member = "foo"
</code>```

to maximize speed for the first one i. would I have to index only the keys (id and type together? seperate?) ii. would I also have to index title and document (together,separate)

same type of questions apply for the second one, and for the third query i. would I have to index only member?
IM just trying to understand mysql retrieval and indexing.

答:
You need 2 indexes

```<code>(id, type, title)
(member, title)
</code>```

id, type makes id redundant

adding title makes the index covering

Body:
So if I have an sql query like these:

SELECT title, document FROM docs WHERE id = "1" and type = "2"

SELECT title FROM docs WHERE id = "1"

SELECT title FROM docs WHERE member = "foo"

to maximize speed for the first one i. would I have to index only the keys (id and type together? seperate?) ii. would I also have to index title and document (together,separate)

same type of questions apply for the second one, and for the third query i. would I have to index only member?
IM just trying to understand mysql retrieval and indexing.

Body:
You need 2 indexes

(id, type, title)
(member, title)

id, type makes id redundant

adding title makes the index covering


问:
Jenkins server is running slow
My Jenkins server is so slow. Java takes 120% or CPU. How can I give Jenkins more memory access.

Of what steps can I take to improve the load time for Jenkins

答:
Manage Jenkins -> Configure System - > Robot Framework
Deselect checkbox as -> [Display "Robot Results" column in the job list view ]

Please look here for detailed screenshot

Title: Jenkins server is running slow


问:
Root password inside a Docker container
I'm using a Docker image which was built using the USER command to use a non-root user called dev.
Inside a container, I'm "dev", but I want to edit the /etc/hosts file.

So I need to be root. I'm trying the su command, but I'm asked to enter the root password.

What's the default root user's password inside a Docker container?

答:
Setting a fixed root password in a docker container can compromise systems, and so shouldn't be used.  Instead you might use:

```<code> docker exec -itu 0 CONTAINER_ID bash
</code>```

whenever you want root access to the container, while the container is up and running.

The above command assumes you want to run bash as your shell.
I don't use MS Windows, but I'd guess that you might try CMD or CMD.EXE instead of bash if you're on a MS Windows machine.

Title: Root password inside a Docker container

Body:
Setting a fixed root password in a docker container can compromise systems, and so shouldn't be used.  Instead you might use:

 docker exec -itu 0 CONTAINER_ID bash

whenever you want root access to the container, while the container is up and running.

The above command assumes you want to run bash as your shell.
I don't use MS Windows, but I'd guess that you might try CMD or CMD.EXE instead of bash if you're on a MS Windows machine.


问:
I am having Issues counting values in a row with separators using SQL
I am new to snowflake and trying the count the number of values in a row with separators using SQL. I am not sure how to go about it. I've googled solutions for this but have not been able to find one.

table name: Lee_tab

user
names

id01
Jon;karl;lee;

id02
Abi;jackson;

id03
don;

id04

what I want to achieve

user
names
name_count

id01
Jon;karl;lee;
3

id02
Abi;jackson;
2

id03
don;
1

id04

0

答:
Here is three solutions using REGEXP_COUNT, SPLIT, ARRAY_SIZE, STRTOK_TO_ARRAY (I would use the REGEXP_COUNT one):

```<code>SELECT
    column1,
    column2,
    regexp_count(column2, ';')+1 as solution_1,
    ARRAY_SIZE(split(column2, ';')) as solution_2,
    ARRAY_SIZE(strtok_to_array(column2, ';')) as solution_3
FROM VALUES
    ('id01','Jon;karl;lee'),
    ('id02','Abi;jackson'),
    ('id03','don');
</code>```

which gives

COLUMN1
COLUMN2
SOLUTION_1
SOLUTION_2
SOLUTION_3

id01
Jon;karl;lee
3
3
3

id02
Abi;jackson
2
2
2

id03
don
1
1
1

Body:
Here is three solutions using REGEXP_COUNT, SPLIT, ARRAY_SIZE, STRTOK_TO_ARRAY (I would use the REGEXP_COUNT one):

SELECT
    column1,
    column2,
    regexp_count(column2, ';')+1 as solution_1,
    ARRAY_SIZE(split(column2, ';')) as solution_2,
    ARRAY_SIZE(strtok_to_array(column2, ';')) as solution_3
FROM VALUES
    ('id01','Jon;karl;lee'),
    ('id02','Abi;jackson'),
    ('id03','don');

which gives

COLUMN1
COLUMN2
SOLUTION_1
SOLUTION_2
SOLUTION_3

id01
Jon;karl;lee
3
3
3

id02
Abi;jackson
2
2
2

id03
don
1
1
1


问:
NSScrollView doesn't work xcode 4
I made an nsscrollview in the interface builder of xcode 4 and i put buttons inside of it's view. The scrollview is clipping the content of the view instead of scrolling it. How come it won't scroll?</p>

答:
You'll need to:

Make sure the buttons are inside the scroll view's content view.

Make sure that the content view is large enough that it'll scroll. If it's the same size as the scroll view, or smaller, it won't scroll. A scroll view is meant to display a portion of a larger view; if the whole view is already displayed, there's no reason to do any scrolling.

Title: NSScrollView doesn't work xcode 4


问:
save as dataframe python
I am really new in python, so I am doing a consultd and I want that the results be save  like dataframe instead of be just print in the terminal. Here is my code:

```<code>service = Service("https://www.mousemine.org/mousemine/service")
query = service.new_query("Gene")
query.add_view(
    "primaryIdentifier", "symbol", "organism.name",
    "homologues.homologue.primaryIdentifier", "homologues.homologue.symbol",
    "homologues.homologue.organism.name", "homologues.type",
    "homologues.dataSets.name"
)
query.add_constraint("homologues.type", "NONE OF", ["horizontal gene transfer", "least diverged horizontal gene transfer"], code = "B")
query.add_constraint("Gene", "LOOKUP", "ENSMUSG00000026981,ENSMUSG00000068039,ENSMUSG00000035007,ENSMUSG00000022972,", "M. musculus", code = "A")
query.add_constraint("homologues.homologue.organism.name", "=", "Homo sapiens", code = "C")
query.add_constraint("homologues.dataSets.name", "=", "Mouse/Human Orthologies from MGI", code = "D")

   for row in query.rows():
    print(row["primaryIdentifier"], row["symbol"], row["organism.name"], \
        row["homologues.homologue.primaryIdentifier"],
        row["homologues.homologue.symbol"], \
        row["homologues.homologue.organism.name"], row["homologues.type"], \
        row["homologues.dataSets.name"])
</code>```

And this is the result that I get it

MGI:1915251 Cfap298 Mus musculus 56683 CFAP298 Homo sapiens orthologue Mouse/Human Orthologies from MGI
MGI:2144506 Rundc1 Mus musculus 146923 RUNDC1 Homo sapiens orthologue Mouse/Human Orthologies from MGI
MGI:96547 Il1rn Mus musculus 3557 IL1RN Homo sapiens orthologue Mouse/Human Orthologies from MGI
MGI:98535 Tcp1 Mus musculus 6950 TCP1 Homo sapiens orthologue Mouse/Human Orthologies from MGI

And it is perfectly ok, but I need it in a dataframe. And if I can the consult using a table with all the ID and not have to writing one by one (because there are 14000) that will be amazing.

答: Pandas would help you.https://pandas.pydata.org. Feel free to ask questions if you stuck with something.</p>

Title: save as dataframe python

Body:
I am really new in python, so I am doing a consultd and I want that the results be save  like dataframe instead of be just print in the terminal. Here is my code:

service = Service("https://www.mousemine.org/mousemine/service")
query = service.new_query("Gene")
query.add_view(
    "primaryIdentifier", "symbol", "organism.name",
    "homologues.homologue.primaryIdentifier", "homologues.homologue.symbol",
    "homologues.homologue.organism.name", "homologues.type",
    "homologues.dataSets.name"
)
query.add_constraint("homologues.type", "NONE OF", ["horizontal gene transfer", "least diverged horizontal gene transfer"], code = "B")
query.add_constraint("Gene", "LOOKUP", "ENSMUSG00000026981,ENSMUSG00000068039,ENSMUSG00000035007,ENSMUSG00000022972,", "M. musculus", code = "A")
query.add_constraint("homologues.homologue.organism.name", "=", "Homo sapiens", code = "C")
query.add_constraint("homologues.dataSets.name", "=", "Mouse/Human Orthologies from MGI", code = "D")

   for row in query.rows():
    print(row["primaryIdentifier"], row["symbol"], row["organism.name"], \
        row["homologues.homologue.primaryIdentifier"],
        row["homologues.homologue.symbol"], \
        row["homologues.homologue.organism.name"], row["homologues.type"], \
        row["homologues.dataSets.name"])

And this is the result that I get it

MGI:1915251 Cfap298 Mus musculus 56683 CFAP298 Homo sapiens orthologue Mouse/Human Orthologies from MGI
MGI:2144506 Rundc1 Mus musculus 146923 RUNDC1 Homo sapiens orthologue Mouse/Human Orthologies from MGI
MGI:96547 Il1rn Mus musculus 3557 IL1RN Homo sapiens orthologue Mouse/Human Orthologies from MGI
MGI:98535 Tcp1 Mus musculus 6950 TCP1 Homo sapiens orthologue Mouse/Human Orthologies from MGI

And it is perfectly ok, but I need it in a dataframe. And if I can the consult using a table with all the ID and not have to writing one by one (because there are 14000) that will be amazing.


问:
How to split a string into individual elements in javascript
I have a need to split a string in javascript to individual components. Let me go through the example of the requirement I'm having.

This is the string I'm having:

```<code>"[InsertDelta, position: 63, lines: [return {]]"
</code>```

I need to split the above string into three components as below:

```<code>InsertDela
position: 63
lines: [return {]
</code>```

Is there any way to separate the strings like this in javascript?

答:
You can use split to split the string at "," and then use for each to iterate through the items.

let y = "[InsertDelta, position: 63, lines: [return {]]";
let x = y.split(",");
x.forEach(item => console.log(item.replace(/\[?\]?/g, "")));```

Body:
I have a need to split a string in javascript to individual components. Let me go through the example of the requirement I'm having.

This is the string I'm having:

"[InsertDelta, position: 63, lines: [return {]]"

I need to split the above string into three components as below:

InsertDela
position: 63
lines: [return {]

Is there any way to separate the strings like this in javascript?


问:
Undefined property on an object
I have a Typescript project in which I am reassigning variables depending on the value that the object contains.

What I am trying to do is define a variable from a property of the object, instead, if this property does not exist, a default value is established.

This is my Object:

```<code>interface InsParams {
  host?: string,
  country?: string,
  pageLimit?: number,
  pageOffset?: number,
  pageToken?: string
}

let dataObj: InsParams;
</code>```

This is the variable I'm creating:

```<code>let limit: number = dataObj.pageLimit ? dataObj.pageLimit : 1000
</code>```

This is the error it shows:

```<code>Error: Cannot read properties of undefined
</code>```

My problem: I need if the property does not exist to assign another value to the limit variable, but it shows an error.

答:
Your issue comes from dataObj being potentially undefined. In this case, you can use optional chaining + null coalescing operator:

```<code>let limit = dataObj?.pageLimit ?? 1000;
</code>```

Title: Undefined property on an object

Body:
I have a Typescript project in which I am reassigning variables depending on the value that the object contains.

What I am trying to do is define a variable from a property of the object, instead, if this property does not exist, a default value is established.

This is my Object:

interface InsParams {
  host?: string,
  country?: string,
  pageLimit?: number,
  pageOffset?: number,
  pageToken?: string
}

let dataObj: InsParams;

This is the variable I'm creating:

let limit: number = dataObj.pageLimit ? dataObj.pageLimit : 1000

This is the error it shows:

Error: Cannot read properties of undefined

My problem: I need if the property does not exist to assign another value to the limit variable, but it shows an error.

Body:
Your issue comes from dataObj being potentially undefined. In this case, you can use optional chaining + null coalescing operator:

let limit = dataObj?.pageLimit ?? 1000;


问:
JPA 2 Criteria Fetch Path Navigation
With JPA 2 Criteria Join method I can do the following:

```<code>    //Join Example (default inner join)
    int age = 25;
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Team> c = cb.createQuery(Team.class);
    Root<Team> t = c.from(Team.class);
    Join<Team, Player> p = t.join(Team_.players);
    c.select(t).where(cb.equal(p.get(Player_.age), age));
    TypedQuery<Team> q = entityManager.createQuery(c);
    List<Team> result = q.getResultList();
</code>```

How can I do the same with fetch method, I expected that Fetch interface had get method for path navigation but it doesn't:

```<code>    //Fetch Join Example

    int age = 25;
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Team> cq = cb.createQuery(Team.class);
    Root<Team> t = cq.from(Team.class);
    Fetch<Team,Player> p = t.fetch(Team_.players);
    cq.where(cb.equal(p.get(Player_.age), age)); //This leads to compilation error there is no such method get in interface Fetch
    TypedQuery<Team> q = entityManager.createQuery(cq);
    List<Team> result = q.getResultList();
</code>```

According to Hiberante Documentation fetch returns a Join object which is wrong.
http://docs.jboss.org/hibernate/stable/entitymanager/reference/en/html/querycriteria.html#querycriteria-from-fetch

答: I updated the Hibernate Version to "5.6.5.Final" and I think the problem is resolved.</p>

ContentLicense: CC BY-SA 2.5

Title: JPA 2 Criteria Fetch Path Navigation

Body:
With JPA 2 Criteria Join method I can do the following:

    //Join Example (default inner join)
    int age = 25;
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Team> c = cb.createQuery(Team.class);
    Root<Team> t = c.from(Team.class);
    Join<Team, Player> p = t.join(Team_.players);
    c.select(t).where(cb.equal(p.get(Player_.age), age));
    TypedQuery<Team> q = entityManager.createQuery(c);
    List<Team> result = q.getResultList();

How can I do the same with fetch method, I expected that Fetch interface had get method for path navigation but it doesn't:

    //Fetch Join Example

    int age = 25;
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Team> cq = cb.createQuery(Team.class);
    Root<Team> t = cq.from(Team.class);
    Fetch<Team,Player> p = t.fetch(Team_.players);
    cq.where(cb.equal(p.get(Player_.age), age)); //This leads to compilation error there is no such method get in interface Fetch
    TypedQuery<Team> q = entityManager.createQuery(cq);
    List<Team> result = q.getResultList();

According to Hiberante Documentation fetch returns a Join object which is wrong.
http://docs.jboss.org/hibernate/stable/entitymanager/reference/en/html/querycriteria.html#querycriteria-from-fetch


问:
Understanding C runtimes
I am learning C Language and I have a question.
If I compile and make an executable for C program in say BorlandC on one Windows PC and then transfer this file to another Windows PC which does not have the compiler, how does it run where there is no C runtime and how does the memory management work?</p>

答:
For C language, there is often a shared library called "libc" that should be shipped with your OS. Memory management is handled by your own program with malloc(calloc, etc.) and free. They are also part of the library.

Also notice that the compiler and runtime are different things (you can install the runtime binary without the compiler), although sometimes they are bundled together.

Title: Understanding C runtimes


问:
akka http throws EntityStreamException: Entity stream truncation
I'm writing a client for a rest API using the akka http library. The library seems very powerful, but it works very unstable for me. Quite often (not always) it throws the following exception when I try to consume an HttpResponse.entity:

EntityStreamException: Entity stream truncation

and after this it stops processing subsequent requests at all. Maybe it tries to deal with some back-pressure or actors just die, I don't know.

It doesn't matter how I send a request, using the Request-Level Client-Side API:

```<code>def pollSearchResult(searchId: String): FutureActionResult[String, SearchResult] = {
    val request = HttpRequest(GET, s"http://***/Search/$searchId")

    for {
      response <- Http().singleRequest(request)
      entity <- Unmarshal(response.entity).to[String]
      result = entity.decodeEither[SearchResult]
    } yield result
  }
</code>```

or using the Connection-Level Client-Side API:

```<code>val client = Http(actorSystem).outgoingConnection("***")

def pollSearchResult(searchId: String): FutureActionResult[String, SearchResult] = {
    val request = HttpRequest(GET, s"Search/$searchId")

    for {
      response <- Source.single(request).via(client).runWith(Sink.head)
      entity <- Unmarshal(response.entity).to[String]
      result = entity.decodeEither[SearchResult]
      } yield result
    }
</code>```

It doesn't metter whether I consume the entity using unmarshaller or manually using the getDataBytes, the result is the same - the above exception.

The http status of the response is 200 OK, headers are ok, it is a "Default" entity (so, no chunking), content length is about 500-2000 Kb (increasing akka.http.parsing.max-content-length doesn't help, although the default value should be enough). The server is also ok - other http libraries on other platforms work with this API just fine.

Is it a bug or I am doing something wrong? What is the best non blocking, asycnhonous http library for scala?

答: akka.http.parsing.max-to-strict-bytes property needs to be set appropriately in the configuration file. You can also set it to infinite.

Body:
I'm writing a client for a rest API using the akka http library. The library seems very powerful, but it works very unstable for me. Quite often (not always) it throws the following exception when I try to consume an HttpResponse.entity:

EntityStreamException: Entity stream truncation

and after this it stops processing subsequent requests at all. Maybe it tries to deal with some back-pressure or actors just die, I don't know.

It doesn't matter how I send a request, using the Request-Level Client-Side API:

def pollSearchResult(searchId: String): FutureActionResult[String, SearchResult] = {
    val request = HttpRequest(GET, s"http://***/Search/$searchId")

    for {
      response <- Http().singleRequest(request)
      entity <- Unmarshal(response.entity).to[String]
      result = entity.decodeEither[SearchResult]
    } yield result
  }

or using the Connection-Level Client-Side API:

val client = Http(actorSystem).outgoingConnection("***")

def pollSearchResult(searchId: String): FutureActionResult[String, SearchResult] = {
    val request = HttpRequest(GET, s"Search/$searchId")

    for {
      response <- Source.single(request).via(client).runWith(Sink.head)
      entity <- Unmarshal(response.entity).to[String]
      result = entity.decodeEither[SearchResult]
      } yield result
    }

It doesn't metter whether I consume the entity using unmarshaller or manually using the getDataBytes, the result is the same - the above exception.

The http status of the response is 200 OK, headers are ok, it is a "Default" entity (so, no chunking), content length is about 500-2000 Kb (increasing akka.http.parsing.max-content-length doesn't help, although the default value should be enough). The server is also ok - other http libraries on other platforms work with this API just fine.

Is it a bug or I am doing something wrong? What is the best non blocking, asycnhonous http library for scala?


问:
Miworkplace : An error has occured. See the log file (RPG)
I am learning RPG, and I have to install Miworkplace, I am trying to understand the tutoriel below:

https://miworkplace.com/docs/

I installed Java11 on my Windows 10

https://miworkplace.com/docs/Requirements

I downloaded Miworkplace on my desktop

When I launch MiWorkplace, I have an error message ?

"An error has occured. See the log file"

I don't understand the problem ??

I deleted 3 times the folder -> workspace but I always have the same problem.

Thank you for your help.

答:
Older versions of MiWorkplace required the installation of Java prior to running MiWorkplace. This was documented on the download page.

Recent versions of MiWorkplace do not require a separate installation of Java anymore.

The latest version of MiWorkplace/Pub400 can be downloaded here: https://miworkplace.com


问:
Expected ',' or '...' before numeric const
I am new in C programming and trying to figure out some problems encountered.
When I wrote </p>

```<code>#define N 5

void Sort(int *const array,  int N);
</code>```

<p>the compiler gave me the message "Expected ',' or '...' before numeric const". After searching on the internet and found out that the problem may be casued by the #define being debugged as numeric values. I did get through the compiler by not using the #define for the constant N. However, I wondered how should I modified the above two lines so that I won't get that error message?  </p>

答: You are using N for a macro, #define N 5 and N for a variable name, int N. This is a bad idea. The usual convention is to reserve all capital names for macros. So in this case I would recommend changing int N to int n. Avoid careless use of macros, they cause exactly this sort of problem. But if you do use macros give them more meanful names than 'N' to minimise the chance of this kind of mistake.

Body:
I am new in C programming and trying to figure out some problems encountered.
When I wrote

#define N 5

void Sort(int *const array,  int N);

the compiler gave me the message "Expected ',' or '...' before numeric const". After searching on the internet and found out that the problem may be casued by the #define being debugged as numeric values. I did get through the compiler by not using the #define for the constant N. However, I wondered how should I modified the above two lines so that I won't get that error message?


问:
Extract different kinds of protocol from URL
I have the following URLs with different types of protocol:

```<code>URL=https://example.com
URL=ftp://example.com
URL=ssh://example.com
URL=///filestore/storage
</code>```

I'm using echo ${URL%://*} to get protocol, but for /// it doesn't work, can't apply multiple regex, please help

答:
You can use this extended glob matching:

```<code>"${url%?(:)//*}"
</code>```

Where ?(:) matches an optional : using extended globbing followed by // and that is followed by any number of characters as per glob matching in shell.

Code:

for url in 'https://example.com' 'ftp://example.com' 'ssh://example.com' '///filestore/storage'; do
   echo "${url%?(:)//*}"
done

https
ftp
ssh
/
```

PS: On BASH versions < 4 use shopt -s extglob before this code.

Body:
I have the following URLs with different types of protocol:

URL=https://example.com
URL=ftp://example.com
URL=ssh://example.com
URL=///filestore/storage

I'm using echo ${URL%://*} to get protocol, but for /// it doesn't work, can't apply multiple regex, please help

Body:
You can use this extended glob matching:

"${url%?(:)//*}"

Where ?(:) matches an optional : using extended globbing followed by // and that is followed by any number of characters as per glob matching in shell.

Code:

for url in 'https://example.com' 'ftp://example.com' 'ssh://example.com' '///filestore/storage'; do
   echo "${url%?(:)//*}"
done

https
ftp
ssh
/

PS: On BASH versions < 4 use shopt -s extglob before this code.


问:
Invalid token, state does not match - Auth0 Error Safari only
while using parseHash function in Auth0 library in safari I am getting error

Same code is working fine in chrome. what can be possibly done to resolve this issue?

```<code>handleAuthentication = (onSuccessCallback, onErrorCallback) => {
    console.log('handle auth', this.authservice);
    this.authservice.parseHash((err, authResult) => {
      console.log('authresult inside', authResult, 'error', err);
      if (authResult && authResult.accessToken && authResult.idToken) {
        this.setSession(authResult, onSuccessCallback);
      } else if (err) {
        // onErrorCallback();
      }
    });
  };
</code>```

答:
After lots of research and article exploration, I finally found a solution to this issue.
As auth0 is unable to access state and nonce parameters which are required for forwarding to check login details therefore we can manually add it for the authentication flow to work without any issue.

```<code>login = () => {
    this.authservice.authorize(
      {
        nonce: ${randomString},
        state: ${randomString},
      }
    );
  }

handleAuthentication = (onSuccessCallback, onErrorCallback) => {
  this.authservice.parseHash(
    {nonce: ${randomString}, state: ${randomString},
      (err, result) => {
        // some code
       }
     );
   };
</code>```

Hope it works for you too!!

Body:
while using parseHash function in Auth0 library in safari I am getting error

Same code is working fine in chrome. what can be possibly done to resolve this issue?

handleAuthentication = (onSuccessCallback, onErrorCallback) => {
    console.log('handle auth', this.authservice);
    this.authservice.parseHash((err, authResult) => {
      console.log('authresult inside', authResult, 'error', err);
      if (authResult && authResult.accessToken && authResult.idToken) {
        this.setSession(authResult, onSuccessCallback);
      } else if (err) {
        // onErrorCallback();
      }
    });
  };

Body:
After lots of research and article exploration, I finally found a solution to this issue.
As auth0 is unable to access state and nonce parameters which are required for forwarding to check login details therefore we can manually add it for the authentication flow to work without any issue.

login = () => {
    this.authservice.authorize(
      {
        nonce: ${randomString},
        state: ${randomString},
      }
    );
  }

handleAuthentication = (onSuccessCallback, onErrorCallback) => {
  this.authservice.parseHash(
    {nonce: ${randomString}, state: ${randomString},
      (err, result) => {
        // some code
       }
     );
   };

Hope it works for you too!!


问:
Compare two list for differences - DateTime & String
Sorry but there is no code for this question... I hope thats ok.

So, I have a list of objects with two properties,  DateTime and String.

As a matter of fact, DateTime is just date (insertDate), for example 2022-02-04T00:00:00+01:00.
String is of course some text, a lot of text :)

I have to compare the list with these two properties with another list of identical structure.

To be more clear, those are the data returned by the API, so I have to compare is there any differences between these two lists.

答:
Do it like this (it will compare two lists based on element index , so
if your lists are unsorted you must sort them and then use these codes) :</p>
```<code>public class YourClass
{
    public DateTime DateTime { get; set; }
    public string String { get; set; }
}

public class Program
{
    static List<YourClass> list1 = new List<YourClass>
    {
        new YourClass { DateTime = DateTime.MinValue, String = "str1"},
        new YourClass { DateTime = DateTime.Now.AddDays(1), String = "str2"},
        new YourClass { DateTime = DateTime.Now.AddDays(2), String = "str3"}
    };

    static List<YourClass> list2 = new List<YourClass>
    {
        new YourClass { DateTime = DateTime.MinValue, String = "str1"},
        new YourClass { DateTime = DateTime.Now.AddDays(-1), String = "2str"},
        new YourClass { DateTime = DateTime.Now.AddDays(-2), String = "3str"}
    };

    static void Main(string[] args)
    {
        //a list of integer for storing different elements indexes
        var differentElementsIndexes = new List<int>();

        //check difference of these two list using for loop
        for (int i = 0; i < list1.Count; i++)
        {
            if (list1.ElementAt(i).DateTime != list2.ElementAt(i).DateTime || list1.ElementAt(i).String != list2.ElementAt(i).String)
                differentElementsIndexes.Add(i);
        }
    }
</code>```

Body:
Do it like this (it will compare two lists based on element index , so
if your lists are unsorted you must sort them and then use these codes) :

public class YourClass
{
    public DateTime DateTime { get; set; }
    public string String { get; set; }
}

public class Program
{
    static List<YourClass> list1 = new List<YourClass>
    {
        new YourClass { DateTime = DateTime.MinValue, String = "str1"},
        new YourClass { DateTime = DateTime.Now.AddDays(1), String = "str2"},
        new YourClass { DateTime = DateTime.Now.AddDays(2), String = "str3"}
    };

    static List<YourClass> list2 = new List<YourClass>
    {
        new YourClass { DateTime = DateTime.MinValue, String = "str1"},
        new YourClass { DateTime = DateTime.Now.AddDays(-1), String = "2str"},
        new YourClass { DateTime = DateTime.Now.AddDays(-2), String = "3str"}
    };

    static void Main(string[] args)
    {
        //a list of integer for storing different elements indexes
        var differentElementsIndexes = new List<int>();

        //check difference of these two list using for loop
        for (int i = 0; i < list1.Count; i++)
        {
            if (list1.ElementAt(i).DateTime != list2.ElementAt(i).DateTime || list1.ElementAt(i).String != list2.ElementAt(i).String)
                differentElementsIndexes.Add(i);
        }
    }


答:
Your example is not reproducible because we can't construct the query but I suppose, this should work:

```<code>import pandas as pd

df = pd.DataFrame(list(query.rows()))

# OR

df = pd.DataFrame(query.rows(), columns=query.views)
</code>```

Output:

```<code>>>> df
  Gene.briefDescription                                   Gene.description   Gene.id  ...  Gene.homologues.homologue.organism.name Gene.homologues.type     Gene.homologues.dataSets.name
0                  None  FUNCTION: <B>Automated description from the Al...  23666503  ...                             Homo sapiens           orthologue  Mouse/Human Orthologies from MGI
1                  None  FUNCTION: <B>Automated description from the Al...  23341647  ...                             Homo sapiens           orthologue  Mouse/Human Orthologies from MGI
2                  None  FUNCTION: <B>Automated description from the Al...  23862751  ...                             Homo sapiens           orthologue  Mouse/Human Orthologies from MGI
3                  None  FUNCTION: <B>Automated description from the Al...  23677242  ...                             Homo sapiens           orthologue  Mouse/Human Orthologies from MGI

[4 rows x 21 columns]
</code>```

Title: save as dataframe python

Body:
Your example is not reproducible because we can't construct the query but I suppose, this should work:

import pandas as pd

df = pd.DataFrame(list(query.rows()))

# OR

df = pd.DataFrame(query.rows(), columns=query.views)

Output:

>>> df
  Gene.briefDescription                                   Gene.description   Gene.id  ...  Gene.homologues.homologue.organism.name Gene.homologues.type     Gene.homologues.dataSets.name
0                  None  FUNCTION: <B>Automated description from the Al...  23666503  ...                             Homo sapiens           orthologue  Mouse/Human Orthologies from MGI
1                  None  FUNCTION: <B>Automated description from the Al...  23341647  ...                             Homo sapiens           orthologue  Mouse/Human Orthologies from MGI
2                  None  FUNCTION: <B>Automated description from the Al...  23862751  ...                             Homo sapiens           orthologue  Mouse/Human Orthologies from MGI
3                  None  FUNCTION: <B>Automated description from the Al...  23677242  ...                             Homo sapiens           orthologue  Mouse/Human Orthologies from MGI

[4 rows x 21 columns]