问:
How to write the superscript text in java?
I want to display meter/second(2) in the output of acceleration as units. Which keyword should I use?</p>

```<code>public class Distance {
public static void main(String[] args)
{
    int distance,init_velocity,time,acceleration;
    acceleration=10;
    init_velocity=20;
    time=20;
    distance=(init_velocity*time)+((acceleration*time*time)/2);
    System.out.println("-------------------------------------------------------------------------");
    System.out.println("Distance travelled by John ="+ distance+"  "+"meters" );
    System.out.println("-------------------------------------------------------------------------");
  }
}
</code>```

答:
Expanding on the previous answer from @shachar - this can be achieved using unicode characters as seen here:

```<code>   System.out.println("cm\u00b2");
   System.out.println("meter/second\u00b2");
   System.out.println("meter/second\u00b3");
</code>```

This results in the below output:

```<code>cm²
meter/second²
meter/second³
</code>```

Body:
I want to display meter/second(2) in the output of acceleration as units. Which keyword should I use?

public class Distance {
public static void main(String[] args)
{
    int distance,init_velocity,time,acceleration;
    acceleration=10;
    init_velocity=20;
    time=20;
    distance=(init_velocity*time)+((acceleration*time*time)/2);
    System.out.println("-------------------------------------------------------------------------");
    System.out.println("Distance travelled by John ="+ distance+"  "+"meters" );
    System.out.println("-------------------------------------------------------------------------");
  }
}

Body:
Expanding on the previous answer from @shachar - this can be achieved using unicode characters as seen here:

   System.out.println("cm\u00b2");
   System.out.println("meter/second\u00b2");
   System.out.println("meter/second\u00b3");

This results in the below output:

cm²
meter/second²
meter/second³


来源: stackexchange

问:
how to open the .ipynb file in readable format
I have got downloaded a file that got downloaded in a format .ipynb extension but its not in a readable format. Can anyone help me to figure out how to make it in a readable format? Attaching a screenshot of the file when I tried opening it in notepad.

how to open it in readable format

答:
You need Jupyter Notebook in your machine. That is one option.
 Otherwise, you can upload the file into GitHub and open the .ipynb file from there.

ContentLicense: CC BY-SA 4.0


问:
Flutter error: Execution failed for task ':app:compileDebugJavaWithJavac'
I try run on android and return this error.

I Aredy tried:

gradle.properties:

android.useAndroidX=true
android.enableJetifier=true

build.gradle:

testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true

my pubspec.yaml:

flutter_facebook_login: ^3.0.0
  firebase_database: ^3.1.0
  firebase_auth: ^0.15.0+1
  cloud_firestore: ^0.12.11
  url_launcher: ^5.2.7
  google_maps_flutter: ^0.5.21+12
  image_picker: ^0.6.2+1
  firebase_storage: ^3.0.8
  intl: ^0.16.0

What went wrong: Execution failed for task ':app:compileDebugJavaWithJavac'.

Compilation failed; see the compiler error output for details.

Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 35s The built failed likely due to AndroidX
  incompatibilities in a plugin. The tool is about to try using Jetfier
  to solve the incompatibility. Building plugin cloud_firestore... The
  plugin cloud_firestore could not be built due to the issue above.

SOLUTION:

When you created the new project, did you select "androidX"? And are those versions the latest versions? (meaning, androidX compatible/requiring). if not sure, create a new project and make sure to select androidX, and change the sdk settings to 23/29 as above.

答: I solved my problem by changing the version (reduced the gradle version), which caused me another problem, but related to one API and Kotlin plugin. Since I cannot delete Kotlin I took out the API and it came to life again! thanks for your help here!</p>


问:
Strange values when using Memoization for Grid Traveler problem?
I'm learning dynamic programming and I've just started with some simple problems. I'm doing a grid traveler problem where you start in the top-left corner of a grid and you can only move left or down. You need to return the amount of unique paths to get from the top-left corner to the bottom-right corner of the grid.

I'm getting some strange return values when I try some bigger grids. For example, when I try (18,18) it goes to -> -1961361076 instead of 2333606220

Can anyone see something wrong with my code?

'''

```<code>import java.util.HashMap;

public class Test{

    public static void main(String[] args){
        HashMap<String, Integer> memo = new HashMap<>();
        System.out.println(gridTraveler(2,2,memo));
        System.out.println(gridTraveler(18,18,memo));
    }

    public static int gridTraveler(int m, int n, HashMap<String, Integer> memo){

        String key = "" + m + "," + n;
        //base case
        if(m == 1 || n == 1)
            return 1;

        //base case
        if(m == 0 || n == 0)
            return 0;

        if (memo.containsKey(key))
            return memo.get(key);

        //Set value of the key memo[key]
        memo.put(key, gridTraveler(m-1, n, memo) + gridTraveler(m, n-1, memo));

        return memo.get(key);
    }
}
</code>```

答:
This is because the maximum value of an Integer has been reached. When you try to add a value to it, it overflows, and "wraps around" to the negative.

If you change to Long instead of Integer it will work: -

```<code>public static void main(String[] args){
    HashMap<String, Long> memo = new HashMap<>();
    System.out.println(gridTraveler(2,2,memo));
    System.out.println(gridTraveler(18,18,memo));
}

public static Long gridTraveler(long i, long j, HashMap<String, Long> memo){

    String key = "" + i + "," + j;
    //base case
    if(i == 1 || j == 1)
        return (long) 1;

    //base case
    if(i == 0 || j == 0)
        return (long) 0;

    if (memo.containsKey(key))
        return memo.get(key);

    //Set value of the key memo[key]
    memo.put(key, gridTraveler(i-1, j, memo) + gridTraveler(i, j-1, memo));

    return memo.get(key);
}
}
</code>```

Body:
I'm learning dynamic programming and I've just started with some simple problems. I'm doing a grid traveler problem where you start in the top-left corner of a grid and you can only move left or down. You need to return the amount of unique paths to get from the top-left corner to the bottom-right corner of the grid.

I'm getting some strange return values when I try some bigger grids. For example, when I try (18,18) it goes to -> -1961361076 instead of 2333606220

Can anyone see something wrong with my code?

'''

import java.util.HashMap;

public class Test{

    public static void main(String[] args){
        HashMap<String, Integer> memo = new HashMap<>();
        System.out.println(gridTraveler(2,2,memo));
        System.out.println(gridTraveler(18,18,memo));
    }

    public static int gridTraveler(int m, int n, HashMap<String, Integer> memo){

        String key = "" + m + "," + n;
        //base case
        if(m == 1 || n == 1)
            return 1;

        //base case
        if(m == 0 || n == 0)
            return 0;

        if (memo.containsKey(key))
            return memo.get(key);

        //Set value of the key memo[key]
        memo.put(key, gridTraveler(m-1, n, memo) + gridTraveler(m, n-1, memo));

        return memo.get(key);
    }
}

Body:
This is because the maximum value of an Integer has been reached. When you try to add a value to it, it overflows, and "wraps around" to the negative.

If you change to Long instead of Integer it will work: -

public static void main(String[] args){
    HashMap<String, Long> memo = new HashMap<>();
    System.out.println(gridTraveler(2,2,memo));
    System.out.println(gridTraveler(18,18,memo));
}

public static Long gridTraveler(long i, long j, HashMap<String, Long> memo){

    String key = "" + i + "," + j;
    //base case
    if(i == 1 || j == 1)
        return (long) 1;

    //base case
    if(i == 0 || j == 0)
        return (long) 0;

    if (memo.containsKey(key))
        return memo.get(key);

    //Set value of the key memo[key]
    memo.put(key, gridTraveler(i-1, j, memo) + gridTraveler(i, j-1, memo));

    return memo.get(key);
}
}


问:
How to build regex to match values if they exists
I have a requirement to match the complete string if some part of value exists or not

For example :- Here are the list of strings that should be matched

en.key.value
fr.key.value
es.key.value
pt.key.value
key.value

So, length of string before first . can only be >=2.

Below are some values which should not be accepted

.key.value
z.key.value

Could someone please help ?
Thanks in advance

答:
```<code>^[^.]{2,}\..+$
</code>```

Matches

```<code>en.key.value
fr.key.value
es.key.value
pt.key.value
key.value
</code>```

Does not match

```<code>.key.value
z.key.value
</code>```

See yourself: Regexr.com

Body:
^[^.]{2,}\..+$

Matches

en.key.value
fr.key.value
es.key.value
pt.key.value
key.value

Does not match

.key.value
z.key.value

See yourself: Regexr.com


问:
Android AdMob Loading Problem
I have used adMob to display ads in my android app.

but it takes some time to load the ad. So I want to display static banner while the ad is loading. The probelm I am facing is that, the adListeners events are not responding which cause the ad to overlap over the static banner

how can I hide the banner when adMob actually loads ad and how do I know that ad is loaded and actually shown in the Application ?

Any help would be greatly appreciated.

答: You can have a ImageView for default banner right under the ad view. So no need to hide/show the default banner. When the ad loads the default banner will go under it and will not be visible.

ContentLicense: CC BY-SA 3.0

Title: Android AdMob Loading Problem


问:
phpMyAdmin and Laragon
How do Laragon and phpMyAdmin work with one another?  I've downloaded phpMyAdmin and extracted it to laragon\etc\apps, but whenever I click on the Database button of Laragon, I get sent to something called Adminer instead of phpMySQL.  I have tried deleting Adminer, but that doesn't work.  Please help.  Thanks!</p>

答:
First of Download and Install Laragon. After installtion of Laragon You can see following screen.

Right Click on the Database Button You see following screen.

Database > Tools  > Quick Add > Phpmyadmin.

After this it download and install phpmyadmin in Laragon automatically.

Title: phpMyAdmin and Laragon


问:
Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"
I'm trying to connect a Java Web API via HTTPS; however, an exception is thrown:

```<code>javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException
</code>```

I followed these steps which I learned from online keytool & SSL cert tutorials:

I copied the HTTPS URL into the browser, downloaded the SSL certificates & Installed them in the browser using Internet Explorer.

Exported the certificates to a path on my computer, the certificates were saved as .cer

Used the keytool's import option. The command below executed without any errors.

```<code>keytool -import -alias downloadedCertAlias -keystore C:\path\to\my\keystore\cacerts.file -file C:\path\of\exportedCert.cer
</code>```

I was prompted for a password at the command prompt, which I entered then I was authenticated.

The cmd window printed some certificate data & signatures and I was prompted with the question:

Trust this certificate?

I answered yes.

The cmd prompt displayed

Certificate was added to keystore

However after that message, another exception was displayed:

```<code>keytool error: java.io.FileNotFoundException: C:\Program files\...\cacerts <Access Denied>
</code>```

Finally when I checked the keystore , the SSL certificate was not added and my application gives the same exception I was getting earlier when trying to connect:

```<code>(javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException)
</code>```

答:
Make sure you running as Administrator.
In Mac terminal:-

Run sudo -i

Then execute the commands

Body:
I'm trying to connect a Java Web API via HTTPS; however, an exception is thrown:

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException

I followed these steps which I learned from online keytool & SSL cert tutorials:

I copied the HTTPS URL into the browser, downloaded the SSL certificates & Installed them in the browser using Internet Explorer.

Exported the certificates to a path on my computer, the certificates were saved as .cer

Used the keytool's import option. The command below executed without any errors.

keytool -import -alias downloadedCertAlias -keystore C:\path\to\my\keystore\cacerts.file -file C:\path\of\exportedCert.cer

I was prompted for a password at the command prompt, which I entered then I was authenticated.

The cmd window printed some certificate data & signatures and I was prompted with the question:

Trust this certificate?

I answered yes.

The cmd prompt displayed

Certificate was added to keystore

However after that message, another exception was displayed:

keytool error: java.io.FileNotFoundException: C:\Program files\...\cacerts <Access Denied>

Finally when I checked the keystore , the SSL certificate was not added and my application gives the same exception I was getting earlier when trying to connect:

(javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException)


问:
Perl - hash->Yaml->hash reduces quotation marks in numbers:
I'm trying to insert a hash to a YAML file and later return it to the original hash.
(I'm doing it because I'm using multiple threads and want to merge them all at the end).

This is my code:

```<code>#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;
$Data::Dumper::Sortkeys = 1;
use YAML::XS;
use YAML qw(Dump);

sub PrintHash2Yaml {
    my ( $hash2Yaml, $yamlfilename ) = @_;

    open( FH, ">$yamlfilename.yaml" ) or die "can't open $yamlfilename.yaml : $!\n";
    print FH Dump($hash2Yaml);
    close FH;
}

sub yaml2Hash {
    my ($yamlfilename) = @_;

    # step 1: open file
    open my $fh, '<', "$yamlfilename.yaml" or die "can't open config file: $yamlfilename $!";

    # step 2: slurp file contents
    my $yml = do { local $/; <$fh> };

    # step 3: convert YAML 'stream' to perl hash ref
    my $yaml2hash = Load($yml);

    my $hashDebug = Dumper($yaml2hash);
    open( FH2, ">$yamlfilename.hash2" ) or die "can't open $yamlfilename.hash2 : $!\n";
    print FH2 $hashDebug;
    close FH2;

    return $yaml2hash;
}

my $hash1 = { 'hello' => '234' };
PrintHash2Yaml($hash1, "ex1");
my $hash3 = yaml2Hash("ex1");

print Dumper($hash3);
</code>```

The output is:

```<code>$VAR1 = {
          'hello' => 234
        };

</code>```

I would have expected the value to be '234' and not just 234.
Any ideas how could I return it to '234'?

Thanks :)

EDIT:
I was told there is no difference in perl between those options and that perl relates to everything the same. That's enough for me.

答:
YAML.pm and YAML::XS might not handle numbers and strings correctly. YAML.pm is old anyway and shouldn't be used anymore.

While it is true that strictly there is no 100% reliable way to differentiate between numbers and strings, the variables have certain internal flags, and as long as they don't change, you can use YAML::PP which will handle the flags (in the same way as currently JSON::PP does) to differentiate between numbers and strings by making a good guess. Simply replace your usage of YAML and YAML::XS with YAML::PP:

```<code>use YAML::PP qw( Load Dump );
</code>```

and the output will be

```<code>$VAR1 = {
          'hello' => '234'
        };
</code>```

Body:
I'm trying to insert a hash to a YAML file and later return it to the original hash.
(I'm doing it because I'm using multiple threads and want to merge them all at the end).

This is my code:

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;
$Data::Dumper::Sortkeys = 1;
use YAML::XS;
use YAML qw(Dump);

sub PrintHash2Yaml {
    my ( $hash2Yaml, $yamlfilename ) = @_;

    open( FH, ">$yamlfilename.yaml" ) or die "can't open $yamlfilename.yaml : $!\n";
    print FH Dump($hash2Yaml);
    close FH;
}

sub yaml2Hash {
    my ($yamlfilename) = @_;

    # step 1: open file
    open my $fh, '<', "$yamlfilename.yaml" or die "can't open config file: $yamlfilename $!";

    # step 2: slurp file contents
    my $yml = do { local $/; <$fh> };

    # step 3: convert YAML 'stream' to perl hash ref
    my $yaml2hash = Load($yml);

    my $hashDebug = Dumper($yaml2hash);
    open( FH2, ">$yamlfilename.hash2" ) or die "can't open $yamlfilename.hash2 : $!\n";
    print FH2 $hashDebug;
    close FH2;

    return $yaml2hash;
}

my $hash1 = { 'hello' => '234' };
PrintHash2Yaml($hash1, "ex1");
my $hash3 = yaml2Hash("ex1");

print Dumper($hash3);

The output is:

$VAR1 = {
          'hello' => 234
        };

I would have expected the value to be '234' and not just 234.
Any ideas how could I return it to '234'?

Thanks :)

EDIT:
I was told there is no difference in perl between those options and that perl relates to everything the same. That's enough for me.

Body:
YAML.pm and YAML::XS might not handle numbers and strings correctly. YAML.pm is old anyway and shouldn't be used anymore.

While it is true that strictly there is no 100% reliable way to differentiate between numbers and strings, the variables have certain internal flags, and as long as they don't change, you can use YAML::PP which will handle the flags (in the same way as currently JSON::PP does) to differentiate between numbers and strings by making a good guess. Simply replace your usage of YAML and YAML::XS with YAML::PP:

use YAML::PP qw( Load Dump );

and the output will be

$VAR1 = {
          'hello' => '234'
        };


问:
Basic JSF: is it possible to SET a property value in EL?
I need to do something like this:

```<code><a4j:support even="onclick" action="#{myBean.myProperty = null}"/>
</code>```

I would like to know if this is possible and which would be the proper syntax if so.

答:
If you're running an EL 2.2 capable container (Tomcat 7, Glassfish 3, JBoss AS 6, etc and newer, with a web.xml declared conform at least Servlet 3.0), or are using JBoss EL (your seam tag suggests that you are using it...), then you should be able to invoke methods with arguments in EL:

```<code><a4j:support event="onclick" action="#{myBean.setMyProperty(null)}"/>
</code>```

An alternative is using <f:setPropertyActionListener>, this is supported in JSF 1.2 as well:

```<code><a4j:support event="onclick" />
<f:setPropertyActionListener target="#{myBean.myProperty}" value="#{null}" />
</code>```

Body:
I need to do something like this:

<a4j:support even="onclick" action="#{myBean.myProperty = null}"/>

I would like to know if this is possible and which would be the proper syntax if so.

Body:
If you're running an EL 2.2 capable container (Tomcat 7, Glassfish 3, JBoss AS 6, etc and newer, with a web.xml declared conform at least Servlet 3.0), or are using JBoss EL (your seam tag suggests that you are using it...), then you should be able to invoke methods with arguments in EL:

<a4j:support event="onclick" action="#{myBean.setMyProperty(null)}"/>

An alternative is using <f:setPropertyActionListener>, this is supported in JSF 1.2 as well:

<a4j:support event="onclick" />
<f:setPropertyActionListener target="#{myBean.myProperty}" value="#{null}" />


问:
T3PO3 v10: How to use RouteEnhancer with ArrayPaginator?
I'm using the ArrayPaginator for my Extbase list view, since Fluid widget functionality will no longer be available in TYPO3 v11.

And I'm currently trying to use the RouteEnhancer with this.

My list action just receives the argument for the current page as integer.

And the code for the RouteEnhancer looks like this:

```<code>  RefList:
    type: Extbase
    limitToPages:
      - 142
    extension: Ref
    plugin: Pi2
    routes:
      -
        routePath: /seite-{page}
        _controller: 'Ref::list'
        _arguments:
          page: currentPage
    defaultController: 'Ref::list'
    requirements:
      page: \d+
    aspects:
      page:
        type: StaticRangeMapper
        start: '1'
        end: '1000'
</code>```

I've seen a lot examples for the Fluid pagination widget that contained the value @widget_0/currentPage for the argument page.

The URL is generated correctly if I switch to another page but the content displayed from the list view is still the same as on page 1.

What am I missing here?

答:
I've found a workaround.
Inside the controller list action:  $currentPage = (int) ($_GET['tx_ref_pi2']['currentPage'] ?? 1);

Body:
I'm using the ArrayPaginator for my Extbase list view, since Fluid widget functionality will no longer be available in TYPO3 v11.

And I'm currently trying to use the RouteEnhancer with this.

My list action just receives the argument for the current page as integer.

And the code for the RouteEnhancer looks like this:

  RefList:
    type: Extbase
    limitToPages:
      - 142
    extension: Ref
    plugin: Pi2
    routes:
      -
        routePath: /seite-{page}
        _controller: 'Ref::list'
        _arguments:
          page: currentPage
    defaultController: 'Ref::list'
    requirements:
      page: \d+
    aspects:
      page:
        type: StaticRangeMapper
        start: '1'
        end: '1000'

I've seen a lot examples for the Fluid pagination widget that contained the value @widget_0/currentPage for the argument page.

The URL is generated correctly if I switch to another page but the content displayed from the list view is still the same as on page 1.

What am I missing here?


问:
converting Coldfusion query results to formatted javascript array
I am trying to write ColdFusion code runs a query then puts the results in an array in a certain format.

the query:

```<code><cfquery name="get_cbox" datasource="ds" username="un" password="pw">
    SELECT CBOXADD, MFLPU, SATLPU, BOXTYPE
    FROM myTable
</cfquery>
</code>```

and array with 1 element looks like:

```<code><script type="text/javascript">
    var addresses = [{ name: "<table width=100% style='font-size:14px'><td rowspan='3'>OBS:1</td><tr><td>"#cboxadd#"</td><td align='right'>LPU M-F: "#mflpu#"</td></tr><tr><td>Barrigada Guam, 96910 ("#boxtype#")</td><td align='right'>LPU Sat: "#satlpu#"</td></tr></table>", to: #cboxadd#", Barrigada Guam, 96910" }];
</script>
</code>```

How do I accomplish this?

答: You could try the serializeJSON function in CF8 or CF9, which will take any ColdFusion object and turn it into a usable JSON string. That can then be used in your JavaScript functions.</p>

Body:
I am trying to write ColdFusion code runs a query then puts the results in an array in a certain format.

the query:

<cfquery name="get_cbox" datasource="ds" username="un" password="pw">
    SELECT CBOXADD, MFLPU, SATLPU, BOXTYPE
    FROM myTable
</cfquery>

and array with 1 element looks like:

How do I accomplish this?


问:
What does "The code generator has deoptimised the styling of [some file] as it exceeds the max of "100KB"" mean?
I added a new npm package to my project and require it in one of my modules.

Now I get this message from webpack,

build modulesNote: The code generator has deoptimised the styling of "D:/path/to/project/node_modules/ramda/dist/ramda.js" as it exceeds the max of "100KB".

What does it mean? Do I need to take some action?

答:
This is my babel configuration:

module.exports = {
  presets: [['@babel/preset-env'], ['@babel/preset-react']],
  plugins: [
    [
      '@babel/plugin-transform-runtime',
      {
        corejs: 3,
      },
    ],
    // react hmr
    ['react-refresh/babel'],
  ],
};

```
<p>I also met this problem because these code:</p>
<pre class="lang-js prettyprint-override"><code>    [
      '@babel/plugin-transform-runtime',
      {
        corejs: 3,
      },
    ],
</code>```

And finally I solved this problem by add

```<code>exclude: /node_modules/
</code>```

in

```<code>      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: ['babel-loader'],
      },
</code>```

Body:
This is my babel configuration:

module.exports = {
  presets: [['@babel/preset-env'], ['@babel/preset-react']],
  plugins: [
    [
      '@babel/plugin-transform-runtime',
      {
        corejs: 3,
      },
    ],
    // react hmr
    ['react-refresh/babel'],
  ],
};

I also met this problem because these code:

    [
      '@babel/plugin-transform-runtime',
      {
        corejs: 3,
      },
    ],

And finally I solved this problem by add

exclude: /node_modules/

in

      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: ['babel-loader'],
      },


问:
How to display a different message read from a file every day of the week in php?
I have a php function that reads a line (random message) from a file and displays it on my web page. It displays a new message every time I click refresh, but I want it to display the message for a day (it should change at midnight). Is it possible to do it with another function, implying my database? Or with a JS function?

EDIT
This is the function (not my code):

function loadMessagesFromFile()
{
    $path = ROOT_PATH. '/messages.txt';
    $file = fopen($path,"r");
    $messages = array();
    while($data = fgets($file))
    {
        $messages[] = $data;
    }
    fclose($file);
    return $messages;
}
```
<p>This is how I use it to display the message:</p>
```$messages_from_file = loadMessagesFromFile();
$key = array_rand($messages_from_file);
$full_text = $messages_from_file[$key];
```
<p>LATER EDIT</p>
```I found the answer here: <https://stackoverflow.com/questions/6815614/generating-word-of-the-day-via-php-random-number#:~:text=Just%20set%20the%20current%20date,same%20number%20for%20one%20Day.>
```

答:
You have multiple possibilities:

Create a file with only one line every day taken from the other file

Create a cron who will be executed ad midnight who will get a random message and set it in database or cache.

If you want a different message per people but persist one day, you can use the local storage of the visitor to store the message with the current date and if the date stored is different from the current date, you change it.

Body:
I have a php function that reads a line (random message) from a file and displays it on my web page. It displays a new message every time I click refresh, but I want it to display the message for a day (it should change at midnight). Is it possible to do it with another function, implying my database? Or with a JS function?

EDIT
This is the function (not my code):

function loadMessagesFromFile()
{
    $path = ROOT_PATH. '/messages.txt';
    $file = fopen($path,"r");
    $messages = array();
    while($data = fgets($file))
    {
        $messages[] = $data;
    }
    fclose($file);
    return $messages;
}

This is how I use it to display the message:

$messages_from_file = loadMessagesFromFile();
$key = array_rand($messages_from_file);
$full_text = $messages_from_file[$key];

LATER EDIT

I found the answer here: <https://stackoverflow.com/questions/6815614/generating-word-of-the-day-via-php-random-number#:~:text=Just%20set%20the%20current%20date,same%20number%20for%20one%20Day.>


问:
How does Sentry's semantic versioning work?
I’ve just done a new release to our customer and manually uploaded the version with:

```<code>sentry-cli releases new -p myproject 0.0.53
sentry-cli releases --org mycompany deploys 0.0.53 new -e beta
</code>```

0.0.53 shows up in the Releases list. It’s top of the list of releases sorted by Semantic Versioning. But the list sorted by Build Number shows “There are no releases
with semantic versioning”:
https://sentry.io/organizations/mycompany/releases/?sort=build

If “0.0.53” isn’t semantic versioning then what is?

Update:

I'm confused because although in Bind The Version they give the example my.project.name@2.3.12+1234 elsewhere they mention using semver 2.0.0 - this accepts a version MAJOR.MINOR.BUILD with no brackets. Also in Passing Additional Data the version is shown as "2.3.12" which is the same format as what we're providing now.

答:
From their documentation on release, it looks like they are expecting a value comprised of package name, version  number, and build number, like so -

my.project.name@2.3.12+1234

More details here - https://docs.sentry.io/platforms/javascript/configuration/releases/#bind-the-version

Body:
I’ve just done a new release to our customer and manually uploaded the version with:

sentry-cli releases new -p myproject 0.0.53
sentry-cli releases --org mycompany deploys 0.0.53 new -e beta

0.0.53 shows up in the Releases list. It’s top of the list of releases sorted by Semantic Versioning. But the list sorted by Build Number shows “There are no releases
with semantic versioning”:
https://sentry.io/organizations/mycompany/releases/?sort=build

If “0.0.53” isn’t semantic versioning then what is?

Update:

I'm confused because although in Bind The Version they give the example my.project.name@2.3.12+1234 elsewhere they mention using semver 2.0.0 - this accepts a version MAJOR.MINOR.BUILD with no brackets. Also in Passing Additional Data the version is shown as "2.3.12" which is the same format as what we're providing now.


问:
Fix alignment of multiline equations with separate equation number
I am writing the following set of equations having multiple lines with each needing a separate equation number. I am currently stuck with the alignment for this equations. Any help? Is there some better way of doing this using a package? Thanks!</p>
```<code>\documentclass[10pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{graphicx}
\begin{document}
    \begin{align}
        G_{1}^{e x}=& \sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l^{\prime}} A_{j k l} Y^{j} Z^{k} U^{\prime}
    \end{align}

    \begin{equation}
        \begin{aligned}
            G_{2}^{e x}=&-\sum_{2}^{j^{\prime}} A_{j 00} /(1-j)+\sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l^{\prime}} \\
            &\left\{A_{j k l} Y^{j} Z^{k} U^{l}\{1+(j-k) /[Y(1-j)]\}\right\} \\
        \end{aligned}
    \end{equation}

    \begin{equation}
        \begin{aligned}
            G_{3}^{e x}=&-\sum_{2} \sum_{0} A_{j k 0} /(1-j)+\sum_{2} \sum_{0} \sum_{0} \\
            &\{A _ { j k l } Y ^ { j } Z ^ { k } U ^ { l } \{1+(j-k) /[Y(1-j)]\\
            &+(k-l) /[Y Z(1-j)]\}\} \\
            %G_{4}^{e x}=&-\sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l^{\prime}} A_{j k l} /(1-j)+\sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l^{\prime}} \\
            %   &\left\{A _ { j k l } Y ^ { j } Z ^ { k } U ^ { l } \left\{1+(j-k) /[Y(1-j)]\right.\\
            %   &+(k-l) /[Y Z(1-j)]+l /[Y Z U(1-j)]\}\}
        \end{aligned}
    \end{equation}

    \begin{equation}
        \begin{aligned}
            G_{4}^{e x}=&-\sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l^{\prime}} A_{\mathrm{jkl}} \mathrm{Y} /(1-\mathrm{j})-\sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l} A_{\mathrm{jkl}} \mathrm{Y}^{\mathrm{j}} \mathrm{Z} \mathrm{T}^{\mathrm{j}} \\
            &\{1+[(\mathrm{j}-\mathrm{k}) / \mathrm{Y}(1-\mathrm{j})]+[(\mathrm{k}-1) / \mathrm{YZ}(1-\mathrm{j})]+\\
            &[1 / \mathrm{YZT}(1-\mathrm{j})]\}
        \end{aligned}
    \end{equation}
    \begin{equation}
        \begin{aligned}
            G^{e x}=&-\sum_{2}^{j^{\prime}} A_{\mathrm{j} 00} \mathrm{Y} /(1-\mathrm{j})-\sum_{2}^{j^{\prime}} \sum_{1}^{k^{\prime}} A_{\mathrm{jk} 0} \mathrm{YZ} /(1-\mathrm{j})-\\
            & \sum_{2}^{j^{\prime}} \sum_{1}^{k^{\prime}} \sum_{1}^{l^{\prime}} A_{\mathrm{jkl}} \mathrm{YZT} /(1-\mathrm{j})+\\
            & \sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l^{\prime}} A_{\mathrm{jkl}} \mathrm{Y}^{\mathrm{j}} \mathrm{Z}^{\mathrm{k}} \mathrm{T}^{1} /(1-\mathrm{j})
        \end{aligned}
    \end{equation}
\end{document}
</code>```

答:
Maybe use a single align and then excludes all lines which don't need their own equation number with \notag?

```<code>\documentclass[10pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{graphicx}
\begin{document}
    \begin{align}
        G_{1}^{e x}=& \sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l^{\prime}} A_{j k l} Y^{j} Z^{k} U^{\prime} \\
            G_{2}^{e x}=&-\sum_{2}^{j^{\prime}} A_{j 00} /(1-j)+\sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l^{\prime}} \\
            &\left\{A_{j k l} Y^{j} Z^{k} U^{l}\{1+(j-k) /[Y(1-j)]\}\right\} \notag\\
            G_{3}^{e x}=&-\sum_{2} \sum_{0} A_{j k 0} /(1-j)+\sum_{2} \sum_{0} \sum_{0} \\
            &\{A _ { j k l } Y ^ { j } Z ^ { k } U ^ { l } \{1+(j-k) /[Y(1-j)]\notag\\
            &+(k-l) /[Y Z(1-j)]\}\} \notag\\
            %G_{4}^{e x}=&-\sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l^{\prime}} A_{j k l} /(1-j)+\sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l^{\prime}} \\
            %   &\left\{A _ { j k l } Y ^ { j } Z ^ { k } U ^ { l } \left\{1+(j-k) /[Y(1-j)]\right.\\
            %   &+(k-l) /[Y Z(1-j)]+l /[Y Z U(1-j)]\}\}
            G_{4}^{e x}=&-\sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l^{\prime}} A_{\mathrm{jkl}} \mathrm{Y} /(1-\mathrm{j})-\sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l} A_{\mathrm{jkl}} \mathrm{Y}^{\mathrm{j}} \mathrm{Z} \mathrm{T}^{\mathrm{j}} \\
            &\{1+[(\mathrm{j}-\mathrm{k}) / \mathrm{Y}(1-\mathrm{j})]+[(\mathrm{k}-1) / \mathrm{YZ}(1-\mathrm{j})]+\notag\\
            &[1 / \mathrm{YZT}(1-\mathrm{j})]\}\notag\\
            G^{e x}=&-\sum_{2}^{j^{\prime}} A_{\mathrm{j} 00} \mathrm{Y} /(1-\mathrm{j})-\sum_{2}^{j^{\prime}} \sum_{1}^{k^{\prime}} A_{\mathrm{jk} 0} \mathrm{YZ} /(1-\mathrm{j})-\\
            & \sum_{2}^{j^{\prime}} \sum_{1}^{k^{\prime}} \sum_{1}^{l^{\prime}} A_{\mathrm{jkl}} \mathrm{YZT} /(1-\mathrm{j})+\notag\\
            & \sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l^{\prime}} A_{\mathrm{jkl}} \mathrm{Y}^{\mathrm{j}} \mathrm{Z}^{\mathrm{k}} \mathrm{T}^{1} /(1-\mathrm{j})\notag
        \end{align}
\end{document}
</code>```

Body:
I am writing the following set of equations having multiple lines with each needing a separate equation number. I am currently stuck with the alignment for this equations. Any help? Is there some better way of doing this using a package? Thanks!

\documentclass[10pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{graphicx}
\begin{document}
    \begin{align}
        G_{1}^{e x}=& \sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l^{\prime}} A_{j k l} Y^{j} Z^{k} U^{\prime}
    \end{align}

    \begin{equation}
        \begin{aligned}
            G_{2}^{e x}=&-\sum_{2}^{j^{\prime}} A_{j 00} /(1-j)+\sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l^{\prime}} \\
            &\left\{A_{j k l} Y^{j} Z^{k} U^{l}\{1+(j-k) /[Y(1-j)]\}\right\} \\
        \end{aligned}
    \end{equation}

    \begin{equation}
        \begin{aligned}
            G_{3}^{e x}=&-\sum_{2} \sum_{0} A_{j k 0} /(1-j)+\sum_{2} \sum_{0} \sum_{0} \\
            &\{A _ { j k l } Y ^ { j } Z ^ { k } U ^ { l } \{1+(j-k) /[Y(1-j)]\\
            &+(k-l) /[Y Z(1-j)]\}\} \\
            %G_{4}^{e x}=&-\sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l^{\prime}} A_{j k l} /(1-j)+\sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l^{\prime}} \\
            %   &\left\{A _ { j k l } Y ^ { j } Z ^ { k } U ^ { l } \left\{1+(j-k) /[Y(1-j)]\right.\\
            %   &+(k-l) /[Y Z(1-j)]+l /[Y Z U(1-j)]\}\}
        \end{aligned}
    \end{equation}

    \begin{equation}
        \begin{aligned}
            G_{4}^{e x}=&-\sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l^{\prime}} A_{\mathrm{jkl}} \mathrm{Y} /(1-\mathrm{j})-\sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l} A_{\mathrm{jkl}} \mathrm{Y}^{\mathrm{j}} \mathrm{Z} \mathrm{T}^{\mathrm{j}} \\
            &\{1+[(\mathrm{j}-\mathrm{k}) / \mathrm{Y}(1-\mathrm{j})]+[(\mathrm{k}-1) / \mathrm{YZ}(1-\mathrm{j})]+\\
            &[1 / \mathrm{YZT}(1-\mathrm{j})]\}
        \end{aligned}
    \end{equation}
    \begin{equation}
        \begin{aligned}
            G^{e x}=&-\sum_{2}^{j^{\prime}} A_{\mathrm{j} 00} \mathrm{Y} /(1-\mathrm{j})-\sum_{2}^{j^{\prime}} \sum_{1}^{k^{\prime}} A_{\mathrm{jk} 0} \mathrm{YZ} /(1-\mathrm{j})-\\
            & \sum_{2}^{j^{\prime}} \sum_{1}^{k^{\prime}} \sum_{1}^{l^{\prime}} A_{\mathrm{jkl}} \mathrm{YZT} /(1-\mathrm{j})+\\
            & \sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l^{\prime}} A_{\mathrm{jkl}} \mathrm{Y}^{\mathrm{j}} \mathrm{Z}^{\mathrm{k}} \mathrm{T}^{1} /(1-\mathrm{j})
        \end{aligned}
    \end{equation}
\end{document}

Body:
Maybe use a single align and then excludes all lines which don't need their own equation number with \notag?

\documentclass[10pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{graphicx}
\begin{document}
    \begin{align}
        G_{1}^{e x}=& \sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l^{\prime}} A_{j k l} Y^{j} Z^{k} U^{\prime} \\
            G_{2}^{e x}=&-\sum_{2}^{j^{\prime}} A_{j 00} /(1-j)+\sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l^{\prime}} \\
            &\left\{A_{j k l} Y^{j} Z^{k} U^{l}\{1+(j-k) /[Y(1-j)]\}\right\} \notag\\
            G_{3}^{e x}=&-\sum_{2} \sum_{0} A_{j k 0} /(1-j)+\sum_{2} \sum_{0} \sum_{0} \\
            &\{A _ { j k l } Y ^ { j } Z ^ { k } U ^ { l } \{1+(j-k) /[Y(1-j)]\notag\\
            &+(k-l) /[Y Z(1-j)]\}\} \notag\\
            %G_{4}^{e x}=&-\sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l^{\prime}} A_{j k l} /(1-j)+\sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l^{\prime}} \\
            %   &\left\{A _ { j k l } Y ^ { j } Z ^ { k } U ^ { l } \left\{1+(j-k) /[Y(1-j)]\right.\\
            %   &+(k-l) /[Y Z(1-j)]+l /[Y Z U(1-j)]\}\}
            G_{4}^{e x}=&-\sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l^{\prime}} A_{\mathrm{jkl}} \mathrm{Y} /(1-\mathrm{j})-\sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l} A_{\mathrm{jkl}} \mathrm{Y}^{\mathrm{j}} \mathrm{Z} \mathrm{T}^{\mathrm{j}} \\
            &\{1+[(\mathrm{j}-\mathrm{k}) / \mathrm{Y}(1-\mathrm{j})]+[(\mathrm{k}-1) / \mathrm{YZ}(1-\mathrm{j})]+\notag\\
            &[1 / \mathrm{YZT}(1-\mathrm{j})]\}\notag\\
            G^{e x}=&-\sum_{2}^{j^{\prime}} A_{\mathrm{j} 00} \mathrm{Y} /(1-\mathrm{j})-\sum_{2}^{j^{\prime}} \sum_{1}^{k^{\prime}} A_{\mathrm{jk} 0} \mathrm{YZ} /(1-\mathrm{j})-\\
            & \sum_{2}^{j^{\prime}} \sum_{1}^{k^{\prime}} \sum_{1}^{l^{\prime}} A_{\mathrm{jkl}} \mathrm{YZT} /(1-\mathrm{j})+\notag\\
            & \sum_{2}^{j^{\prime}} \sum_{0}^{k^{\prime}} \sum_{0}^{l^{\prime}} A_{\mathrm{jkl}} \mathrm{Y}^{\mathrm{j}} \mathrm{Z}^{\mathrm{k}} \mathrm{T}^{1} /(1-\mathrm{j})\notag
        \end{align}
\end{document}


问:
Maximum String Mismatches in Java
I was recently going through a question in codehub and I was unable to solve this query. Can anyone help me how can this be solved?

You are given a string S of length N. You can select and reverse any substring of S of any length. You are allowed to perform this operation many number of times.

Determine maximum number of mismatches by performing operation.

Mismatch(S) is defined as number of corresponding positions were characters are different in S and reverse(S). For example : S = abab, reverse(S) = baba. Number of mismatches = 4. S= abca. Number of mismatches = 2.

Pseudo code :

```<code>static int solve( String S, int n)
{
//To do
}
</code>```

Will be helpful if some one can explain once the code is done how this can be interpreted more easily and approached to solve.

答:
First a function to calculate the mismatch score, using this spec:

Mismatch(S) is defined as number of corresponding positions were characters are different in S and reverse(S). For example : S = abab, reverse(S) = baba. Number of mismatches = 4. S= abca. Number of mismatches = 2.

We don't need to actually reverse the string. Just compare the first character with the last, then the second with the second last, etc. I find it straightforward to use two index variables for something like this:

```<code>int mismatches(String s) {
    int result = 0;
    int i = 0;
    int j = s.length() - 1;
    while (j >= 0) {
        if (s.charAt(i) != s.charAt(j)) result++;
        i++;
        j--;
    }
    return result;
}
</code>```

And here are some tests to increase our confidence:

```<code>@Test
public void test_mismatches() {
    assertEquals(0, mismatches(""));
    assertEquals(0, mismatches("a"));
    assertEquals(0, mismatches("aa"));
    assertEquals(2, mismatches("ab"));
    assertEquals(0, mismatches("aaa"));
    assertEquals(2, mismatches("aab"));
    assertEquals(2, mismatches("abc"));
    assertEquals(0, mismatches("aaaa"));
    assertEquals(2, mismatches("aaab"));
    assertEquals(2, mismatches("aaba"));
    assertEquals(4, mismatches("abcd"));
}
</code>```

Now let's find the max mismatch. Here is the spec:

You are given a string S of length N. You can select and reverse any
substring of S of any length. You are allowed to perform this
operation many number of times.

Determine maximum number of mismatches by performing operation.

This is unclear and has typos. It is lazily written and if it was client work, I would be asking for a clarification. I've been burned in the past by working from unclear specs, and building something that the client didn't intend.

I think the use of the word "reverse" is a misnomer. I think it is to help hint at a solution for calculating the mismatch. The spec should be:

You are given a string. Determine maximum number of mismatches from any substring. For clarity, the original string is a valid substring of itself.

With this revised spec, we can just use a nested for loop to traverse the search space:

```<code>int maxMismatches(String s) {
    int result = 0;
    for (int i = 0; i < s.length(); i++)
        for (int j = s.length(); j > i; j--) {
            int mismatch = mismatches(s.substring(i, j));
            if (mismatch > result)
                result = mismatch;
        }
    return result;
}
</code>```

And some tests:

```<code>@Test
public void test_max_mismatches() {
    assertEquals(0, maxMismatches(""));
    assertEquals(0, maxMismatches("a"));
    assertEquals(0, maxMismatches("aa"));
    assertEquals(2, maxMismatches("ab"));
    assertEquals(2, maxMismatches("aba"));
    assertEquals(4, maxMismatches("aabbaa"));
    assertEquals(6, maxMismatches("aaabcda"));
}
</code>```

There is a gap in this set of tests. Some of the test strings require truncating the start to find the max. Some require truncating the end, but none require truncating both the start and end.

Both functions have obvious optimisations but they reduce clarity in a scenario where I don't think performance is important.

Title: Maximum String Mismatches in Java

Body:
I was recently going through a question in codehub and I was unable to solve this query. Can anyone help me how can this be solved?

You are given a string S of length N. You can select and reverse any substring of S of any length. You are allowed to perform this operation many number of times.

Determine maximum number of mismatches by performing operation.

Mismatch(S) is defined as number of corresponding positions were characters are different in S and reverse(S). For example : S = abab, reverse(S) = baba. Number of mismatches = 4. S= abca. Number of mismatches = 2.

Pseudo code :

static int solve( String S, int n)
{
//To do
}

Will be helpful if some one can explain once the code is done how this can be interpreted more easily and approached to solve.

Body:
First a function to calculate the mismatch score, using this spec:

Mismatch(S) is defined as number of corresponding positions were characters are different in S and reverse(S). For example : S = abab, reverse(S) = baba. Number of mismatches = 4. S= abca. Number of mismatches = 2.

We don't need to actually reverse the string. Just compare the first character with the last, then the second with the second last, etc. I find it straightforward to use two index variables for something like this:

int mismatches(String s) {
    int result = 0;
    int i = 0;
    int j = s.length() - 1;
    while (j >= 0) {
        if (s.charAt(i) != s.charAt(j)) result++;
        i++;
        j--;
    }
    return result;
}

And here are some tests to increase our confidence:

@Test
public void test_mismatches() {
    assertEquals(0, mismatches(""));
    assertEquals(0, mismatches("a"));
    assertEquals(0, mismatches("aa"));
    assertEquals(2, mismatches("ab"));
    assertEquals(0, mismatches("aaa"));
    assertEquals(2, mismatches("aab"));
    assertEquals(2, mismatches("abc"));
    assertEquals(0, mismatches("aaaa"));
    assertEquals(2, mismatches("aaab"));
    assertEquals(2, mismatches("aaba"));
    assertEquals(4, mismatches("abcd"));
}

Now let's find the max mismatch. Here is the spec:

You are given a string S of length N. You can select and reverse any
substring of S of any length. You are allowed to perform this
operation many number of times.

Determine maximum number of mismatches by performing operation.

This is unclear and has typos. It is lazily written and if it was client work, I would be asking for a clarification. I've been burned in the past by working from unclear specs, and building something that the client didn't intend.

I think the use of the word "reverse" is a misnomer. I think it is to help hint at a solution for calculating the mismatch. The spec should be:

You are given a string. Determine maximum number of mismatches from any substring. For clarity, the original string is a valid substring of itself.

With this revised spec, we can just use a nested for loop to traverse the search space:

int maxMismatches(String s) {
    int result = 0;
    for (int i = 0; i < s.length(); i++)
        for (int j = s.length(); j > i; j--) {
            int mismatch = mismatches(s.substring(i, j));
            if (mismatch > result)
                result = mismatch;
        }
    return result;
}

And some tests:

@Test
public void test_max_mismatches() {
    assertEquals(0, maxMismatches(""));
    assertEquals(0, maxMismatches("a"));
    assertEquals(0, maxMismatches("aa"));
    assertEquals(2, maxMismatches("ab"));
    assertEquals(2, maxMismatches("aba"));
    assertEquals(4, maxMismatches("aabbaa"));
    assertEquals(6, maxMismatches("aaabcda"));
}

There is a gap in this set of tests. Some of the test strings require truncating the start to find the max. Some require truncating the end, but none require truncating both the start and end.

Both functions have obvious optimisations but they reduce clarity in a scenario where I don't think performance is important.


问:
how to push huge data in less time from Database table to Elastic search using log stash
I'm processing the 500 000 records from Postgres database to elastic using Logstash but it taking 40 minutes to completed the process. I want to reduce the process time and i have changed the pipeline.batch.size: 1000, pipeline.batch.delay: 50 in logstash.yml file and increase the heap space 1 gb to 2 gb in the JVM.options file still processing the records in same time.

Conf file

```<code>input {
  jdbc {
    jdbc_driver_library => "C:\Users\Downloads\elk stack/postgresql-42.3.1.jar"
    jdbc_driver_class => "org.postgresql.Driver"
    jdbc_connection_string => "jdbc:postgresql://localhost:5432/postgres"
    jdbc_user => "postgres"
    jdbc_password => "postgres123"
    statement => "SELECT * FROM jolap.order_desk_activation"
  }
}

output {
    elasticsearch {
        hosts =>["http://localhost:9200/"]

        index => "test-powerbi-transformed"
        document_type => "_doc"

    }
    stdout {}
}
</code>```

答:
The problem is not the logstash pipeline or the batch size. As above suggested, u need to get volume is less time.

This can be achieved using "Parallel Hints" which makes the query superfast, as the query start using the core processor the DB infrastructure (Dont miss to consult your DBA before applying this). Once u start getting volume records in less time, you can scale your logstash or tweak the pipeline settings.
Refer to this link.

Body:
I'm processing the 500 000 records from Postgres database to elastic using Logstash but it taking 40 minutes to completed the process. I want to reduce the process time and i have changed the pipeline.batch.size: 1000, pipeline.batch.delay: 50 in logstash.yml file and increase the heap space 1 gb to 2 gb in the JVM.options file still processing the records in same time.

Conf file

input {
  jdbc {
    jdbc_driver_library => "C:\Users\Downloads\elk stack/postgresql-42.3.1.jar"
    jdbc_driver_class => "org.postgresql.Driver"
    jdbc_connection_string => "jdbc:postgresql://localhost:5432/postgres"
    jdbc_user => "postgres"
    jdbc_password => "postgres123"
    statement => "SELECT * FROM jolap.order_desk_activation"
  }
}

output {
    elasticsearch {
        hosts =>["http://localhost:9200/"]

        index => "test-powerbi-transformed"
        document_type => "_doc"

    }
    stdout {}
}


问:
Fatal error: Call to a member function query() on a non-object in /var/www/likeslomakkeet/controllers/petitions_controller.php on line 33
I'm getting:
Fatal error: Call to a member function query() on a non-object in /var/www/likeslomakkeet/controllers/petitions_controller.php on line 33

with the code below. I'm not sure why as I have also defined $name correctly in the model with var $name = 'Petition';
The error comes out when I put custom query.

Anyone has any suggestions?

```<code>function index() {
        if ($this->Session->read('Auth.User.group_id') != 1) {
            $commune_id = $this->Session->read('Auth.User.commune_id');
            $commune_id = $this->Petition->Commune->findbyId($commune_id);
            $commune_id = $this->Petition->Commune->find('all',array('conditions' => array('group' => $commune_id['Commune']['group'])));
            debug($commune_id);
            $count = count($commune_id);
            $i=1;
            $sql = "SELECT * FROM `petitions` WHERE `commune_id` = ";
            foreach($commune_id as $commune_ids){
                if($i==1){
                $sql .= $commune_ids['Commune']['id'];
                }else{
                $sql .= " OR `commune_id` = ".$commune_ids['Commune']['id'];
                }
            /*if($i != $count){
            $this->paginate = array(
                'or' => array(
                    array('Petition.commune_id LIKE' => $commune_ids['Commune']['id'] . ","),
                    //array('Petition.commune_id LIKE' => "," . $commune_ids['Commune']['id'] . ",")
                    ),
                'limit' => 10
            );
            }*/
            $i++;
            }
            $query = $this->Petiton->query($sql);
            debug($query);
        }
        $this->Petition->recursive = 0;
        $petitions = $this->paginate();
        $this->set('petitions', $petitions);
    }
</code>```

答:
I have one:

```<code>$this->Petiton
          ^^^
</code>```

Add an i.

Body:
I'm getting:
Fatal error: Call to a member function query() on a non-object in /var/www/likeslomakkeet/controllers/petitions_controller.php on line 33

with the code below. I'm not sure why as I have also defined $name correctly in the model with var $name = 'Petition';
The error comes out when I put custom query.

Anyone has any suggestions?

function index() {
        if ($this->Session->read('Auth.User.group_id') != 1) {
            $commune_id = $this->Session->read('Auth.User.commune_id');
            $commune_id = $this->Petition->Commune->findbyId($commune_id);
            $commune_id = $this->Petition->Commune->find('all',array('conditions' => array('group' => $commune_id['Commune']['group'])));
            debug($commune_id);
            $count = count($commune_id);
            $i=1;
            $sql = "SELECT * FROM `petitions` WHERE `commune_id` = ";
            foreach($commune_id as $commune_ids){
                if($i==1){
                $sql .= $commune_ids['Commune']['id'];
                }else{
                $sql .= " OR `commune_id` = ".$commune_ids['Commune']['id'];
                }
            /*if($i != $count){
            $this->paginate = array(
                'or' => array(
                    array('Petition.commune_id LIKE' => $commune_ids['Commune']['id'] . ","),
                    //array('Petition.commune_id LIKE' => "," . $commune_ids['Commune']['id'] . ",")
                    ),
                'limit' => 10
            );
            }*/
            $i++;
            }
            $query = $this->Petiton->query($sql);
            debug($query);
        }
        $this->Petition->recursive = 0;
        $petitions = $this->paginate();
        $this->set('petitions', $petitions);
    }

Body:
I have one:

$this->Petiton
          ^^^

Add an i.


问:
Get IP address from hosts in a Group
I have a simple playbook referencing an inventory hosts.yml file.  I want to be able to query a group, and retrieve the IP address for hosts in that group.

Simple hosts.yml

---
all:
  hosts:
    w2k16-std:
      ansible_host: 10.1.1.12
      in_play_ip: 10.200.2.12
    w2k12-x64:
      ansible_host: 10.1.1.13
      in_play_ip: 10.200.2.13
    lin-test:
      ansible_host: 10.1.1.20
      in_play_ip: 10.200.2.20
  children:
    windows:
      vars:
        ansible_connection: winrm
        ansible_winrm_transport: certificate
        ansible_winrm_cert_pem: /home/user/.ssh/windows.pem
        ansible_winrm_cert_key_pem: /home/user/.ssh/windows_key.pem
        ansible_port: 5986
        ansible_winrm_scheme: https
        ansible_winrm_server_cert_validation: ignore
      hosts:
        w2k12-x64:
        w2k16-std:
    linux:
      hosts:
        lin-test:
    targets:
      hosts:
        w2k12-x64:
        w2k16-std:
```
<p><strong>Here's the simple playbook:</strong></p>
<pre class="lang-yaml prettyprint-override"><code>---
- hosts: kali
  vars:
  tasks:
    - name: Create comma delimited list of target names from targets group.
      set_fact:
        targets: "{{ groups.targets | list | join(',') }}"

    - name: List targets from Inventory
      debug:
        var: targets
</code>```

Produces the following output:

```<code>TASK [List targets from Inventory] ***************************************
ok: [lin-test] => {
    "targets": "w2k12-x64,w2k16-std"
</code>```

I want be able do the following:

Retrieve the members of the targets group (w2k12-x64 & w2k16-std)

Get the IP address listed in ansible_host values.

Create a comma delimited list of the target's IPs (10.1.1.12,10.1.1.13).

So far I can:

Retrieve the members of the targets group (w2k12-x64 & w2k16-std)

Create a comma delimited list of the target names.

I'm not sure if my hosts file is correctly laid out, or if I just need help with the query?

Desired output:

Produce the following output:

```<code>TASK [List target IPs from Inventory] ***************************************
ok: [lin-test] => {
    "targets": "10.1.1.12,10.1.1.13"
</code>```

答:
You can extract the value you are looking for from the hostvars special variable.

You can also filter the items of the dictionary hostvars contained in the group targets thanks to the filters dict2items, which will create a key/value list from the dictionary, and selectattr to get only the items of the created list having a key matching in the targets group.

Then, you just need to reduce the list of dictionaries to a simple list via map, because you are only interested in the ansible_host attribute, and join the whole thing together.

So, this end up with this single task:

- debug:
    msg: >-
      {{
        hostvars
          | dict2items
          | selectattr('key', 'in', groups.targets)
          | map(attribute="value.ansible_host")
          | join(',')
      }}
```
<p>Which yields your expected:</p>
<pre class="lang-none prettyprint-override"><code>TASK [debug] **************************************************************
ok: [localhost] =>
  msg: 10.1.1.12,10.1.1.13
</code>```

Title: Get IP address from hosts in a Group

Body:
I have a simple playbook referencing an inventory hosts.yml file.  I want to be able to query a group, and retrieve the IP address for hosts in that group.

Simple hosts.yml

---
all:
  hosts:
    w2k16-std:
      ansible_host: 10.1.1.12
      in_play_ip: 10.200.2.12
    w2k12-x64:
      ansible_host: 10.1.1.13
      in_play_ip: 10.200.2.13
    lin-test:
      ansible_host: 10.1.1.20
      in_play_ip: 10.200.2.20
  children:
    windows:
      vars:
        ansible_connection: winrm
        ansible_winrm_transport: certificate
        ansible_winrm_cert_pem: /home/user/.ssh/windows.pem
        ansible_winrm_cert_key_pem: /home/user/.ssh/windows_key.pem
        ansible_port: 5986
        ansible_winrm_scheme: https
        ansible_winrm_server_cert_validation: ignore
      hosts:
        w2k12-x64:
        w2k16-std:
    linux:
      hosts:
        lin-test:
    targets:
      hosts:
        w2k12-x64:
        w2k16-std:

Here's the simple playbook:

---
- hosts: kali
  vars:
  tasks:
    - name: Create comma delimited list of target names from targets group.
      set_fact:
        targets: "{{ groups.targets | list | join(',') }}"

    - name: List targets from Inventory
      debug:
        var: targets

Produces the following output:

TASK [List targets from Inventory] ***************************************
ok: [lin-test] => {
    "targets": "w2k12-x64,w2k16-std"

I want be able do the following:

Retrieve the members of the targets group (w2k12-x64 & w2k16-std)

Get the IP address listed in ansible_host values.

Create a comma delimited list of the target's IPs (10.1.1.12,10.1.1.13).

So far I can:

Retrieve the members of the targets group (w2k12-x64 & w2k16-std)

Create a comma delimited list of the target names.

I'm not sure if my hosts file is correctly laid out, or if I just need help with the query?

Desired output:

Produce the following output:

TASK [List target IPs from Inventory] ***************************************
ok: [lin-test] => {
    "targets": "10.1.1.12,10.1.1.13"

Body:
You can extract the value you are looking for from the hostvars special variable.

You can also filter the items of the dictionary hostvars contained in the group targets thanks to the filters dict2items, which will create a key/value list from the dictionary, and selectattr to get only the items of the created list having a key matching in the targets group.

Then, you just need to reduce the list of dictionaries to a simple list via map, because you are only interested in the ansible_host attribute, and join the whole thing together.

So, this end up with this single task:

- debug:
    msg: >-
      {{
        hostvars
          | dict2items
          | selectattr('key', 'in', groups.targets)
          | map(attribute="value.ansible_host")
          | join(',')
      }}

Which yields your expected:

TASK [debug] **************************************************************
ok: [localhost] =>
  msg: 10.1.1.12,10.1.1.13


问:
toggle controlbar based on tab and action button
I'm trying to toggle the control bar using an actionLink in the top right (to basically copy what the gears icon is doing, and later I will remove the gears icon to just have one actionLink) and also to automate the toggling such that when the user clicks on feedback, the controlbar disappears and reappears when the user clicks on any other tab. I also want to make sure throughout this toggling, the controlbar does not overlay on the dashboard body (basically the dashboard body will resize appropriately whenever the control bar toggles).

This is what I've tried so far:

```<code>library(shiny)
library(shinydashboard)
library(shinydashboardPlus)
library(shinyWidgets)
library(shinyjs)

ui <-  dashboardPage(
    title = 'Test',
    header = dashboardHeader(
      title = span("Test"),
      titleWidth = 600,
      tags$li(
        id = 'right-sidebar-toggle-list-item',
        class = "dropdown",
        actionLink("rightSidebarToggle", "Select Population"))

    ), # end of dashboardheader

    sidebar = dashboardSidebar(
      sidebarMenu(id = "sidebar",
                  menuItem("Overview", tabName = "introduction", icon = icon("info")),
    menuItem("Feedback", tabName = "feedback", icon = icon("info")))),
       body = dashboardBody(plotOutput("cars")),
                            controlbar = dashboardControlbar(
                              id = "controlbar",
                              width = 270,
                              skin = "light",
                              collapsed = F,
                              overlay = F,
                              controlbarMenu(
                                id = "menu",
                                controlbarItem(
                                  ' ',
                                  # - select study
                                  checkboxGroupButtons(
                                    inputId = "select_study",
                                    label = "Select Study",
                                    choiceNames = c("1", "2"),
                                    choiceValues = c("1", "2"),
                                    selected = c("1", "2"),
                                    justified = TRUE,
                                    status = "primary",
                                    direction = "vertical",
                                    checkIcon = list(yes = icon("ok", lib = "glyphicon"))
                                  ),
                                )
                              )
                            )
  )

server <- function(input, output, session) {

  output$cars <- renderPlot({
 plot(mtcars)
  })

  # event to toggle right sidebar menu
  observeEvent(input$rightSidebarToggle, {
    shinyjs::toggleClass(selector = "aside.control-sidebar", class = "control-sidebar-open")
})

  ##### > Controlbar Collapse #####

  observeEvent(input[["sidebar"]], {
    if(input[["sidebar"]] == "feedback"){
      removeClass(selector = "aside.control-sidebar", class = "control-sidebar-open")
    }else{
      addClass(selector = "aside.control-sidebar", class = "control-sidebar-open")
      updateControlbar("controlbar")
    }
  })
}
shinyApp(ui, server)

</code>```

答:
There is no need to create a new actionLink and hide the existing a-tag. We can simply modify it.

Please check the following:

```<code>library(shiny)
library(shinydashboard)
library(shinydashboardPlus)
library(shinyWidgets)
library(shinyjs)

ui <-  dashboardPage(
  title = 'Test',
  header = dashboardHeader(
    title = span("Test"),
    titleWidth = 600,
    controlbarIcon = NULL
  ),
  sidebar = dashboardSidebar(sidebarMenu(
    id = "sidebar",
    menuItem("Overview", tabName = "introduction", icon = icon("info")),
    menuItem("Feedback", tabName = "feedback", icon = icon("info"))
  )),
  body = dashboardBody(
    useShinyjs(),
    tags$script(
      HTML(
        "var el = document.querySelector('body > div > header > nav > div:nth-child(4) > ul > li:last-child > a');
             el.innerHTML = 'Select Population';"
      )
    ),
    plotOutput("cars")
  ),
  controlbar = dashboardControlbar(
    id = "controlbar",
    width = 270,
    skin = "light",
    collapsed = FALSE,
    overlay = FALSE,
    controlbarMenu(id = "menu",
                   controlbarItem(' ',
                                  checkboxGroupButtons(
                                    inputId = "select_study",
                                    label = "Select Study",
                                    choiceNames = c("1", "2"),
                                    choiceValues = c("1", "2"),
                                    selected = c("1", "2"),
                                    justified = TRUE,
                                    status = "primary",
                                    direction = "vertical",
                                    checkIcon = list(yes = icon("ok", lib = "glyphicon"))
                                  )
                   )
    )
  )
)

server <- function(input, output, session) {
  output$cars <- renderPlot({
    plot(mtcars)
  })

  observeEvent(input[["sidebar"]], {
    if (input[["sidebar"]] == "feedback") {
      removeClass(selector = "body", class = "control-sidebar-open")
      shinyjs::runjs('Shiny.setInputValue(id = "controlbar", value = false);
                      $(window).trigger("resize");')
    } else {
      addClass(selector = "body", class = "control-sidebar-open")
      shinyjs::runjs('Shiny.setInputValue(id = "controlbar", value = true);
                      $(window).trigger("resize");')
    }
  }, ignoreInit = FALSE)
}
shinyApp(ui, server)
</code>```

Edit: Here is an UI-only approach not using library(shinyjs):

```<code>library(shiny)
library(shinydashboard)
library(shinydashboardPlus)
library(shinyWidgets)

ui <-  dashboardPage(
  title = 'Test',
  header = dashboardHeader(
    title = span("Test"),
    titleWidth = 600,
    controlbarIcon = NULL
  ),
  sidebar = dashboardSidebar(sidebarMenu(
    id = "sidebar",
    menuItem("Overview", tabName = "introduction", icon = icon("info")),
    menuItem("Feedback", tabName = "feedback", icon = icon("info"))
  )),
  body = dashboardBody(
    tags$script(
      HTML(
          "var el = document.querySelector('body > div > header > nav > div:nth-child(4) > ul > li:last-child > a');
             el.innerHTML = 'Select Population';
          $(document).on('shiny:connected', function(event) {
            $(window).trigger('resize'); // resize once on session start - needed when using collapsed = FALSE
          });
          $(document).on('shiny:inputchanged', function(event) {
            if (event.name === 'sidebar') {
              if (event.value === 'feedback') {
                document.querySelector('body').classList.remove('control-sidebar-open');
                Shiny.setInputValue(id = 'controlbar', value = false);
                $(window).trigger('resize');
              } else {
                document.querySelector('body').classList.add('control-sidebar-open');
                Shiny.setInputValue(id = 'controlbar', value = true);
                $(window).trigger('resize');
              }
            }
          });"
      )
    ),
    plotOutput("cars")
  ),
  controlbar = dashboardControlbar(
    id = "controlbar",
    width = 270,
    skin = "light",
    collapsed = FALSE,
    overlay = FALSE,
    controlbarMenu(id = "menu",
                   controlbarItem(' ',
                                  checkboxGroupButtons(
                                    inputId = "select_study",
                                    label = "Select Study",
                                    choiceNames = c("1", "2"),
                                    choiceValues = c("1", "2"),
                                    selected = c("1", "2"),
                                    justified = TRUE,
                                    status = "primary",
                                    direction = "vertical",
                                    checkIcon = list(yes = icon("ok", lib = "glyphicon"))
                                  )
                   )
    )
  )
)

server <- function(input, output, session) {
  output$cars <- renderPlot({
    plot(mtcars)
  })
}
shinyApp(ui, server)
</code>```

Body:
I'm trying to toggle the control bar using an actionLink in the top right (to basically copy what the gears icon is doing, and later I will remove the gears icon to just have one actionLink) and also to automate the toggling such that when the user clicks on feedback, the controlbar disappears and reappears when the user clicks on any other tab. I also want to make sure throughout this toggling, the controlbar does not overlay on the dashboard body (basically the dashboard body will resize appropriately whenever the control bar toggles).

This is what I've tried so far:

library(shiny)
library(shinydashboard)
library(shinydashboardPlus)
library(shinyWidgets)
library(shinyjs)

ui <-  dashboardPage(
    title = 'Test',
    header = dashboardHeader(
      title = span("Test"),
      titleWidth = 600,
      tags$li(
        id = 'right-sidebar-toggle-list-item',
        class = "dropdown",
        actionLink("rightSidebarToggle", "Select Population"))

    ), # end of dashboardheader

    sidebar = dashboardSidebar(
      sidebarMenu(id = "sidebar",
                  menuItem("Overview", tabName = "introduction", icon = icon("info")),
    menuItem("Feedback", tabName = "feedback", icon = icon("info")))),
       body = dashboardBody(plotOutput("cars")),
                            controlbar = dashboardControlbar(
                              id = "controlbar",
                              width = 270,
                              skin = "light",
                              collapsed = F,
                              overlay = F,
                              controlbarMenu(
                                id = "menu",
                                controlbarItem(
                                  ' ',
                                  # - select study
                                  checkboxGroupButtons(
                                    inputId = "select_study",
                                    label = "Select Study",
                                    choiceNames = c("1", "2"),
                                    choiceValues = c("1", "2"),
                                    selected = c("1", "2"),
                                    justified = TRUE,
                                    status = "primary",
                                    direction = "vertical",
                                    checkIcon = list(yes = icon("ok", lib = "glyphicon"))
                                  ),
                                )
                              )
                            )
  )

server <- function(input, output, session) {

  output$cars <- renderPlot({
 plot(mtcars)
  })

  # event to toggle right sidebar menu
  observeEvent(input$rightSidebarToggle, {
    shinyjs::toggleClass(selector = "aside.control-sidebar", class = "control-sidebar-open")
})

  ##### > Controlbar Collapse #####

  observeEvent(input[["sidebar"]], {
    if(input[["sidebar"]] == "feedback"){
      removeClass(selector = "aside.control-sidebar", class = "control-sidebar-open")
    }else{
      addClass(selector = "aside.control-sidebar", class = "control-sidebar-open")
      updateControlbar("controlbar")
    }
  })
}
shinyApp(ui, server)

Body:
There is no need to create a new actionLink and hide the existing a-tag. We can simply modify it.

Please check the following:

library(shiny)
library(shinydashboard)
library(shinydashboardPlus)
library(shinyWidgets)
library(shinyjs)

ui <-  dashboardPage(
  title = 'Test',
  header = dashboardHeader(
    title = span("Test"),
    titleWidth = 600,
    controlbarIcon = NULL
  ),
  sidebar = dashboardSidebar(sidebarMenu(
    id = "sidebar",
    menuItem("Overview", tabName = "introduction", icon = icon("info")),
    menuItem("Feedback", tabName = "feedback", icon = icon("info"))
  )),
  body = dashboardBody(
    useShinyjs(),
    tags$script(
      HTML(
        "var el = document.querySelector('body > div > header > nav > div:nth-child(4) > ul > li:last-child > a');
             el.innerHTML = 'Select Population';"
      )
    ),
    plotOutput("cars")
  ),
  controlbar = dashboardControlbar(
    id = "controlbar",
    width = 270,
    skin = "light",
    collapsed = FALSE,
    overlay = FALSE,
    controlbarMenu(id = "menu",
                   controlbarItem(' ',
                                  checkboxGroupButtons(
                                    inputId = "select_study",
                                    label = "Select Study",
                                    choiceNames = c("1", "2"),
                                    choiceValues = c("1", "2"),
                                    selected = c("1", "2"),
                                    justified = TRUE,
                                    status = "primary",
                                    direction = "vertical",
                                    checkIcon = list(yes = icon("ok", lib = "glyphicon"))
                                  )
                   )
    )
  )
)

server <- function(input, output, session) {
  output$cars <- renderPlot({
    plot(mtcars)
  })

  observeEvent(input[["sidebar"]], {
    if (input[["sidebar"]] == "feedback") {
      removeClass(selector = "body", class = "control-sidebar-open")
      shinyjs::runjs('Shiny.setInputValue(id = "controlbar", value = false);
                      $(window).trigger("resize");')
    } else {
      addClass(selector = "body", class = "control-sidebar-open")
      shinyjs::runjs('Shiny.setInputValue(id = "controlbar", value = true);
                      $(window).trigger("resize");')
    }
  }, ignoreInit = FALSE)
}
shinyApp(ui, server)

Edit: Here is an UI-only approach not using library(shinyjs):

library(shiny)
library(shinydashboard)
library(shinydashboardPlus)
library(shinyWidgets)

ui <-  dashboardPage(
  title = 'Test',
  header = dashboardHeader(
    title = span("Test"),
    titleWidth = 600,
    controlbarIcon = NULL
  ),
  sidebar = dashboardSidebar(sidebarMenu(
    id = "sidebar",
    menuItem("Overview", tabName = "introduction", icon = icon("info")),
    menuItem("Feedback", tabName = "feedback", icon = icon("info"))
  )),
  body = dashboardBody(
    tags$script(
      HTML(
          "var el = document.querySelector('body > div > header > nav > div:nth-child(4) > ul > li:last-child > a');
             el.innerHTML = 'Select Population';
          $(document).on('shiny:connected', function(event) {
            $(window).trigger('resize'); // resize once on session start - needed when using collapsed = FALSE
          });
          $(document).on('shiny:inputchanged', function(event) {
            if (event.name === 'sidebar') {
              if (event.value === 'feedback') {
                document.querySelector('body').classList.remove('control-sidebar-open');
                Shiny.setInputValue(id = 'controlbar', value = false);
                $(window).trigger('resize');
              } else {
                document.querySelector('body').classList.add('control-sidebar-open');
                Shiny.setInputValue(id = 'controlbar', value = true);
                $(window).trigger('resize');
              }
            }
          });"
      )
    ),
    plotOutput("cars")
  ),
  controlbar = dashboardControlbar(
    id = "controlbar",
    width = 270,
    skin = "light",
    collapsed = FALSE,
    overlay = FALSE,
    controlbarMenu(id = "menu",
                   controlbarItem(' ',
                                  checkboxGroupButtons(
                                    inputId = "select_study",
                                    label = "Select Study",
                                    choiceNames = c("1", "2"),
                                    choiceValues = c("1", "2"),
                                    selected = c("1", "2"),
                                    justified = TRUE,
                                    status = "primary",
                                    direction = "vertical",
                                    checkIcon = list(yes = icon("ok", lib = "glyphicon"))
                                  )
                   )
    )
  )
)

server <- function(input, output, session) {
  output$cars <- renderPlot({
    plot(mtcars)
  })
}
shinyApp(ui, server)


问:
How to build regex to match values if they exists
I have a requirement to match the complete string if some part of value exists or not

For example :- Here are the list of strings that should be matched

en.key.value
fr.key.value
es.key.value
pt.key.value
key.value

So, length of string before first . can only be >=2.

Below are some values which should not be accepted

.key.value
z.key.value

Could someone please help ?
Thanks in advance

答:
You could use the following regex : /[a-z]{2,}\.[a-z]+\.[a-z]+/g

[a-z]{2,} matches 2 or more repetitions of characters in the range between a and z.

\. matches the dot character.

[a-z]+ matches 1 or more repetitions of characters between a and z.

let regex = /[a-z]{2,}\.[a-z]+\.[a-z]+/g;

console.log(regex.test("fr.key.value"));
console.log(regex.test("z.key.value"));```

Regex101.

Body:
You could use the following regex : /[a-z]{2,}\.[a-z]+\.[a-z]+/g

[a-z]{2,} matches 2 or more repetitions of characters in the range between a and z.

\. matches the dot character.

[a-z]+ matches 1 or more repetitions of characters between a and z.

let regex = /[a-z]{2,}\.[a-z]+\.[a-z]+/g;

console.log(regex.test("fr.key.value"));
console.log(regex.test("z.key.value"));

Regex101.


问:
Why bottom sheet not work with bottom navigation in jetpack compose?
I try to learn jetpack compose these days, and I have a simple project in jetpack compose, bottom sheet work in my project, but when I use bottom navigation, it is not work, I search in many website and stackoverflow especially, but I did not find any solution, I do not know what I missed? is there any idea?

```<code> @Composable
fun BSDataScreen() {
    val modalBottomSheetState = rememberModalBottomSheetState(initialValue =
 ModalBottomSheetValue.Hidden)
    val scope = rememberCoroutineScope()

    ModalBottomSheetLayout(
        sheetContent = {

            SheetScreen()
        },
        sheetState = modalBottomSheetState,
        sheetShape = RoundedCornerShape(topStart = 15.dp, topEnd = 15.dp),
        sheetBackgroundColor = Color.White,

    ) {
        Scaffold(

            backgroundColor =  Color.White,
        ) {
            DataScreen(
                scope = scope, state = modalBottomSheetState)}}}

@Composable
fun DataScreen(
    scope: CoroutineScope,
    state: ModalBottomSheetState
  ) {

    val listOfData = listOf(
        Data( painterResource(R.drawable.image1)),
        Data(painterResource(R.drawable.image2)),
        Data(painterResource(R.drawable.image3),)

    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)

    ) {

        LazyColumn(
            modifier = Modifier

        ) {

            items(listOfData.size) { index ->
                DataListItem(listOfData[index]) data: Data->

        scope.launch {
            state.show()
        }

     }}}}

@Composable
fun DataListItem(data: Data, onLongClick: (Data) -> Unit) {

    val context = LocalContext.current

    Column(
        modifier = Modifier.padding(5.dp)
    ) {

        Row(

            modifier = Modifier
                .fillMaxWidth()
                .padding(5.dp)
                .combinedClickable(
                    onLongClick= {
               onLongClick(data)
     },)

        ) {

            Image(
                painter = data.painter,
                contentDescription = null,)}}}

</code>```

BottomNav:

```<code>class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MainScreen()
        }
    }
}

@Composable
fun MainScreen() {
    val navController = rememberNavController()
    Scaffold(

        bottomBar = { BottomNavigationBar(navController) }
    ) {
        Navigation(navController = navController)
    }
}

 @Composable
 fun Navigation(navController: NavHostController) {
     val modalBottomSheetState = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)
     val scope = rememberCoroutineScope()
    NavHost(navController, startDestination = NavigationItem.Data.route) {

        composable(NavigationItem.Data.route) {
          DataScreen(
              scope = scope, state = modalBottomSheetState
          )

        }
        composable(NavigationItem.Data2.route) {
            Data2Screen()
        }
        composable(NavigationItem.Data3.route) {
            Data3Screen()
        }
        composable(NavigationItem.Data4.route) {
            Data4Screen()
        }
        composable(NavigationItem.Data5.route) {
            Data5Screen()
        }
    }
 }

@Composable
fun BottomNavigationBar(navController: NavController

    ) {
    val items = listOf(
        NavigationItem.Data,
        NavigationItem.Data2,
        NavigationItem.Data3,
        NavigationItem.Data4,
        NavigationItem.Data5

    )

    BottomNavigation(
        backgroundColor = colorResource(id = R.color.white),
        contentColor = colorResource(id = R.color.black)

    ) {
        val navBackStackEntry by navController.currentBackStackEntryAsState()
        val currentRoute = navBackStackEntry?.destination?.route
        items.forEach { item ->
            BottomNavigationItem(
                icon = {
                    Icon(
                        painterResource(id = item.icon),
                        contentDescription = null
                    )
                },
                selectedContentColor = colorResource(id = R.color.red),
                unselectedContentColor = colorResource(id = R.color.blue),
                alwaysShowLabel = true,
                selected = currentRoute == item.route,
                onClick = {
                    navController.navigate(item.route) {

                        navController.graph.startDestinationRoute?.let { route ->
                            popUpTo(route) {
                                saveState = true
                            }
                        }

                        launchSingleTop = true

                        restoreState = true
                    }})}}}

</code>```

答:
Just wrap the whole screen with ModalBottomSheetLayout.

You can put the following code:

```<code>Scaffold(

        bottomBar = { BottomNavigationBar(navController) }
    ) {
        Navigation(navController = navController)
    }
</code>```

inside

```<code>ModalBottomSheetLayout(...){
    Scaffold(

        bottomBar = { BottomNavigationBar(navController) }
    ) {
        Navigation(navController = navController)
    }
}
</code>```

Body:
I try to learn jetpack compose these days, and I have a simple project in jetpack compose, bottom sheet work in my project, but when I use bottom navigation, it is not work, I search in many website and stackoverflow especially, but I did not find any solution, I do not know what I missed? is there any idea?

 @Composable
fun BSDataScreen() {
    val modalBottomSheetState = rememberModalBottomSheetState(initialValue =
 ModalBottomSheetValue.Hidden)
    val scope = rememberCoroutineScope()

    ModalBottomSheetLayout(
        sheetContent = {

            SheetScreen()
        },
        sheetState = modalBottomSheetState,
        sheetShape = RoundedCornerShape(topStart = 15.dp, topEnd = 15.dp),
        sheetBackgroundColor = Color.White,

    ) {
        Scaffold(

            backgroundColor =  Color.White,
        ) {
            DataScreen(
                scope = scope, state = modalBottomSheetState)}}}

@Composable
fun DataScreen(
    scope: CoroutineScope,
    state: ModalBottomSheetState
  ) {

    val listOfData = listOf(
        Data( painterResource(R.drawable.image1)),
        Data(painterResource(R.drawable.image2)),
        Data(painterResource(R.drawable.image3),)

    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)

    ) {

        LazyColumn(
            modifier = Modifier

        ) {

            items(listOfData.size) { index ->
                DataListItem(listOfData[index]) data: Data->

        scope.launch {
            state.show()
        }

     }}}}

@Composable
fun DataListItem(data: Data, onLongClick: (Data) -> Unit) {

    val context = LocalContext.current

    Column(
        modifier = Modifier.padding(5.dp)
    ) {

        Row(

            modifier = Modifier
                .fillMaxWidth()
                .padding(5.dp)
                .combinedClickable(
                    onLongClick= {
               onLongClick(data)
     },)

        ) {

            Image(
                painter = data.painter,
                contentDescription = null,)}}}

BottomNav:

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MainScreen()
        }
    }
}

@Composable
fun MainScreen() {
    val navController = rememberNavController()
    Scaffold(

        bottomBar = { BottomNavigationBar(navController) }
    ) {
        Navigation(navController = navController)
    }
}

 @Composable
 fun Navigation(navController: NavHostController) {
     val modalBottomSheetState = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)
     val scope = rememberCoroutineScope()
    NavHost(navController, startDestination = NavigationItem.Data.route) {

        composable(NavigationItem.Data.route) {
          DataScreen(
              scope = scope, state = modalBottomSheetState
          )

        }
        composable(NavigationItem.Data2.route) {
            Data2Screen()
        }
        composable(NavigationItem.Data3.route) {
            Data3Screen()
        }
        composable(NavigationItem.Data4.route) {
            Data4Screen()
        }
        composable(NavigationItem.Data5.route) {
            Data5Screen()
        }
    }
 }

@Composable
fun BottomNavigationBar(navController: NavController

    ) {
    val items = listOf(
        NavigationItem.Data,
        NavigationItem.Data2,
        NavigationItem.Data3,
        NavigationItem.Data4,
        NavigationItem.Data5

    )

    BottomNavigation(
        backgroundColor = colorResource(id = R.color.white),
        contentColor = colorResource(id = R.color.black)

    ) {
        val navBackStackEntry by navController.currentBackStackEntryAsState()
        val currentRoute = navBackStackEntry?.destination?.route
        items.forEach { item ->
            BottomNavigationItem(
                icon = {
                    Icon(
                        painterResource(id = item.icon),
                        contentDescription = null
                    )
                },
                selectedContentColor = colorResource(id = R.color.red),
                unselectedContentColor = colorResource(id = R.color.blue),
                alwaysShowLabel = true,
                selected = currentRoute == item.route,
                onClick = {
                    navController.navigate(item.route) {

                        navController.graph.startDestinationRoute?.let { route ->
                            popUpTo(route) {
                                saveState = true
                            }
                        }

                        launchSingleTop = true

                        restoreState = true
                    }})}}}

Body:
Just wrap the whole screen with ModalBottomSheetLayout.

You can put the following code:

Scaffold(

        bottomBar = { BottomNavigationBar(navController) }
    ) {
        Navigation(navController = navController)
    }

inside

ModalBottomSheetLayout(...){
    Scaffold(

        bottomBar = { BottomNavigationBar(navController) }
    ) {
        Navigation(navController = navController)
    }
}


问:
Retrieve CollectionGroup Using Query and adding the data to a dynamic List using Factory in Flutter
I am trying to save data from a CollectionGroup  called 'songs' in my FirebaseFirestore to a dynamic list using a Factory. I have a method called 'getAllSongsFromCloud()' and a Class called 'Song' that makes use of a Factory.
My Database structure looks like this.

I have a collection called 'artists' and each document in there is an artist,
Each artist then has a collection called 'songs'. And this is the collection with documents of type song that I am interested in.

Here's a code snippet

```<code>class Song {
 final String cTitle, cPic, id, cPrice;
 final int cQuantity;

Song({
required this.cTitle,
required this.cPic,
required this.cPrice,
required this.id,
required this.cQuantity,
});

factory Song.fromJson(Map<String, dynamic> json)  {

return Song(
  cTitle: json['title'],
  cPic: json['songPoster'],
  cPrice: json['price'], id: json['id'],
  cQuantity: 1,
);
}
}
</code>```

This is the list of type 'Song' in which I want to store the data

```<code> List<Song> _songs = [];

 List<Song> getAllSongs() {
 return [..._songs];
</code>```

}

and here is the method I'm using to query the data from all collections called 'songs'
and add them to a list called '_songs'

```<code>Future<void>getAllSongsFromCloud()async {

FirebaseFirestore? _instance;
_instance = FirebaseFirestore.instance;
Query<Map<String, dynamic>> songs =  _instance.collectionGroup('songs');
QuerySnapshot<Map<String, dynamic>> snapshot = await songs.get();

snapshot.docs.forEach((item){

  Song sng = Song.fromJson(item.data());

    _songs.add(sng);

  });
  }
</code>```

This is what I get when I print the list '_songs'

flutter: [Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song']

答: If you get [Instance of 'Song'...] is because the parse operation worked right. If you want to see Song contains in your print() you need to override toString() method in your Song class.

Body:
I am trying to save data from a CollectionGroup  called 'songs' in my FirebaseFirestore to a dynamic list using a Factory. I have a method called 'getAllSongsFromCloud()' and a Class called 'Song' that makes use of a Factory.
My Database structure looks like this.

I have a collection called 'artists' and each document in there is an artist,
Each artist then has a collection called 'songs'. And this is the collection with documents of type song that I am interested in.

Here's a code snippet

class Song {
 final String cTitle, cPic, id, cPrice;
 final int cQuantity;

Song({
required this.cTitle,
required this.cPic,
required this.cPrice,
required this.id,
required this.cQuantity,
});

factory Song.fromJson(Map<String, dynamic> json)  {

return Song(
  cTitle: json['title'],
  cPic: json['songPoster'],
  cPrice: json['price'], id: json['id'],
  cQuantity: 1,
);
}
}

This is the list of type 'Song' in which I want to store the data

 List<Song> _songs = [];

 List<Song> getAllSongs() {
 return [..._songs];

}

and here is the method I'm using to query the data from all collections called 'songs'
and add them to a list called '_songs'

Future<void>getAllSongsFromCloud()async {

FirebaseFirestore? _instance;
_instance = FirebaseFirestore.instance;
Query<Map<String, dynamic>> songs =  _instance.collectionGroup('songs');
QuerySnapshot<Map<String, dynamic>> snapshot = await songs.get();

snapshot.docs.forEach((item){

  Song sng = Song.fromJson(item.data());

    _songs.add(sng);

  });
  }

This is what I get when I print the list '_songs'

flutter: [Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song']


答:
get total lines from your file

Use a database or file and store a random number daily.

Use that number to read a random message from the file.

Use cron to update random numbers at midnight in your database or file.

So, for 24 hours the same message will be displayed.

```<code>function getRandomNo(): int {
    $path = ROOT_PATH. '/randomno.txt';
    $file = fopen($path,"r");
    $data = fread($file,100);
    fclose($file);

    if($data) {
        $parts = explode('=',$data);
        if($parts[0] != date("Y-m-d")) {
            $randomNo = rand(0,100);
            overWrite($randomNo);
        } else {
            $randomNo = $parts[1];
        }
    } else {
        $randomNo = rand(0,100);
        overWrite($randomNo);
    }

    return $randomNo;
}

function overWrite(int $randomNo): void {
    $path = ROOT_PATH. '/randomno.txt';
    $file = fopen($path,"w+");
    $data = date("Y-m-d").'='.$randomNo;
    fwrite($file, $data);
    fclose($file);
}

$messages_from_file = loadMessagesFromFile();
$key = getRandomNo();
$full_text = $messages_from_file[$key];
</code>```

Title: How to display a different message read from a file every day of the week in php?

Body:
I have a php function that reads a line (random message) from a file and displays it on my web page. It displays a new message every time I click refresh, but I want it to display the message for a day (it should change at midnight). Is it possible to do it with another function, implying my database? Or with a JS function?

EDIT
This is the function (not my code):

function loadMessagesFromFile()
{
    $path = ROOT_PATH. '/messages.txt';
    $file = fopen($path,"r");
    $messages = array();
    while($data = fgets($file))
    {
        $messages[] = $data;
    }
    fclose($file);
    return $messages;
}

This is how I use it to display the message:

$messages_from_file = loadMessagesFromFile();
$key = array_rand($messages_from_file);
$full_text = $messages_from_file[$key];

LATER EDIT

I found the answer here: <https://stackoverflow.com/questions/6815614/generating-word-of-the-day-via-php-random-number#:~:text=Just%20set%20the%20current%20date,same%20number%20for%20one%20Day.>

Body:
get total lines from your file

Use a database or file and store a random number daily.

Use that number to read a random message from the file.

Use cron to update random numbers at midnight in your database or file.

So, for 24 hours the same message will be displayed.

function getRandomNo(): int {
    $path = ROOT_PATH. '/randomno.txt';
    $file = fopen($path,"r");
    $data = fread($file,100);
    fclose($file);

    if($data) {
        $parts = explode('=',$data);
        if($parts[0] != date("Y-m-d")) {
            $randomNo = rand(0,100);
            overWrite($randomNo);
        } else {
            $randomNo = $parts[1];
        }
    } else {
        $randomNo = rand(0,100);
        overWrite($randomNo);
    }

    return $randomNo;
}

function overWrite(int $randomNo): void {
    $path = ROOT_PATH. '/randomno.txt';
    $file = fopen($path,"w+");
    $data = date("Y-m-d").'='.$randomNo;
    fwrite($file, $data);
    fclose($file);
}

$messages_from_file = loadMessagesFromFile();
$key = getRandomNo();
$full_text = $messages_from_file[$key];


问:
Simple string addition in ruby/rails
This is something I wasn't expecting.

I'm using anemone to count links in pages (anemone is a web spider framework for ruby)

Its pretty straightforward, but why won't this work?

```<code>anemone.on_every_page do |page|
    @myLinks =[]
      page.links.each_with_index do |link,index|
        puts "HOWDY PARDNER"
        @tempLink =(link.to_s + ",")
        @myLinks[index] = @tempLink
      end
end
</code>```

The part in question is the addition of link.to_s  +","

The reason I'm doing this addition is that links.to_s comes down as an entire string with no spaces. I'd like to sepsrate them with a , so I can use .split() later.

答:
You can turn json objects back into ruby objects using the following:</p>

```<code>ActiveSupport::JSON.decode(some_json)
</code>```

Title: Simple string addition in ruby/rails

Body:
This is something I wasn't expecting.

I'm using anemone to count links in pages (anemone is a web spider framework for ruby)

Its pretty straightforward, but why won't this work?

anemone.on_every_page do |page|
    @myLinks =[]
      page.links.each_with_index do |link,index|
        puts "HOWDY PARDNER"
        @tempLink =(link.to_s + ",")
        @myLinks[index] = @tempLink
      end
end

The part in question is the addition of link.to_s  +","

The reason I'm doing this addition is that links.to_s comes down as an entire string with no spaces. I'd like to sepsrate them with a , so I can use .split() later.

Body:
You can turn json objects back into ruby objects using the following:

ActiveSupport::JSON.decode(some_json)


问:
Postges command exection without password
I want to use rundeck to allow app user to reset their own password without admin access.
So I would like to execute this type of command:

```<code>export PASSFILE=/usr/pgsql-13/.pgpass ; /usr/pgsql-13/bin/psql -h hostname -U postgres -c """alter user ${job.username} PASSWORD '${option.Password}';"""
</code>```

But the script fails because postgres ask for password
Any one have a workaround? The postgres DB is not a classic DB but aws aurora DB, so I don't have access to pg_hba file

Many thanks

答: If you want to use interactive commands on Rundeck you can use expect command, in that way you can "wrap" your command to "answer" any interactive command "question", that was answered here.</p>

Body:
I want to use rundeck to allow app user to reset their own password without admin access.
So I would like to execute this type of command:

export PASSFILE=/usr/pgsql-13/.pgpass ; /usr/pgsql-13/bin/psql -h hostname -U postgres -c """alter user ${job.username} PASSWORD '${option.Password}';"""

But the script fails because postgres ask for password
Any one have a workaround? The postgres DB is not a classic DB but aws aurora DB, so I don't have access to pg_hba file

Many thanks