问:
jQuery AutoComplete JSON in CakePHP
I'm trying to make jQuery AutoComplete JSON data with CakePHP. My code actually WORKs. It shows the autocompletion as expected, but it fails on:

the selected item doesn't show up in the searchbox once we select it (blank).

the 'No result' doesn't show up if the data does not exist.

Here's the code:

//search action of my Customer controller

```<code>function search(){

    $this->Customer->recursive = -1;

    $customers = $this->Customer->find('all', array(
        'conditions'=>array('Customer.nama LIKE'=>$this->params['url']['q'].'%'),
        'fields'=>array('id', 'name', 'telp', 'address'))
    );

    $this->set('customers', $customers);

    Configure::write('debug', 0);
    $this->layout = 'ajax';
}
</code>```

//my search.ctp

```<code><?php

if(!empty($customers)) {

    $data = array();

    foreach ($customers as $customer){
        $data[] = $customer['Customer'];
    }

    echo json_encode($data);
}
else echo 'No result';

?>
</code>```

//my js file

```<code>$().ready(function () {

    $("#search-txtbox").autocomplete("/customers/search",
        {
            parse: function(data){
                var parsed = [];
                for (var i=0; i < data.length; i++) {
                    parsed[i] = {
                        data: data[i],
                        value: data[i].name //the search item
                    };
                }
                return parsed;
            },
            formatItem: function (row, i, max) {
                var str = row.name + ' (Telp: '+ row.telp +')' + '<br />';
                str += row.address;
                return str;
            },
            formatResult: function (row) {
                return row.name;
            },
            minChars: 2,
            max: 0,
            width: 224,
            scrollHeight: 420,
            dataType: 'json'
        }
    );
});
</code>```

Please help me modify the code. Thank you!

答:
First of all, the plugin you're using has been deprecated in favor of jQueryUI, and I'd highly recommend using it instead (better support from the community, updates, etc.). However, if for some reason you have to use that plugin, here are your issues:

This is poorly documented (if it is documented at all), but it looks like the parse function must return an object with a result property that gets inserted into the input element. So you should just have to modify you're parse function to add that property:

```<code>parse: function(data){
    var parsed = [];
    for (var i=0; i < data.length; i++) {
        parsed[i] = {
            data: data[i],
            value: data[i].name, //the search item
            result: data[i].result
        };
    }
    return parsed;
},
</code>```

I'm not sure where you want "No result" to show up, but you could slightly modify your PHP code and show a message inside the parse function:

PHP

```<code>$data = array();

foreach ($customers as $customer){
    $data[] = $customer['Customer'];
}

echo json_encode($data);
</code>```

JavaScript

```<code>parse: function(data){
    var parsed = [];
    for (var i=0; i < data.length; i++) {
        parsed[i] = {
            data: data[i],
            value: data[i].name, //the search item
            result: data[i].name
        };
    }
    if (!parsed.length) { // <-- Do something with the "No Results" message.
        $("body").append("no results");
    }
    return parsed;
},
</code>```

Sorry I can't provide a working example. If you want an example using the jQueryUI widget, I'd be happy to provide one.

Title: jQuery AutoComplete JSON in CakePHP

Body:
I'm trying to make jQuery AutoComplete JSON data with CakePHP. My code actually WORKs. It shows the autocompletion as expected, but it fails on:

the selected item doesn't show up in the searchbox once we select it (blank).

the 'No result' doesn't show up if the data does not exist.

Here's the code:

//search action of my Customer controller

function search(){

    $this->Customer->recursive = -1;

    $customers = $this->Customer->find('all', array(
        'conditions'=>array('Customer.nama LIKE'=>$this->params['url']['q'].'%'),
        'fields'=>array('id', 'name', 'telp', 'address'))
    );

    $this->set('customers', $customers);

    Configure::write('debug', 0);
    $this->layout = 'ajax';
}

//my search.ctp

<?php

if(!empty($customers)) {

    $data = array();

    foreach ($customers as $customer){
        $data[] = $customer['Customer'];
    }

    echo json_encode($data);
}
else echo 'No result';

?>

//my js file

$().ready(function () {

    $("#search-txtbox").autocomplete("/customers/search",
        {
            parse: function(data){
                var parsed = [];
                for (var i=0; i < data.length; i++) {
                    parsed[i] = {
                        data: data[i],
                        value: data[i].name //the search item
                    };
                }
                return parsed;
            },
            formatItem: function (row, i, max) {
                var str = row.name + ' (Telp: '+ row.telp +')' + '
';
                str += row.address;
                return str;
            },
            formatResult: function (row) {
                return row.name;
            },
            minChars: 2,
            max: 0,
            width: 224,
            scrollHeight: 420,
            dataType: 'json'
        }
    );
});

Please help me modify the code. Thank you!

Body:
First of all, the plugin you're using has been deprecated in favor of jQueryUI, and I'd highly recommend using it instead (better support from the community, updates, etc.). However, if for some reason you have to use that plugin, here are your issues:

This is poorly documented (if it is documented at all), but it looks like the parse function must return an object with a result property that gets inserted into the input element. So you should just have to modify you're parse function to add that property:

parse: function(data){
    var parsed = [];
    for (var i=0; i < data.length; i++) {
        parsed[i] = {
            data: data[i],
            value: data[i].name, //the search item
            result: data[i].result
        };
    }
    return parsed;
},

I'm not sure where you want "No result" to show up, but you could slightly modify your PHP code and show a message inside the parse function:

PHP

$data = array();

foreach ($customers as $customer){
    $data[] = $customer['Customer'];
}

echo json_encode($data);

JavaScript

parse: function(data){
    var parsed = [];
    for (var i=0; i < data.length; i++) {
        parsed[i] = {
            data: data[i],
            value: data[i].name, //the search item
            result: data[i].name
        };
    }
    if (!parsed.length) { // <-- Do something with the "No Results" message.
        $("body").append("no results");
    }
    return parsed;
},

Sorry I can't provide a working example. If you want an example using the jQueryUI widget, I'd be happy to provide one.


来源: stackexchange

问:
HTML5 make empty div full viewport size
I’m trying to create an EMPTY div that takes up 100% of the viewport and that moves with the viewport (or position: fixed).
It also needs to be at top: 0, left 0 of the viewport. This is for a browser extension so I need this div to be added over any page.

The background reason for this is so I can use the div as a full page tooltip that shows the mouse x and y positions and the tooltip follows the mouse.

How can this full page div be achieved? My many attempts have failed to create a div with any height.

I am away from my pc but can add what I’ve tried already soon.

答:
```<code>.empty-div {
  position: fixed;
  inset: 0;
}
</code>```

The inset property is a shorthand for top, right, bottom and left which will stretch the div to all corners.

In order to place the div at the very top, over everything else, it's best to insert the div at the very end of the page; just before the closing  tag.

To be on the safe side, you can also add z-index: 9999999.

ContentLicense: CC BY-SA 4.0

Title: HTML5 make empty div full viewport size

Body:
.empty-div {
  position: fixed;
  inset: 0;
}

The inset property is a shorthand for top, right, bottom and left which will stretch the div to all corners.

In order to place the div at the very top, over everything else, it's best to insert the div at the very end of the page; just before the closing </body> tag.

To be on the safe side, you can also add z-index: 9999999.


问:
Call Navigator from outside state or call child state method from parent
I ended up with a parent calling a child method, which is fine, but I can't call Navigator outside the state class. My goal is either to move the child method in it's state and somehow access it, or to call Navigator form outside the state in a Stateful widget.

What is the best approach to this problem?

```<code>import 'package:flutter/material.dart';

class ParentClass extends StatefulWidget {
  const ParentClass({Key? key}) : super(key: key);

  @override
  _ParentClassState createState() => _ParentClassState();
}

class _ParentClassState extends State<ParentClass> {
  ChildClass childclass = ChildClass();
  @override
  Widget build(BuildContext context) {
    return Container(
      child: ElevatedButton(
          child: Text('Button'),
          onPressed: () => {
                childclass.callNavigator(),//or call callNavigatorState
              }),
    );
  }
}

class ChildClass extends StatefulWidget {
  const ChildClass({Key? key}) : super(key: key);
  void callNavigator() {
    //call navigator from here
  }
  @override
  _ChildClassState createState() => _ChildClassState();
}

class _ChildClassState extends State<ChildClass> {
  void callNavigatorState(){
    //access from parent widget?
  }
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

</code>```

答:
you can access a stateful's state, using Globalkey.currentState...

check this sample code:

class MyHomePage extends StatelessWidget {
  MyHomePage({Key? key}) : super(key: key);

  final child = ChildWidget(key: GlobalKey());
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          child,
          ElevatedButton(
              onPressed: () {
                (((child as ChildWidget).key as GlobalKey).currentState!
                        as _ChildWidgetState)
                    .someFunction();
              },
              child: Text("childWidget someFunction"))
        ],
      ),
    );
  }
}

class ChildWidget extends StatefulWidget {
  const ChildWidget({Key? key}) : super(key: key);

  @override
  _ChildWidgetState createState() => _ChildWidgetState();
}

class _ChildWidgetState extends State<ChildWidget> {
  void someFunction() {
    print("childWidget someFunction");
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}
```

Body:
I ended up with a parent calling a child method, which is fine, but I can't call Navigator outside the state class. My goal is either to move the child method in it's state and somehow access it, or to call Navigator form outside the state in a Stateful widget.

What is the best approach to this problem?

import 'package:flutter/material.dart';

class ParentClass extends StatefulWidget {
  const ParentClass({Key? key}) : super(key: key);

  @override
  _ParentClassState createState() => _ParentClassState();
}

class _ParentClassState extends State<ParentClass> {
  ChildClass childclass = ChildClass();
  @override
  Widget build(BuildContext context) {
    return Container(
      child: ElevatedButton(
          child: Text('Button'),
          onPressed: () => {
                childclass.callNavigator(),//or call callNavigatorState
              }),
    );
  }
}

class ChildClass extends StatefulWidget {
  const ChildClass({Key? key}) : super(key: key);
  void callNavigator() {
    //call navigator from here
  }
  @override
  _ChildClassState createState() => _ChildClassState();
}

class _ChildClassState extends State<ChildClass> {
  void callNavigatorState(){
    //access from parent widget?
  }
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}


Title: How to plot two independent linear regressions on the same plot in R using GGplot2?

Body:
I am trying to present linear regressions of two datasets on the same plot.

Bird data vs year

Signy data vs year
As they are exclusive to each other (count data from two islands) I don't want to plot a multiple regression, but I am not sure the code in R to produce both regressions on the same plot.

PlasticMass.data

  ï..Year |Bird.Plastic.Mass Signy.Plastic.Mass
1     1991 |             NA   |           2.384
2     1992 |             NA   |           8.340
3     1993 |             NA   |           2.680
4     1994 |             NA   |           1.450
5     1995 |             NA   |           1.940
6     1996 |             6.43 |           0.570
7     1997 |             19.86|           1.170
8     1998 |             4.89 |           2.010
9     1999 |             2.97 |           1.410
10    2000 |             3.10 |           1.690
11    2001 |             3.30 |           0.350
12    2002 |             4.45 |           9.280
13    2003 |             4.05 |           16.750
14    2004 |             2.18 |           4.330
15    2005 |             4.88 |           0.260
16    2006 |             4.39 |           13.500
17    2007 |             4.27 |           6.270
18    2008 |             4.40 |           9.030
19    2009 |             1.63 |           3.860
20    2010 |             1.70 |           22.100
21    2011 |             1.64 |           1.150
22    2012 |             2.16 |           13.080
23    2013 |             3.05 |           0.140
24    2014 |             1.34 |           0.010
25    2015 |             3.66 |           0.000
26    2016 |             0.87 |           0.000
27    2017 |             1.10 |           7.010
28    2018 |             2.29 |           1.740
29    2019 |             1.44 |           80.790

R code to plot individual regressions:
Plastic by mass linear regressions

PlasticMass.data <-read.csv("Plastic by Mass.csv", header = T)
print(Plastic.Mass.data)

modelPB <-lm(Bird.Plastic.Mass ~ï..Year, data= PlasticMass.data)

modelPS <-lm(Signy.Plastic.Mass ~ï..Year, data = PlasticMass.data)

ggplot(PlasticMass.data, aes(ï..Year, Bird.Plastic.Mass))+
geom_point()+
geom_smooth(method = "lm")+
labs(x="Year", y="Bird Island Total Debris Count")

ggplot(PlasticMass.data, aes(ï..Year, Signy.Plastic.Mass))+
geom_point()+
geom_smooth(method = "lm", colour ="lightgreen")+
labs(x="Year", y="Signy Island Total Debris Count")

Here is a link to show the regression plot I made on excel (where both datasets are plotted and the separate linear regressions are shown).

Regressions in excel

Body:
Approach

Pivot to longer, use a group mapping to map pivoted group to lm

Code

  library(dplyr)
    library(tidyr)
    library(ggplot2)
    df %>%
      mutate(Bird.Plastic.Mass = as.numeric(trimws(Bird.Plastic.Mass)),
    Year = factor(Year))%>%
      na.omit() %>%
      pivot_longer(cols = Bird.Plastic.Mass:Signy.Plastic.Mass, names_to = "var", values_to="val") %>%
      ggplot(aes(Year, val, col=var, group=var))+
      geom_point() +

  geom_smooth(method="lm")

Result (not exactly as Excel plot, may be due to less data)

Data

df <- structure(list(Year = c("1     1991 ", "2     1992 ", "3     1993 ",
"4     1994 ", "5     1995 ", "6     1996 ", "7     1997 ", "8     1998 ",
"9     1999 ", "10    2000 ", "11    2001 ", "12    2002 ", "13    2003 ",
"14    2004 ", "15    2005 ", "16    2006 ", "17    2007 ", "18    2008 ",
"19    2009 ", "20    2010 ", "21    2011 ", "22    2012 ", "23    2013 ",
"24    2014 ", "25    2015 ", "26    2016 ", "27    2017 ", "28    2018 ",
"29    2019 "), Bird.Plastic.Mass = c("             NA   ", "             NA   ",
"             NA   ", "             NA   ", "             NA   ",
"             6.43 ", "             19.86", "             4.89 ",
"             2.97 ", "             3.10 ", "             3.30 ",
"             4.45 ", "             4.05 ", "             2.18 ",
"             4.88 ", "             4.39 ", "             4.27 ",
"             4.40 ", "             1.63 ", "             1.70 ",
"             1.64 ", "             2.16 ", "             3.05 ",
"             1.34 ", "             3.66 ", "             0.87 ",
"             1.10 ", "             2.29 ", "             1.44 "
), Signy.Plastic.Mass = c(2.384, 8.34, 2.68, 1.45, 1.94, 0.57,
1.17, 2.01, 1.41, 1.69, 0.35, 9.28, 16.75, 4.33, 0.26, 13.5,
6.27, 9.03, 3.86, 22.1, 1.15, 13.08, 0.14, 0.01, 0, 0, 7.01,
1.74, 80.79)), class = "data.frame", row.names = c(NA, -29L))


问:
Can't Run flutter app on ios after Amplify update 0.3.2
I get the following error

```<code>[!] CocoaPods could not find compatible versions for pod "AmplifyPlugins/AWSCognitoAuthPlugin":
  In snapshot (Podfile.lock):
    AmplifyPlugins/AWSCognitoAuthPlugin (= 1.15.6, ~> 1.15.5)

  In Podfile:
    amplify_auth_cognito (from `.symlinks/plugins/amplify_auth_cognito/ios`) was resolved to 0.0.1, which depends on
      AmplifyPlugins/AWSCognitoAuthPlugin (= 1.19.0)

Specs satisfying the `AmplifyPlugins/AWSCognitoAuthPlugin (= 1.15.6, ~> 1.15.5), AmplifyPlugins/AWSCognitoAuthPlugin (= 1.19.0)` dependency were found, but they required a higher minimum deployment target.

</code>```

I have set
platform :ios, '15.0'
in podfile

When I try to open in xcode and build the project I get the following error

```<code>diff: /Podfile.lock: No such file or directory

diff: /Manifest.lock: No such file or directory

error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.
</code>```

答:
from your root flutter project open the terminal and type

```<code>cd ios
</code>```

and then run

```<code>pod install
</code>```

if that doesn't work then run

```<code>pod deintegrate
</code>```

and then

```<code>pod install
</code>```

Body:
I get the following error

[!] CocoaPods could not find compatible versions for pod "AmplifyPlugins/AWSCognitoAuthPlugin":
  In snapshot (Podfile.lock):
    AmplifyPlugins/AWSCognitoAuthPlugin (= 1.15.6, ~> 1.15.5)

  In Podfile:
    amplify_auth_cognito (from `.symlinks/plugins/amplify_auth_cognito/ios`) was resolved to 0.0.1, which depends on
      AmplifyPlugins/AWSCognitoAuthPlugin (= 1.19.0)

Specs satisfying the `AmplifyPlugins/AWSCognitoAuthPlugin (= 1.15.6, ~> 1.15.5), AmplifyPlugins/AWSCognitoAuthPlugin (= 1.19.0)` dependency were found, but they required a higher minimum deployment target.

I have set
platform :ios, '15.0'
in podfile

When I try to open in xcode and build the project I get the following error

diff: /Podfile.lock: No such file or directory

diff: /Manifest.lock: No such file or directory

error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.

Body:
from your root flutter project open the terminal and type

cd ios

and then run

pod install

if that doesn't work then run

pod deintegrate

and then

pod install


问:
Make title string the entire URI for all pages using CodeIgniter
With CodeIgniter I'm trying to create a URL structure that uses a title string as the entire URI; so for example: www.example.com/this-is-a-title-string

I'm pretty confident I need to use the url_title() function in the URL Helper along with the routes.php config folder but I'm stuck bringing it all together.

Where do I define the URI and how is it caught by the routes folder?

Seems to be a straight forward problem but I'm getting stuck creating the URLs end-to-end. What am I missing?

I thought about a catch-all in the routes folder: $route['(.*)'] = "welcome/controller/$1"; ....but how would this work with multiple functions inside a particular controller? ...and maybe it's not even the right way to solve.

答:
If you're going to re-route every request, you should extend CI_Router.

The actual implementation depends on what you're doing. If you customize CI_Router, you can do it AFTER the code that checks routes.php, so that you can keep routes.php available for future customization.

If the URI contains the controller, function, and parameters, you can parse it within your extended CI_Router and then continue with the request like normal.

If the URI is arbitrary, then you'll need something (file, db, etc) that maps the URI to the correct controller/function/parameters. Using blog posts as an example, you can search for the URI (aka post-slug in WordPress) in the db and grab the corresponding record. Then forward the request to something like "articles/view/ID".

ContentLicense: CC BY-SA 3.0


问:
Delay boolean changing in Laravel Livewire / PHP
I would like to toggle a boolean after a couple of seconds. I originally thought I could set the boolean to be true (showing the toast) and then sleep(2) and then set the boolean to false again. But all that occurs is (apparently) the sleep is ignored and the boolean is toggled true then immediately false, so you don't even see it appear.

Could anyone shed some light on how / why this occurs and how to overcome it without the use of JavaScript toast alternatives?

public function store()
{
    $this->validate();
    $this->fileref->save();
    $this->show_toast = true; # Toast show
    sleep(2); # Wait...
    $this->show_toast = false; # Toast hide
}
```

答:
Here is my solution, per the opening question, not resorting to a Javascript toast library, such as Notyf or Toastr. It was not my intention to avoid the use of Javascript altogether.

With that said, by dispatching a browser event (server-side) and then adding a listener to my Component (server-side), I am able to still use mostly the server-side & a simple @if-wrapped notification (html) to render my toast notification, time it, then remove it.

public function store()
{
    $this->validate();
    $this->fileref->save();
    $this->show_toast = true; # Toast show
    $this->dispatchBrowserEvent('fileStored');
}
```
<p>Then, back on my Livewire Component:</p>
<pre class="lang-php prettyprint-override"><code>protected $listeners = ['eatToast' => 'hideToast'];
</code>```

Finally, the only Javascript part:

document.addEventListener('fileStored', function () {
    setTimeout(() => {
        Livewire.emit('eatToast');
    }, 5000);
});
```
<p>Final method (inside of Livewire Component) to hide toast:</p>
<pre class="lang-php prettyprint-override"><code>public function hideToast() {
    $this->show_toast = false;
}
</code>```

Body:
Here is my solution, per the opening question, not resorting to a Javascript toast library, such as Notyf or Toastr. It was not my intention to avoid the use of Javascript altogether.

With that said, by dispatching a browser event (server-side) and then adding a listener to my Component (server-side), I am able to still use mostly the server-side & a simple @if-wrapped notification (html) to render my toast notification, time it, then remove it.

public function store()
{
    $this->validate();
    $this->fileref->save();
    $this->show_toast = true; # Toast show
    $this->dispatchBrowserEvent('fileStored');
}

Then, back on my Livewire Component:

protected $listeners = ['eatToast' => 'hideToast'];

Finally, the only Javascript part:

document.addEventListener('fileStored', function () {
    setTimeout(() => {
        Livewire.emit('eatToast');
    }, 5000);
});

Final method (inside of Livewire Component) to hide toast:

public function hideToast() {
    $this->show_toast = false;
}


问:
Alert for percentage increase of another alert?
I'm using this simple EMA:

```<code>study(title="EMA 5/10/20", overlay=true)
shortest = ema(close, 5)
short = ema(close, 10)
longer = ema(close, 20)
plot(shortest, color = yellow, linewidth=2)
plot(short, color = red, linewidth=2)
plot(longer, color = purple, linewidth=2)
EmaOpen = ta.crossover(shortest, longer)
alertcondition(EmaOpen, title="EmaOpen", message= "Ema Open")
</code>```

Which alerts me when the 5 EMA price cross over 20 EMA.

Is it possible to add another alert that can trigger when the price is above the (EmaOpen) alert by let's say 3%? So we can create some kind of a take profit signal if we bought at the EmaOpen signal?

答:
EmaOpen will be true whenever there is a crossover. You should store the close price whenever that happens and calculate your 3% over that price. Then check if price crossesover your calculated value.

```<code>//@version=5
indicator(title="EMA 5/10/20", overlay=true)

tp_per = input.float(3.0, "Take Profit %") / 100.0

shortest = ta.ema(close, 5)
short = ta.ema(close, 10)
longer = ta.ema(close, 20)

var float EmaTp = na
EmaOpen = ta.crossover(shortest, longer)
EmaTp := EmaOpen ? close * (1 + tp_per) : EmaTp
tpBreached = ta.crossover(close, EmaTp)
EmaTp := tpBreached ? na : EmaTp

plot(shortest, color = color.yellow, linewidth=2)
plot(short, color = color.red, linewidth=2)
plot(longer, color = color.purple, linewidth=2)
plotshape(EmaOpen, location=location.belowbar, size=size.small)
plot(EmaTp, color=color.green, style=plot.style_circles)
plotshape(tpBreached, style=shape.triangledown, location=location.abovebar, color=color.green, size=size.small)

alertcondition(EmaOpen, title="EmaOpen", message= "Ema Open")
alertcondition(tpBreached, title="TP", message= "Take Profit")
</code>```

Blue "X"s are where the EMA cross takes place

Green dots are your take profit level

Green triangles are where the price hits your take profit level

Body:
I'm using this simple EMA:

study(title="EMA 5/10/20", overlay=true)
shortest = ema(close, 5)
short = ema(close, 10)
longer = ema(close, 20)
plot(shortest, color = yellow, linewidth=2)
plot(short, color = red, linewidth=2)
plot(longer, color = purple, linewidth=2)
EmaOpen = ta.crossover(shortest, longer)
alertcondition(EmaOpen, title="EmaOpen", message= "Ema Open")

Which alerts me when the 5 EMA price cross over 20 EMA.

Is it possible to add another alert that can trigger when the price is above the (EmaOpen) alert by let's say 3%? So we can create some kind of a take profit signal if we bought at the EmaOpen signal?

Body:
EmaOpen will be true whenever there is a crossover. You should store the close price whenever that happens and calculate your 3% over that price. Then check if price crossesover your calculated value.

//@version=5
indicator(title="EMA 5/10/20", overlay=true)

tp_per = input.float(3.0, "Take Profit %") / 100.0

shortest = ta.ema(close, 5)
short = ta.ema(close, 10)
longer = ta.ema(close, 20)

var float EmaTp = na
EmaOpen = ta.crossover(shortest, longer)
EmaTp := EmaOpen ? close * (1 + tp_per) : EmaTp
tpBreached = ta.crossover(close, EmaTp)
EmaTp := tpBreached ? na : EmaTp

plot(shortest, color = color.yellow, linewidth=2)
plot(short, color = color.red, linewidth=2)
plot(longer, color = color.purple, linewidth=2)
plotshape(EmaOpen, location=location.belowbar, size=size.small)
plot(EmaTp, color=color.green, style=plot.style_circles)
plotshape(tpBreached, style=shape.triangledown, location=location.abovebar, color=color.green, size=size.small)

alertcondition(EmaOpen, title="EmaOpen", message= "Ema Open")
alertcondition(tpBreached, title="TP", message= "Take Profit")

Blue "X"s are where the EMA cross takes place

Green dots are your take profit level

Green triangles are where the price hits your take profit level


问:
C++ wprintf format specifier for char16_t for printing unicode string
I have the following code successfully compiled:

```<code>#include <io.h>
#include <fcntl.h>
#include <iostream>
#include <cstddef>
#include <cstdio>
int main()
{
    _setmode(_fileno(stdout), _O_U16TEXT);

    char16_t chinese[] = u"\u4e66\u4e2d\u81ea\u6709\u9ec4\u91d1\u5c4b";
    wprintf(L"String written with unicode codes: %ls \n", chinese);

    wchar_t arabic[] = L"أَبْجَدِيَّة عَرَبِيَّة";
    wprintf(L"String written with L-String: %ls \n", arabic);
    std::wcout << std::endl;  std::system("PAUSE");
}
</code>```

It prints:

String written with unicode codes: 书中自有黄金屋

String written with L-String: أَبْجَدِيَّة عَرَبِيَّة

However, the compiler issues a warning for chinese case (not for arabic case):

```<code>warning C4477: 'wprintf' : format string '%ls' requires an argument of type 'wchar_t *', but variadic argument 1 has type 'char16_t *'
</code>```

What would be then the correct wprintf format string?

答:
wchar_t is not the same as char16_t. wchar_t are 2 byte characters on windows, but (usually) 4 byte characters on linux. This is like the int vs. int16_t problem. The standard does not define wchar_t.

So the question is not what format specifier to use with wprintf. It's rather how to convert a char16_t string to a wchar_t string.

Under Windows you might get away with simply casting a char16_t to a wchar_t, which is what happens implicitly with wprintf, since it does not actually validate it's parameters. The warning C4477 is just a little help by the (Visual Studio?) compiler hinting at your problem.

But on other platforms you have to actually convert the string.

So the best solution would be something like this:
wprintf("%ls", boost::utf16_to_wchar_t(chinese)); (I am just throwing in boost here, since they have conversion functions. I don't know the exact function to use).

Or alternatively use wchar_t escape sequences and define your chinese as a wchar_t* string.

Body:
I have the following code successfully compiled:

#include <io.h>
#include <fcntl.h>
#include <iostream>
#include <cstddef>
#include <cstdio>
int main()
{
    _setmode(_fileno(stdout), _O_U16TEXT);

    char16_t chinese[] = u"\u4e66\u4e2d\u81ea\u6709\u9ec4\u91d1\u5c4b";
    wprintf(L"String written with unicode codes: %ls \n", chinese);

    wchar_t arabic[] = L"أَبْجَدِيَّة عَرَبِيَّة";
    wprintf(L"String written with L-String: %ls \n", arabic);
    std::wcout << std::endl;  std::system("PAUSE");
}

It prints:

String written with unicode codes: 书中自有黄金屋

String written with L-String: أَبْجَدِيَّة عَرَبِيَّة

However, the compiler issues a warning for chinese case (not for arabic case):

warning C4477: 'wprintf' : format string '%ls' requires an argument of type 'wchar_t *', but variadic argument 1 has type 'char16_t *'

What would be then the correct wprintf format string?


问:
Listing GitLab Repositories name using GitLab api
I want to list only GitLab repositories name using GitLab API.

i tried command curl "https://gitlab.com/api/v4/projects?private_token=*************"

it is listing all merge requests, issues and also repository names.

How can i list only the repository names?

答:
As Igor mentioned the Gitlab API does not let you to limit the response to a single field.

I would recommend combining the original API call with the jq command.
This will enable parsing of the returned json

```<code>curl "https://gitlab.com/api/v4/projects?private_token=*************" | jq '.[].name'
</code>```

Body:
As Igor mentioned the Gitlab API does not let you to limit the response to a single field.

I would recommend combining the original API call with the jq command.
This will enable parsing of the returned json

curl "https://gitlab.com/api/v4/projects?private_token=*************" | jq '.[].name'


问:
All routes giving 404 in flask despite the routes.py being successfully imported
I currently working on a flask backend but have hit an issue where all routes return a 404 despite the routes.py apparently running.

routes.py:

```<code>import sys, os, json
from flask import Flask, render_template
from flask_cors import CORS, cross_origin

app = Flask(__name__)
app.config.from_pyfile('config.py')
CORS(app)

@app.route('/', endpoint='index')
@app.route('/index', methods=['GET'], endpoint='index')
@cross_origin()
def index():
    print('Hello world!', file=sys.stderr)

    return render_template('index.html', title='home')

@app.route('/projects', endpoint='projects')  # route for projects showcase including json project data loading
@cross_origin()
def projects():
    projects = os.path.join(app.static_folder, 'data', 'projects.json')

    with open(projects) as pData:
        data = json.load(pData)

    return render_template('projects.html', title='showcase', data=data)

@app.route('/contact', endpoint='contact')
def contact():
    return render_template('contact.html', title='contact')

print('Hello routes!', file=sys.stderr) #testing line
</code>```

When I launch it the output is this:

```<code> * Serving Flask app 'ClayG' (lazy loading)
 * Environment: development
 * Debug mode: on
Hello routes!
 * Restarting with stat
 * Debugger is active!
Hello routes!
 * Debugger PIN: 274-753-929
 * Running on http://127.0.0.1:5000/
</code>```

the print function at the end of routes.py runs so my app is making it through, but when i visit localhost:5000 I get a 404 with only this in the terminal output

```<code>127.0.0.1 - - [05/Feb/2022 17:20:29] "GET / HTTP/1.1" 404 -
</code>```

The other files and file structure

```<code>.
├── ClayG.py
├── .flaskenv
├── app
│   ├── config.py
│   ├── routes.py
│   └── __init__.py
</code>```

ClayG.py

```<code>import os, sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__))))
from app import app
</code>```

.flaskenv

```<code>FLASK_APP=ClayGale
FLASK_ENV=development
</code>```

init.py

```<code>from flask import Flask

from . import routes

app = Flask(__name__)
</code>```

config.py

```<code>class Config:
    STATIC_FOLDER = 'static'
    TEMPLATES_FOLDER = 'templates'
    DEBUG = True
    TESTING = True
</code>```

One thing i've noticed is that adding FLASK_ENV = 'development' to the config class is that it still launches as production and I can only get it to launch in development with the .flaskenv file. I'm unfortunately just stumped as for what to do from here so any wisdom on what to try would be helpful.

答:
You have created two Flask apps. One in routes.py with the endpoints, and a new one in __init__.py which is completely empty. You should use the previously created app in the __init__.py file:

```<code>from . import routes

app = routes.app
</code>```

Body:
I currently working on a flask backend but have hit an issue where all routes return a 404 despite the routes.py apparently running.

routes.py:

import sys, os, json
from flask import Flask, render_template
from flask_cors import CORS, cross_origin

app = Flask(__name__)
app.config.from_pyfile('config.py')
CORS(app)

@app.route('/', endpoint='index')
@app.route('/index', methods=['GET'], endpoint='index')
@cross_origin()
def index():
    print('Hello world!', file=sys.stderr)

    return render_template('index.html', title='home')

@app.route('/projects', endpoint='projects')  # route for projects showcase including json project data loading
@cross_origin()
def projects():
    projects = os.path.join(app.static_folder, 'data', 'projects.json')

    with open(projects) as pData:
        data = json.load(pData)

    return render_template('projects.html', title='showcase', data=data)

@app.route('/contact', endpoint='contact')
def contact():
    return render_template('contact.html', title='contact')

print('Hello routes!', file=sys.stderr) #testing line

When I launch it the output is this:

 * Serving Flask app 'ClayG' (lazy loading)
 * Environment: development
 * Debug mode: on
Hello routes!
 * Restarting with stat
 * Debugger is active!
Hello routes!
 * Debugger PIN: 274-753-929
 * Running on http://127.0.0.1:5000/

the print function at the end of routes.py runs so my app is making it through, but when i visit localhost:5000 I get a 404 with only this in the terminal output

127.0.0.1 - - [05/Feb/2022 17:20:29] "GET / HTTP/1.1" 404 -

The other files and file structure

.
├── ClayG.py
├── .flaskenv
├── app
│   ├── config.py
│   ├── routes.py
│   └── __init__.py

ClayG.py

import os, sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__))))
from app import app

.flaskenv

FLASK_APP=ClayGale
FLASK_ENV=development

init.py

from flask import Flask

from . import routes

app = Flask(__name__)

config.py

class Config:
    STATIC_FOLDER = 'static'
    TEMPLATES_FOLDER = 'templates'
    DEBUG = True
    TESTING = True

One thing i've noticed is that adding FLASK_ENV = 'development' to the config class is that it still launches as production and I can only get it to launch in development with the .flaskenv file. I'm unfortunately just stumped as for what to do from here so any wisdom on what to try would be helpful.

Body:
You have created two Flask apps. One in routes.py with the endpoints, and a new one in __init__.py which is completely empty. You should use the previously created app in the __init__.py file:

from . import routes

app = routes.app


问:
qemu-system-aarch64 always entering exception level 2 and hangs when switching to EL1. Why?
I am using qemu-system-aarch64 to emulate raspi3 (ARM Cortex A-53) on a x86 host. Here's the command that I use to launch the baremetal image :

```<code>$ qemu-system-aarch64 --version
QEMU emulator version 4.2.1 (Debian 1:4.2-3ubuntu6.18)
Copyright (c) 2003-2019 Fabrice Bellard and the QEMU Project developers

$ qemu-system-aarch64 -M raspi3 -kernel kernel8.img -serial null -serial stdio -display none
</code>```

The code for kernel8.img is taken from here : https://github.com/s-matyukevich/raspberry-pi-os/tree/master/src/lesson02/src . The following function is used to get the current exception level :

```<code>.globl get_el
get_el:
    mrs x0, CurrentEL
    lsr x0, x0, #2
    ret
</code>```

The following piece of code tries to switch to EL1 on boot, which I had to comment out, otherwise this piece of code hangs indefinitely :

```<code>master:
    ldr x0, =SCTLR_VALUE_MMU_DISABLED
    msr sctlr_el1, x0

    ldr x0, =HCR_VALUE
    msr hcr_el2, x0

    ldr x0, =SCR_VALUE
    msr scr_el3, x0

    ldr x0, =SPSR_VALUE
    msr spsr_el3, x0

    adr x0, el1_entry
    msr elr_el3, x0

    eret
</code>```

After the above piece of code is commented, my program at least runs, but prints Exception level as 2.

I have following two questions :

As per the corresponding repo docs, when we are using a hypervisor, EL2 is used by the host OS so that the guest OS uses EL1 or EL0. But why my baremetal guest OS is entering EL2 by default? It should have been EL1 as per my understanding. Also, this older post on SO also had got EL1 on boot. Not sure if something changed or if I am missing anything.

Why the code to switch to EL1 hangs at line msr scr_el3, x0 ?

答:
You are running at EL2. The instruction "msr scr_el3, x0" tries to write to an EL3-only register, and it will cause an UNDEF exception if you try it from a lower EL. In other words, the code fragment you're trying to use is written to run at EL3, and needs changes if you want to run it at EL2.

The reason your code is running at EL2 is because you have used QEMU's "-kernel" argument and passed it a binary (non-ELF) file, which is telling QEMU "You should boot me in the way that the Linux kernel booting protocol documents that a Linux kernel should be booted". That protocol says "start me in EL2 or EL1, EL2 is recommended", and so that's what QEMU does.

For more information on the various options QEMU provides for loading guest code, see this answer. Note that QEMU does not provide a "boot this image or ELF file in the way that the Raspberry PI bootrom code would boot it": you may have to adapt code intended to run on real bare-metal boards a little bit.

Body:
I am using qemu-system-aarch64 to emulate raspi3 (ARM Cortex A-53) on a x86 host. Here's the command that I use to launch the baremetal image :

$ qemu-system-aarch64 --version
QEMU emulator version 4.2.1 (Debian 1:4.2-3ubuntu6.18)
Copyright (c) 2003-2019 Fabrice Bellard and the QEMU Project developers

$ qemu-system-aarch64 -M raspi3 -kernel kernel8.img -serial null -serial stdio -display none

The code for kernel8.img is taken from here : https://github.com/s-matyukevich/raspberry-pi-os/tree/master/src/lesson02/src . The following function is used to get the current exception level :

.globl get_el
get_el:
    mrs x0, CurrentEL
    lsr x0, x0, #2
    ret

The following piece of code tries to switch to EL1 on boot, which I had to comment out, otherwise this piece of code hangs indefinitely :

master:
    ldr x0, =SCTLR_VALUE_MMU_DISABLED
    msr sctlr_el1, x0

    ldr x0, =HCR_VALUE
    msr hcr_el2, x0

    ldr x0, =SCR_VALUE
    msr scr_el3, x0

    ldr x0, =SPSR_VALUE
    msr spsr_el3, x0

    adr x0, el1_entry
    msr elr_el3, x0

    eret

After the above piece of code is commented, my program at least runs, but prints Exception level as 2.

I have following two questions :

As per the corresponding repo docs, when we are using a hypervisor, EL2 is used by the host OS so that the guest OS uses EL1 or EL0. But why my baremetal guest OS is entering EL2 by default? It should have been EL1 as per my understanding. Also, this older post on SO also had got EL1 on boot. Not sure if something changed or if I am missing anything.

Why the code to switch to EL1 hangs at line msr scr_el3, x0 ?


问:
CodeIgniter4 - Redirect with data
I try to do this redirect in controller:

```<code>$this->getSession()->setFlashdata("error_controller", "Incorrect email or password");
return redirect()->route("login");
</code>```

and this is in view:

```<code><?php
    if($error_controller){
        echo "<div>" . $error_controller . "</div>";
    }else{
        echo "no-no";
    }
?>
</code>```

In browser is printed no-no, which that means error_controller from flashdata not arrives to view.

How to redirect to login route with data?

答:
I tried this way and it worked:

In Controller:

```<code>$validate = $this->validate([
   'firstname' => 'required',
   'lastname'  => 'required',
   'email'     => 'required|valid_email|is_unique[users.email]',
]);
</code>```

Then I passed errors as array in view (in controller)

```<code>$data['validation'] = $this->validator;
return view( 'view_file', $data );
</code>```

Then in View File:

```<code><?= form_open(....) ?>
  <input type="text" name="firstname" class="form-control" placeholder="Firstname">
  <?= ( isset($validation) && $validation->hasError('firstname')) ? $validation->getError('firstname'): ''; ?>
<?= form_close() ?>
</code>```

Title: CodeIgniter4 - Redirect with data

Body:
I try to do this redirect in controller:

$this->getSession()->setFlashdata("error_controller", "Incorrect email or password");
return redirect()->route("login");

and this is in view:

<?php
    if($error_controller){
        echo "
" . $error_controller . "
";
    }else{
        echo "no-no";
    }
?>

In browser is printed no-no, which that means error_controller from flashdata not arrives to view.

How to redirect to login route with data?

Body:
I tried this way and it worked:

In Controller:

$validate = $this->validate([
   'firstname' => 'required',
   'lastname'  => 'required',
   'email'     => 'required|valid_email|is_unique[users.email]',
]);

Then I passed errors as array in view (in controller)

$data['validation'] = $this->validator;
return view( 'view_file', $data );

Then in View File:

<?= form_open(....) ?>
  <input type="text" name="firstname" class="form-control" placeholder="Firstname">
  <?= ( isset($validation) && $validation->hasError('firstname')) ? $validation->getError('firstname'): ''; ?>
<?= form_close() ?>


问:
where does "this" refer to? (javascript30 --Day10 by Wes Bos)
First of all, I'm a Japanese beginner web devlopment learner.
So, My English might be weird and I don't have enough knowledge about programming.
I'm taking a course called javascript30 that focuses on various usage of vanilla JS and

I'm currently  making  a scheme to check the multiple checkboxes by pushing shift button and clicking it(if my explanation doesn't make scence, please copy and paste the source code below)

Accornig to source code, I gotta change the boolean of "inBetween" by setting if sentence.
I can understand what  he does but I can't understand that where does "this"  of "checkbox === this" refer to?
Why writing the code like "checkbox === this" means that it checks if check box is checked?
And I also struggle to catch the meaning of"let lastChecked".
I understand "let lastChecked" is the key to check if it is the last checkbox that was checked by user, but why he set the value of "lastChecked" like "let lastChecked = this"?
Sorry for long sentence and poor English.
I'll be happy if someone explain it.
I'll paste the source code below.

source code

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Hold Shift to Check Multiple Checkboxes</title>

      <input type="checkbox">

This is an inbox layout.

      <input type="checkbox">

Check one item

      <input type="checkbox">

Hold down your Shift key

      <input type="checkbox">

Check a lower item

      <input type="checkbox">

Everything in between should also be set to checked

      <input type="checkbox">

Try do it without any libraries

      <input type="checkbox">

Just regular JavaScript

      <input type="checkbox">

Good Luck!

      <input type="checkbox">

Don't forget to tweet your result!

```

答:
this refers to the clicked checkbox after calling the function in checkbox.addEventListener. In this case, whenever a checkbox (or you can say it as the element with the selector .inbox input[type="checkbox"]) is clicked, the function handleCheck will be called with this referred to the clicked checkbox.

For more info, please visit What does "this" means? and Why is "this" referred to the checkbox in this case?. They provide more detailed and technical info than my explanation :)


问:
The named parameter 'onChanged' is required, but there's no corresponding argument. Try adding the required argument
My trainer writes code like this:

I am writing the same code but I am getting an error. The error is as follows:

What is the problem? How can I solve it? My codes:

```<code>import 'package:flutter/material.dart';

class dropDownMenu extends StatefulWidget {
  dropDownMenu({Key? key}) : super(key: key);

  @override
  State<dropDownMenu> createState() => _dropDownMenuState();
}

class _dropDownMenuState extends State<dropDownMenu> {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: DropdownButton<String>(
        items: [
          DropdownMenuItem( child: Text('One'), value: 'One', ),
          DropdownMenuItem(child: Text('Two'), value: 'Two', ),
        ],
      ),
    );
  }
}
</code>```

Error:

```<code>The named parameter 'onChanged' is required, but there's no corresponding argument.
Try adding the required argument.
</code>```

答:
As the message says, onChanged is  a required callback method that is needed to be implemented on  DropdownButton

Follow the error message and do like

 child: DropdownButton<String>(
         onChanged: (value){
            //do your operation while chaning value
              }
         items: [
          DropdownMenuItem( child: Text('One'), value: 'One', ),
          DropdownMenuItem(child: Text('Two'), value: 'Two', ),
        ],
      ),
```

You can follow DropdownButton document.

Body:
My trainer writes code like this:

I am writing the same code but I am getting an error. The error is as follows:

What is the problem? How can I solve it? My codes:

import 'package:flutter/material.dart';

class dropDownMenu extends StatefulWidget {
  dropDownMenu({Key? key}) : super(key: key);

  @override
  State<dropDownMenu> createState() => _dropDownMenuState();
}

class _dropDownMenuState extends State<dropDownMenu> {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: DropdownButton<String>(
        items: [
          DropdownMenuItem( child: Text('One'), value: 'One', ),
          DropdownMenuItem(child: Text('Two'), value: 'Two', ),
        ],
      ),
    );
  }
}

Error:

The named parameter 'onChanged' is required, but there's no corresponding argument.
Try adding the required argument.

Body:
As the message says, onChanged is  a required callback method that is needed to be implemented on  DropdownButton

Follow the error message and do like

 child: DropdownButton<String>(
         onChanged: (value){
            //do your operation while chaning value
              }
         items: [
          DropdownMenuItem( child: Text('One'), value: 'One', ),
          DropdownMenuItem(child: Text('Two'), value: 'Two', ),
        ],
      ),

You can follow DropdownButton document.


问:
Removing a user from a group after N days
I am trying to create a PowerShell script that will be executed via a task every day. The task will check if a user has been a member of an AD group longer than 7 days. If so, that user will be removed.
The data is imported from a CSV file in which we will insert the date the user was added to the group:

samaccountname,Date
user 1,20/01/2022
user2,06/02/2022
```
<p>This is the code I wrote:</p>
<pre class="lang-powershell prettyprint-override"><code>$users = "C:\Path to CSV\File.csv"

Import-Module ActiveDirectory
Import-Csv $users

foreach ($user in $Users)
{
    $CheckDate2 = get-date ($user.'Date').AddDays(7)
    $CheckDate1 = get-date ($user.'Date')

    if ($CheckDate1 -lt $CheckDate2){
        exit
    }
    else{
        Remove-ADGroupMember -Identity "Group Name" -Members $user.samaccountname -Confirm:$false
    }
}
</code>```

This is the errors I am receiving:

You cannot call a method on a null-valued expression.
At line:8 char:1
+ $CheckDate2 = get-date ($user.'Date').AddDays(7)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Get-Date : Cannot bind parameter 'Date' to the target. Exception setting "Date": "Cannot convert null to type "System.DateTime"."
At line:9 char:24
+ $CheckDate1 = get-date ($user.'Date')
+                        ~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (:) [Get-Date], ParameterBindingException
    + FullyQualifiedErrorId : ParameterBindingFailed,Microsoft.PowerShell.Commands.GetDateCommand

Remove-ADGroupMember : Cannot validate argument on parameter 'Members'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At line:16 char:68
+ ... tity "Group Name" -Members $user.samaccountname -Confir ...
+                                              ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Remove-ADGroupMember], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.RemoveADGroupMember
```

答:
Your foreach loop is enumerating $users, which has a value of "C:\Path to CSV\File.csv".  This means there will be one iteration of the loop where $user has a value of "C:\Path to CSV\File.csv".  Since the [String] class does not have a Date property, this...

($user.'Date').AddDays(7)
```
<p>...is effectively this...</p>
<pre class="lang-powershell prettyprint-override"><code>($null).AddDays(7)
</code>```

...hence the error.  You are also not doing anything with the output of Import-Csv $users, so you need to collect it somewhere for processing; either store it in a variable...

$usersPath = "C:\Path to CSV\File.csv"

Import-Module ActiveDirectory
$users = Import-Csv $usersPath

foreach ($user in $users)
{
    # ...
```
<p>...or, even better, loop directly over the output to process records as they're read...</p>
<pre class="lang-powershell prettyprint-override"><code>$usersPath = "C:\Path to CSV\File.csv"

Import-Module ActiveDirectory

foreach ($user in Import-Csv $usersPath)
{
    # ...
</code>```

I renamed your initial $users variable to $usersPath for clarity; reusing a variable in that way can be confusing and unexpected.

Even after fixing the loop you still need to change your parentheses from this...

get-date ($user.'Date').AddDays(7)
```
<p>...to this...</p>
<pre class="lang-powershell prettyprint-override"><code>(get-date $user.'Date').AddDays(7)
</code>```

...to create a [DateTime] using the value of $user.'Date' and then call AddDays(7) on the result.  Note that you don't need to quote a property that doesn't contains spaces in the name, so you can simplify that to...

(get-date $user.Date).AddDays(7)
```
<p>Also, you are comparing a user's <code>Date</code> with <code>Date + 7d</code>, which will always be <code>$true</code>.  Instead, you want to test if today is beyond the 7-day membership limit...</p>
<pre class="lang-powershell prettyprint-override"><code>$today = (Get-Date).Date # Ignore the TimeOfDay portion so the expiration happens on a day boundary
$userAddedDate = Get-Date ($user.Date)
$maxGroupMembershipTime = New-TimeSpan -Day 7

if ($today - $userAddedDate -gt $maxGroupMembershipTime)
# Alternative: if ($userAddedDate + $maxGroupMembershipTime -lt $today)
{
    # ...
</code>```

Finally, you are conditionally exiting the loop, which means no further user records nor anything else in the script will be processed.  To skip that user you would replace exit with continue, or just let control fall through to the end of the foreach block...

$usersPath = "C:\Path to CSV\File.csv"
$today = (Get-Date).Date # Ignore the TimeOfDay portion so the expiration happens on a day boundary
$maxGroupMembershipTime = New-TimeSpan -Day 7

Import-Module ActiveDirectory

foreach ($user in Import-Csv $usersPath)
{
    $userAddedDate = Get-Date ($user.Date)

    if ($today - $userAddedDate -gt $maxGroupMembershipTime)
    # Alternative: if ($userAddedDate + $maxGroupMembershipTime -lt $today)
    {
        Remove-ADGroupMember -Identity "Group Name" -Members $user.samaccountname -Confirm:$false
    }
}
```

I moved the initialization of $today outside of the loop since there's really no need to set it on each iteration and to ensure every user gets the same date for "today" regardless of when the script executes.

Body:
I am trying to create a PowerShell script that will be executed via a task every day. The task will check if a user has been a member of an AD group longer than 7 days. If so, that user will be removed.
The data is imported from a CSV file in which we will insert the date the user was added to the group:

samaccountname,Date
user 1,20/01/2022
user2,06/02/2022

This is the code I wrote:

$users = "C:\Path to CSV\File.csv"

Import-Module ActiveDirectory
Import-Csv $users

foreach ($user in $Users)
{
    $CheckDate2 = get-date ($user.'Date').AddDays(7)
    $CheckDate1 = get-date ($user.'Date')

    if ($CheckDate1 -lt $CheckDate2){
        exit
    }
    else{
        Remove-ADGroupMember -Identity "Group Name" -Members $user.samaccountname -Confirm:$false
    }
}

This is the errors I am receiving:

You cannot call a method on a null-valued expression.
At line:8 char:1
+ $CheckDate2 = get-date ($user.'Date').AddDays(7)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Get-Date : Cannot bind parameter 'Date' to the target. Exception setting "Date": "Cannot convert null to type "System.DateTime"."
At line:9 char:24
+ $CheckDate1 = get-date ($user.'Date')
+                        ~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (:) [Get-Date], ParameterBindingException
    + FullyQualifiedErrorId : ParameterBindingFailed,Microsoft.PowerShell.Commands.GetDateCommand

Remove-ADGroupMember : Cannot validate argument on parameter 'Members'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At line:16 char:68
+ ... tity "Group Name" -Members $user.samaccountname -Confir ...
+                                              ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Remove-ADGroupMember], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.RemoveADGroupMember

Body:
Your foreach loop is enumerating $users, which has a value of "C:\Path to CSV\File.csv".  This means there will be one iteration of the loop where $user has a value of "C:\Path to CSV\File.csv".  Since the [String] class does not have a Date property, this...

($user.'Date').AddDays(7)

...is effectively this...

($null).AddDays(7)

...hence the error.  You are also not doing anything with the output of Import-Csv $users, so you need to collect it somewhere for processing; either store it in a variable...

$usersPath = "C:\Path to CSV\File.csv"

Import-Module ActiveDirectory
$users = Import-Csv $usersPath

foreach ($user in $users)
{
    # ...

...or, even better, loop directly over the output to process records as they're read...

$usersPath = "C:\Path to CSV\File.csv"

Import-Module ActiveDirectory

foreach ($user in Import-Csv $usersPath)
{
    # ...

I renamed your initial $users variable to $usersPath for clarity; reusing a variable in that way can be confusing and unexpected.

Even after fixing the loop you still need to change your parentheses from this...

get-date ($user.'Date').AddDays(7)

...to this...

(get-date $user.'Date').AddDays(7)

...to create a [DateTime] using the value of $user.'Date' and then call AddDays(7) on the result.  Note that you don't need to quote a property that doesn't contains spaces in the name, so you can simplify that to...

(get-date $user.Date).AddDays(7)

Also, you are comparing a user's Date with Date + 7d, which will always be $true.  Instead, you want to test if today is beyond the 7-day membership limit...

$today = (Get-Date).Date # Ignore the TimeOfDay portion so the expiration happens on a day boundary
$userAddedDate = Get-Date ($user.Date)
$maxGroupMembershipTime = New-TimeSpan -Day 7

if ($today - $userAddedDate -gt $maxGroupMembershipTime)
# Alternative: if ($userAddedDate + $maxGroupMembershipTime -lt $today)
{
    # ...

Finally, you are conditionally exiting the loop, which means no further user records nor anything else in the script will be processed.  To skip that user you would replace exit with continue, or just let control fall through to the end of the foreach block...

$usersPath = "C:\Path to CSV\File.csv"
$today = (Get-Date).Date # Ignore the TimeOfDay portion so the expiration happens on a day boundary
$maxGroupMembershipTime = New-TimeSpan -Day 7

Import-Module ActiveDirectory

foreach ($user in Import-Csv $usersPath)
{
    $userAddedDate = Get-Date ($user.Date)

    if ($today - $userAddedDate -gt $maxGroupMembershipTime)
    # Alternative: if ($userAddedDate + $maxGroupMembershipTime -lt $today)
    {
        Remove-ADGroupMember -Identity "Group Name" -Members $user.samaccountname -Confirm:$false
    }
}

I moved the initialization of $today outside of the loop since there's really no need to set it on each iteration and to ensure every user gets the same date for "today" regardless of when the script executes.


问:
Equivalent function to sscanf in Vlang
Title says it all; looking for an equivalent to sscanf in vlang.

Go (which Vlang is similar to), has fmt.sscanf; but I don't see anything similar in the Vlang docs.

The somewhat closest method I could find is find_between; but I'd have to call it successive times if I have numerous elements to pull out of a string.

答:
In V there is no need of this type of function because you can format your string with the following syntax '$var_q:$var_e'

This is a real code example of the v compiler

```<code>fn run_repl(workdir string, vrepl_prefix string) {
    if !is_stdin_a_pipe {
        println(version.full_v_version(false))
        println('Use Ctrl-C or ${term.highlight_command('exit')} to exit, or ${term.highlight_command('help')} to see other available commands')
    }
// .. other repl code
}
</code>```

Title: Equivalent function to sscanf in Vlang

Body:
In V there is no need of this type of function because you can format your string with the following syntax '$var_q:$var_e'

This is a real code example of the v compiler

fn run_repl(workdir string, vrepl_prefix string) {
    if !is_stdin_a_pipe {
        println(version.full_v_version(false))
        println('Use Ctrl-C or ${term.highlight_command('exit')} to exit, or ${term.highlight_command('help')} to see other available commands')
    }
// .. other repl code
}


问:
Node.JS problem redirecting to new api endpoint after calling function
I'm trying to create an endpoint that updates a file using a post request, then redirects back to the home page. But the redirect isn't working.

However, when I comment out 'await sendMsg()', the redirect works fine.

Could you help me spot and fix the problem?

Thanks in advance!

app.get('/add', async function(req, res){

    await sendMsg();
    res.redirect('/');

});

app.post('/update', async function(req, res){

    const {data} = req.body;

    async function writeData(data) {
        try {
            return fs.writeFileSync(__dirname + '/config/' + 'task.json', JSON.stringify(data), 'utf8');
        }
        catch (err) {
            console.log('Problem writing to file.')
        }
    }

    await writeData(data);

});

async function sendMsg(){

    var pURL = 'http://localhost:6500/update';
    ...
    ...
    await fetch(pURL, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({data:config})
    })
    .catch(err => console.log(err));

}

```

答:
Thanks everyone!

I forgot to put res.end() at the end of the 'update' post API.

Thanks for the help.

The working code:

app.get('/add', async function(req, res){

   try {
        await sendMsg();
    } catch(e) {
        console.log(e);
   }

   res.redirect('/');

});

app.post('/update', async function(req, res){

    const {data} = req.body;

    async function writeData(data) {
        try {
            return fs.writeFileSync(__dirname + '/config/' + 'task.json', JSON.stringify(data), 'utf8');
        }
        catch (err) {
            console.log('Problem writing to file.')
        }
    }

    await writeData(data);

    res.end();

});

async function sendMsg(){
   return new Promise((resolve, reject)=>{
     var pURL = 'http://localhost:6500/update';
     ...
     ...
     fetch(pURL, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({data:config})
     })
     .then(response => { // <---------- Little Change ----------
         resolve()
     })
     .catch(err => {
       console.log(err)
       reject()
      });

    })

}

```


问:
Anyone can help me to speed up this Google Sheet script?
I am using the following script to refresh my Google Finance watchlist. I am not a programmer so that's why I copied this from somewhere and use it as long as it does the trick. It certainly works for me but it's kinda slow, and I hope someone can help me to optimize this script to make it better.

My understanding is, this script basically scan the whole table (7 columns and over 60 rows) to find out the no. of rows and column. It first empty the cells then fill the cell with original formula (which is GoogleFinance function for stock quote, something like that) to force the update for the whole table. I actually just need to trigger update for a specific column but I don't know how to do it (yep, not a programmer..). I tried to change the row = x and col = x to another values and it would help to reduce the scope of the update size of the table, and it help me abit only.

In order to make it update more frequently, I actually copy and paste those two for loops set 5 more times and use Utilities.sleep(10000); in between to make the script run 6 rounds a minute. So I can bypass the minimum 1 minute interval in Google Sheet setting. But yes, I know it's cause the script run even slower...

I hope someone can help me to speed this script up, really appreciate anyone can help! Thanks you!!

```<code>
function forceRefreshSheetFormulas(sheetName) {
    var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = activeSpreadsheet.getSheetByName('*Table Name*');
    var range = sheet.getDataRange();
    var numCols = range.getNumColumns();
    var numRows = range.getNumRows();
    var rowOffset = range.getRow();
    var colOffset = range.getColumn();

    // Change formulas then change them back to refresh it
    var originalFormulas = range.getFormulas();

    //Loop through each column and each row in the sheet
    //`row` and `col` are relative to the range, not the sheet
    for (row = 0; row < numRows ; row++){
    for(col = 0; col < numCols; col++){
    if (originalFormulas[row][col] != "")
    range.getCell(row+rowOffset, col+colOffset).setFormula("");
    }
    };
    };
    SpreadsheetApp.flush();
    for (row = 0; row < numRows ; row++){
    for(col = 0; col < numCols; col++){
    if (originalFormulas[row][col] != "") {
    range.getCell(row+rowOffset, col+colOffset).setFormula(originalFormulas[row][col]);
    }
    };
    };
    SpreadsheetApp.flush();
</code>```

答:
Try

pls enable Sheets API at Advanced Google services.

```<code>function forceRefreshSheetFormulas(sheetName) {
  var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = activeSpreadsheet.getSheetByName('*Table Name*');
  var range = sheet.getDataRange();
  var numCols = range.getNumColumns();
  var numRows = range.getNumRows();
  var rowOffset = range.getRow();
  var colOffset = range.getColumn();

  // Change formulas then change them back to refresh it
  var originalFormulas = range.getFormulas();

  //Loop through each column and each row in the sheet
  //`row` and `col` are relative to the range, not the sheet
  var ranges = []
  var blank = []
  var original = []
  for (row = 0; row < numRows; row++) {
    for (col = 0; col < numCols; col++) {
      if (originalFormulas[row][col] != ""){
        ranges.push( `'*Table Name*'!${columnToLetter(col + colOffset)}${row + rowOffset}` )
        blank.push('')
        original.push(`${originalFormulas[row][col]}`)
      };
    }
  };
  updateGoogleSheet(ranges,blank)
  SpreadsheetApp.flush();
  updateGoogleSheet(ranges,original)
};
function updateGoogleSheet(ranges,values) {
  var spreadsheetId = SpreadsheetApp.getActiveSpreadsheet().getId()
  var data = ranges.map((e, i) => ({ range: e, values: [[values[i]]] }));
  Sheets.Spreadsheets.Values.batchUpdate({ data, valueInputOption: "USER_ENTERED" }, spreadsheetId);
}
function columnToLetter(column) {
  var temp, letter = '';
  while (column > 0) {
    temp = (column - 1) % 26;
    letter = String.fromCharCode(temp + 65) + letter;
    column = (column - temp - 1) / 26;
  }
  return letter;
}
</code>```

reference

batchupdate

Body:
I am using the following script to refresh my Google Finance watchlist. I am not a programmer so that's why I copied this from somewhere and use it as long as it does the trick. It certainly works for me but it's kinda slow, and I hope someone can help me to optimize this script to make it better.

My understanding is, this script basically scan the whole table (7 columns and over 60 rows) to find out the no. of rows and column. It first empty the cells then fill the cell with original formula (which is GoogleFinance function for stock quote, something like that) to force the update for the whole table. I actually just need to trigger update for a specific column but I don't know how to do it (yep, not a programmer..). I tried to change the row = x and col = x to another values and it would help to reduce the scope of the update size of the table, and it help me abit only.

In order to make it update more frequently, I actually copy and paste those two for loops set 5 more times and use Utilities.sleep(10000); in between to make the script run 6 rounds a minute. So I can bypass the minimum 1 minute interval in Google Sheet setting. But yes, I know it's cause the script run even slower...

I hope someone can help me to speed this script up, really appreciate anyone can help! Thanks you!!

function forceRefreshSheetFormulas(sheetName) {
    var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = activeSpreadsheet.getSheetByName('*Table Name*');
    var range = sheet.getDataRange();
    var numCols = range.getNumColumns();
    var numRows = range.getNumRows();
    var rowOffset = range.getRow();
    var colOffset = range.getColumn();

    // Change formulas then change them back to refresh it
    var originalFormulas = range.getFormulas();

    //Loop through each column and each row in the sheet
    //`row` and `col` are relative to the range, not the sheet
    for (row = 0; row < numRows ; row++){
    for(col = 0; col < numCols; col++){
    if (originalFormulas[row][col] != "")
    range.getCell(row+rowOffset, col+colOffset).setFormula("");
    }
    };
    };
    SpreadsheetApp.flush();
    for (row = 0; row < numRows ; row++){
    for(col = 0; col < numCols; col++){
    if (originalFormulas[row][col] != "") {
    range.getCell(row+rowOffset, col+colOffset).setFormula(originalFormulas[row][col]);
    }
    };
    };
    SpreadsheetApp.flush();

Body:
Try

pls enable Sheets API at Advanced Google services.

function forceRefreshSheetFormulas(sheetName) {
  var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = activeSpreadsheet.getSheetByName('*Table Name*');
  var range = sheet.getDataRange();
  var numCols = range.getNumColumns();
  var numRows = range.getNumRows();
  var rowOffset = range.getRow();
  var colOffset = range.getColumn();

  // Change formulas then change them back to refresh it
  var originalFormulas = range.getFormulas();

  //Loop through each column and each row in the sheet
  //`row` and `col` are relative to the range, not the sheet
  var ranges = []
  var blank = []
  var original = []
  for (row = 0; row < numRows; row++) {
    for (col = 0; col < numCols; col++) {
      if (originalFormulas[row][col] != ""){
        ranges.push( `'*Table Name*'!${columnToLetter(col + colOffset)}${row + rowOffset}` )
        blank.push('')
        original.push(`${originalFormulas[row][col]}`)
      };
    }
  };
  updateGoogleSheet(ranges,blank)
  SpreadsheetApp.flush();
  updateGoogleSheet(ranges,original)
};
function updateGoogleSheet(ranges,values) {
  var spreadsheetId = SpreadsheetApp.getActiveSpreadsheet().getId()
  var data = ranges.map((e, i) => ({ range: e, values: [[values[i]]] }));
  Sheets.Spreadsheets.Values.batchUpdate({ data, valueInputOption: "USER_ENTERED" }, spreadsheetId);
}
function columnToLetter(column) {
  var temp, letter = '';
  while (column > 0) {
    temp = (column - 1) % 26;
    letter = String.fromCharCode(temp + 65) + letter;
    column = (column - temp - 1) / 26;
  }
  return letter;
}

reference

batchupdate


问:
nunit tests not discovered in c# solution
The following is the configuration of my development setup (not that much all of this is required; but i thought i would give this information anyway)

Visual Studio 2012 Update 4

Nunit 2.6.3

Nunit Test Adapter 1.1

Windows 7 Ultimate 64 bit

The solution that I am working on has a number of unit tests written in c# using Nunit. I am logged in as the Administrator. For some reason I cannot view the tests in the test explorer.

Upon opening the solution the error message displayed by VS is
"Unexpected error detected. Check the output pane for details"

The output pane just mentions that there were 0 tests detected

I have tried everything from re-installing Nunit, repairing VS, to resetting the IDE and the windows layout. No success.

If i login as another user on my laptop, I am ABLE to view the tests in test explorer.

Given point no 4 above, can anyone help me to work my way backwards? Try to find out what the problem might be.

The only other painful option would be to reinstall VS. I dont want it to come to that.

Thanks in advance

答:
Just go to the search bar
type %temp%
Delete all the files in the Temp folder
Delete all from recycle bin
Clean project
Build project.</p>


问:
Javascript: Need a decent red black tree implementation
Where can I find one ready for use?  Or for that matter, a good collection of "standard" data structures, if you know of any?</p>

答: I wrote a red-black tree in javascript, available here: https://github.com/vadimg/js_bintrees or as bintrees in npm. Unlike the other implementations, it has unit tests.

ContentLicense: CC BY-SA 2.5


答:
onChanged parameter is required for the DropdownButton widget. it is called when the user selects an item.
try this one:

class dropDownMenu extends StatefulWidget {
  dropDownMenu({Key? key}) : super(key: key);

  @override
  State<dropDownMenu> createState() => _dropDownMenuState();
}

class _dropDownMenuState extends State<dropDownMenu> {
  String value = 'One';
  @override
  Widget build(BuildContext context) {
    return Center(
      child: DropdownButton<String>(
        value: value,
        onChanged: (String? newValue) {
          setState(() {
            value = newValue!;
          });
        },
        items: [
          DropdownMenuItem(
            child: Text('One'),
            value: 'One',
          ),
          DropdownMenuItem(
            child: Text('Two'),
            value: 'Two',
          ),
        ],
      ),
    );
  }
}

```

Title: The named parameter 'onChanged' is required, but there's no corresponding argument. Try adding the required argument


问:
Why i can't get a full path while using xpath?
For the following html code:

```<code> <div hidden>
  <svg>
   <symbol viewBox=“0 0 8 14” id=“icon-carousel-next”>
     <path d=“M1.005 14a1 1 0 01-.71-1.71l5.296-5.288L.296></path>
   </symbol>
  <symbol viewBox=“0 0 8 14” id=“icon-carousel-prev”>
    <path d=“M1.005 14a1 1 0 01-.71-1.71l5.296-5.288L.296></path>
  <symbol id=“icon-arrow-right-bold” viewBox=“1.2 2.1 22 21”>
    <path d=“M1.005 14a1 1 0 01-.71-1.71l5.296-5.288L.296></path>
 </svg>
</div>
</code>```

The following xpath doesn't return result:

```<code>//div/svg/symbol
</code>```

I've noticed that any manipulation related to symbol element doesn't work.
Is there a known issue with this element?

答:
svg, path etc. are special tag names.

Instead of

//div/svg/symbol
```
<p>try using</p>
<pre class="lang-xml prettyprint-override"><code>//div/*[name()='svg'/*[name()='symbol']
</code>```

or

//div/*[local-name()='svg'/*[local-name()='symbol']
```

Body:
For the following html code:

  <svg>
   <symbol viewBox=“0 0 8 14” id=“icon-carousel-next”>
     <path d=“M1.005 14a1 1 0 01-.71-1.71l5.296-5.288L.296></path>
   </symbol>
  <symbol viewBox=“0 0 8 14” id=“icon-carousel-prev”>
    <path d=“M1.005 14a1 1 0 01-.71-1.71l5.296-5.288L.296></path>
  <symbol id=“icon-arrow-right-bold” viewBox=“1.2 2.1 22 21”>
    <path d=“M1.005 14a1 1 0 01-.71-1.71l5.296-5.288L.296></path>
 </svg>

The following xpath doesn't return result:

//div/svg/symbol

I've noticed that any manipulation related to symbol element doesn't work.
Is there a known issue with this element?

Body:
svg, path etc. are special tag names.

Instead of

//div/svg/symbol

try using

//div/*[name()='svg'/*[name()='symbol']

or

//div/*[local-name()='svg'/*[local-name()='symbol']


问:
Iterate through Dictionary of DataFrames
I've got pretty stuck on the basic idea of DataFrames within dictionaries.

Could someone please explain to me how they would iterate through a dict and select specific columns in a DataFrame while still keeping in mind time complexity?

For that reason I created a reproducible example:

```<code>import numpy as np
import pandas as pd

data = np.random.randint(5, 30, size=(10,3))
df_APPL = pd.DataFrame(data, columns=['Volume', 'Open', 'Close'])
df_TSLA = pd.DataFrame(data, columns=['Volume', 'Open', 'Close'])
df_AMZN = pd.DataFrame(data, columns=['Volume', 'Open', 'Close'])

d = {'APPL': df_APPL,
     'TSLA': df_TSLA,
     'AMZN': df_AMZN}
</code>```

In this basic example, how would I select 'Open' in every DataFrame and sort the keys from max to min according to 'Open'?

Any other example would also be welcome. :)

答:
You can use sort_values() to sort dataframe based on a column values:

see more about sort_values() here

```<code>nd = {k:v.sort_values('Open', ascending=False) for k,v in d.items()}
</code>```

Body:
I've got pretty stuck on the basic idea of DataFrames within dictionaries.

Could someone please explain to me how they would iterate through a dict and select specific columns in a DataFrame while still keeping in mind time complexity?

For that reason I created a reproducible example:

import numpy as np
import pandas as pd

data = np.random.randint(5, 30, size=(10,3))
df_APPL = pd.DataFrame(data, columns=['Volume', 'Open', 'Close'])
df_TSLA = pd.DataFrame(data, columns=['Volume', 'Open', 'Close'])
df_AMZN = pd.DataFrame(data, columns=['Volume', 'Open', 'Close'])

d = {'APPL': df_APPL,
     'TSLA': df_TSLA,
     'AMZN': df_AMZN}

In this basic example, how would I select 'Open' in every DataFrame and sort the keys from max to min according to 'Open'?

Any other example would also be welcome. :)

Body:
You can use sort_values() to sort dataframe based on a column values:

see more about sort_values() here

nd = {k:v.sort_values('Open', ascending=False) for k,v in d.items()}


问:
Destructured contents of Redux state returns an empty array but there is data after I fetch data with axios
I am creating an e-commerce front-end that I have its Server posted in Heroku created with nodejs. I am trying to use Redux to implement every operation on the website. I tried to call all the list of products in the database using the redux method but when console.log the products after-action creators I get an empty array

My Store Code

```<code>import {createStore, combineReducers, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import {composeWithDevTools} from 'redux-devtools-extension';
import { productsListReducer} from './reducers/productsReducer';

const reducer = combineReducers({

     productList:productsListReducer,
});

const initialState = {};

const middleware = [thunk];

const store = createStore(
    reducer,
    initialState,
    composeWithDevTools(applyMiddleware(...middleware))
);

export default store;
</code>```

My Constants For Products

```<code>export const PRODUCTS_LIST_REQUEST = "PRODUCTS_LIST_REQUEST";
export const PRODUCTS_LIST_SUCCESS = "PRODUCTS_LIST_SUCCESS";
export const PRODUCTS_LIST_FAIL = "PRODUCTS_LIST_FAIL";
</code>```

My ProductsReducer Code

```<code>import {
  PRODUCTS_LIST_FAIL,
  PRODUCTS_LIST_REQUEST,
  PRODUCTS_LIST_SUCCESS,
} from "../constants/productConstants";

export const productsListReducer = (state = { products:[]}, action) => {

  switch (action.type) {
    case PRODUCTS_LIST_REQUEST:
      return {
        loading: true,
      };

    case PRODUCTS_LIST_SUCCESS:
      return {
        loading: false,
        products: action.payload,
      };

    case PRODUCTS_LIST_FAIL:
      return {
        loading: false,
        error: action.payload,
      };

    default:
      return state;
  }
};
</code>```

My Action Creator Code

```<code>import axios from "axios";
import {
  PRODUCTS_LIST_FAIL,
  PRODUCTS_LIST_REQUEST,
  PRODUCTS_LIST_SUCCESS,
} from "../constants/productConstants";

export const Products = () => async (dispatch) => {
  try {
    dispatch({
      type: PRODUCTS_LIST_REQUEST,
    });

    const headers = {
      "Content-Type":"application/json",
    };
    const url = `${process.env.REACT_APP_SERVER_URL}api/products`;

    const { data } = await axios.get(url, { headers });

    dispatch({
      type: PRODUCTS_LIST_SUCCESS,
      payload: data,
    });

  } catch (error) {
    const message =
      error.response && error.response.data.message
        ? error.response.data.message
        : error.message;

    dispatch({
      type: PRODUCTS_LIST_FAIL,
      payload: message,
    });
  }
};
</code>```

How I am Trying to get The Reducer data in-home Page

```<code>import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Products } from "../../actions/productsActions";
import SideBar from "../Home/SideBar";
import SingleProduct from "../Home/SingleProduct";

const Home = () => {

const dispatch = useDispatch();

const productList = useSelector((state) => state.productList);

const { products, error, loading } = productList

console.log("products", products)

useEffect(() => {
    dispatch(Products);
},[dispatch])

  return (
    <div className ='home'>
      <SideBar />
      <div className="productConatiner">
        {
            products.map((product) => {
              return <span>{product?.title}</span>
            })
        };
      </div>
    </div>
  );
};

export default Home;
</code>```

答:
The problem is that you're not actually dispatching an action.
You should write

```<code>useEffect(() => {
  dispatch(Products());
},[dispatch])
</code>```

instead of

```<code>useEffect(() => {
  dispatch(Products);
},[dispatch])
</code>```

Body:
I am creating an e-commerce front-end that I have its Server posted in Heroku created with nodejs. I am trying to use Redux to implement every operation on the website. I tried to call all the list of products in the database using the redux method but when console.log the products after-action creators I get an empty array

My Store Code

import {createStore, combineReducers, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import {composeWithDevTools} from 'redux-devtools-extension';
import { productsListReducer} from './reducers/productsReducer';

const reducer = combineReducers({

     productList:productsListReducer,
});

const initialState = {};

const middleware = [thunk];

const store = createStore(
    reducer,
    initialState,
    composeWithDevTools(applyMiddleware(...middleware))
);

export default store;

My Constants For Products

export const PRODUCTS_LIST_REQUEST = "PRODUCTS_LIST_REQUEST";
export const PRODUCTS_LIST_SUCCESS = "PRODUCTS_LIST_SUCCESS";
export const PRODUCTS_LIST_FAIL = "PRODUCTS_LIST_FAIL";

My ProductsReducer Code

import {
  PRODUCTS_LIST_FAIL,
  PRODUCTS_LIST_REQUEST,
  PRODUCTS_LIST_SUCCESS,
} from "../constants/productConstants";

export const productsListReducer = (state = { products:[]}, action) => {

  switch (action.type) {
    case PRODUCTS_LIST_REQUEST:
      return {
        loading: true,
      };

    case PRODUCTS_LIST_SUCCESS:
      return {
        loading: false,
        products: action.payload,
      };

    case PRODUCTS_LIST_FAIL:
      return {
        loading: false,
        error: action.payload,
      };

    default:
      return state;
  }
};

My Action Creator Code

import axios from "axios";
import {
  PRODUCTS_LIST_FAIL,
  PRODUCTS_LIST_REQUEST,
  PRODUCTS_LIST_SUCCESS,
} from "../constants/productConstants";

export const Products = () => async (dispatch) => {
  try {
    dispatch({
      type: PRODUCTS_LIST_REQUEST,
    });

    const headers = {
      "Content-Type":"application/json",
    };
    const url = `${process.env.REACT_APP_SERVER_URL}api/products`;

    const { data } = await axios.get(url, { headers });

    dispatch({
      type: PRODUCTS_LIST_SUCCESS,
      payload: data,
    });

  } catch (error) {
    const message =
      error.response && error.response.data.message
        ? error.response.data.message
        : error.message;

    dispatch({
      type: PRODUCTS_LIST_FAIL,
      payload: message,
    });
  }
};

How I am Trying to get The Reducer data in-home Page

import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Products } from "../../actions/productsActions";
import SideBar from "../Home/SideBar";
import SingleProduct from "../Home/SingleProduct";

const Home = () => {

const dispatch = useDispatch();

const productList = useSelector((state) => state.productList);

const { products, error, loading } = productList

console.log("products", products)

useEffect(() => {
    dispatch(Products);
},[dispatch])

  return (

      <SideBar />

        {
            products.map((product) => {
              return {product?.title}
            })
        };

  );
};

export default Home;

Body:
The problem is that you're not actually dispatching an action.
You should write

useEffect(() => {
  dispatch(Products());
},[dispatch])

instead of

useEffect(() => {
  dispatch(Products);
},[dispatch])


问:
Open a buffer on a new Tab on Vim
I'm creating a Vim plugin that I need intercept when a new buffer is loaded.

The basic idea consists in when I open a new buffer this new buffer must be screened on another tab, and the previous tab must keep the previous buffer loaded.

Eg.: I have a buffer with the foo.txt, when I try to open bar.txt with :e bar.txt It will open in a new tab and the previous tab must stay with the foo.txt. I know that :tabe bar.txt does the job, but to my plugin I need the "tabe behavior" even when it's not used to open a file.

Does anyone have any idea how to do this with Vimscript?

The reason behind this: https://github.com/vim-ctrlspace/vim-ctrlspace/issues/177.

答:
Try using this</p>
```<code>au BufNewFile,BufRead * nested
  \ if &buftype != "help" |
  \   tab sball |
  \ endif
</code>```

Title: Open a buffer on a new Tab on Vim

Body:
Try using this

au BufNewFile,BufRead * nested
  \ if &buftype != "help" |
  \   tab sball |
  \ endif


问:
jinja to json in Salt
I have a jinja template in salt that every time apply.state is ran, salt thinks it has changed when it hasn't.

The issue is that a reconfigure command executes when the file "changes", and this reconfigure would change the file from a single lined JSON to a lined JSON. For example:

salt creates the file like:

```<code>{ "key1": { "sub-key1": "sub-value1", "sub-key2": "sub-value2"}, "key2": "value2" }
</code>```

but when the reconfigure command executes, it changes the file to:

```<code>{
  "key1": {
    "sub-key1": "sub-value1",
    "sub-key2": "sub-value2"
  },
  "key2": "value2"
}
</code>```

Is there a way to have salt create the file as a formatted JSON to begin with?

This is what I have:

```<code>{{ gb_server.secrets_file }}:
  file.managed:
    - source: {{ gb_server.secrets_tmpl }}
    - user: {{ gb_server.secure_user }}
    - group: {{ gb_server.secure_user }}
    - mode: 600
    - template: jinja
</code>```

the template is as follow:

```<code>{%- import_yaml 'gb-server/defaults.yaml' as defaultmap -%}
{%- set  secrets = gb_server_config['secrets'] -%}
{{ secrets|tojson|replace('\\\\n','\\n') }}
</code>```

The values are in pillar in yaml format.

Ideally, the resulted JSON would have its key sorted alphabetically, that way the content of the resulted file wouldn't "change" and the reconfigure command wouldn't run every single time.

Is there a way to make this happen with salt?

Thank you.

答:
It looks like file.serialize will do what you want here

{{ gb_server.secrets_file }}:
  file.serialize:
    - user: {{ gb_server.secure_user }}
    - group: {{ gb_server.secure_user }}
    - mode: 600
    - data: {{ gb_server.secrets }}
    - serializer: json
    - serializer_opts:
      - indent: 2
      - sort_keys: true
```

Title: jinja to json in Salt

Body:
I have a jinja template in salt that every time apply.state is ran, salt thinks it has changed when it hasn't.

The issue is that a reconfigure command executes when the file "changes", and this reconfigure would change the file from a single lined JSON to a lined JSON. For example:

salt creates the file like:

{ "key1": { "sub-key1": "sub-value1", "sub-key2": "sub-value2"}, "key2": "value2" }

but when the reconfigure command executes, it changes the file to:

{
  "key1": {
    "sub-key1": "sub-value1",
    "sub-key2": "sub-value2"
  },
  "key2": "value2"
}

Is there a way to have salt create the file as a formatted JSON to begin with?

This is what I have:

{{ gb_server.secrets_file }}:
  file.managed:
    - source: {{ gb_server.secrets_tmpl }}
    - user: {{ gb_server.secure_user }}
    - group: {{ gb_server.secure_user }}
    - mode: 600
    - template: jinja

the template is as follow:

{%- import_yaml 'gb-server/defaults.yaml' as defaultmap -%}
{%- set  secrets = gb_server_config['secrets'] -%}
{{ secrets|tojson|replace('\\\\n','\\n') }}

The values are in pillar in yaml format.

Ideally, the resulted JSON would have its key sorted alphabetically, that way the content of the resulted file wouldn't "change" and the reconfigure command wouldn't run every single time.

Is there a way to make this happen with salt?

Thank you.


问:
Password Checker improvement
1.Problem...Its my password validation.COnsoleApp
But i have bug....if first space is null program working(...but i want return false if first char is white

2.Many Condition using
I wanna few using condition..i wanna practise good way

```<code>        {
            bool symb = false;
            bool letdig = false;
            char currentchar;
            char currentchar2;
            if (!(pass.Length >= 8 && pass.Length <= 25))
            {
                return true;
            }
            string symbols = "!@#$%^&*()_-+=[{]};:<>|./?.";
            char[] simbolchar = symbols.ToCharArray();

            for (int j = 0; j < pass.Length; j++)
            {
                currentchar = pass[j];
                foreach (var simb in simbolchar)
                {
                    if (simb == currentchar)
                    {
                        symb = true;
                    }
                }
                if (symb)
                {
                    for (int i = 0; i < pass.Length; i++)
                    {
                        currentchar2 = pass[i];
                        if (char.IsUpper(currentchar2) && (char.IsLetterOrDigit(currentchar2)))
                        {
                            letdig = true;
                        }
                    }
                }
                if (letdig)
                {
                    Console.WriteLine("WELCOME");
                    return true;
                }
            }
            return letdig;

        }
</code>```

答:
Solve the first bug can be by adding a condition to check if the string is null or empty before any check after that

```<code>        public static bool passwordCheck(string pass)
        {
        bool symb = false;
        bool letdig = false;
        char currentchar;
        char currentchar2;
        //Solve the first bug
        if (string.IsNullOrEmpty(pass))
        {
            return false;
        }
        else
        {
            if (!(pass.Length >= 8 && pass.Length <= 25))
            {
                return true;
            }
            string symbols = "!@#$%^&*()_-+=[{]};:<>|./?.";
            char[] simbolchar = symbols.ToCharArray();

            for (int j = 0; j < pass.Length; j++)
            {
                currentchar = pass[j];
                foreach (var simb in simbolchar)
                {
                    if (simb == currentchar)
                    {
                        symb = true;
                    }
                }
                if (symb)
                {
                    for (int i = 0; i < pass.Length; i++)
                    {
                        currentchar2 = pass[i];
                        if (char.IsUpper(currentchar2) && (char.IsLetterOrDigit(currentchar2)))
                        {
                            letdig = true;
                        }
                    }
                }
                if (letdig)
                {
                    Console.WriteLine("WELCOME");
                    return true;
                }
            }
            return letdig;
        }
    }
</code>```

As for code optimization, you can reading about clear code for your case

Title: Password Checker improvement

Body:
1.Problem...Its my password validation.COnsoleApp
But i have bug....if first space is null program working(...but i want return false if first char is white

2.Many Condition using
I wanna few using condition..i wanna practise good way

        {
            bool symb = false;
            bool letdig = false;
            char currentchar;
            char currentchar2;
            if (!(pass.Length >= 8 && pass.Length <= 25))
            {
                return true;
            }
            string symbols = "!@#$%^&*()_-+=[{]};:<>|./?.";
            char[] simbolchar = symbols.ToCharArray();

            for (int j = 0; j < pass.Length; j++)
            {
                currentchar = pass[j];
                foreach (var simb in simbolchar)
                {
                    if (simb == currentchar)
                    {
                        symb = true;
                    }
                }
                if (symb)
                {
                    for (int i = 0; i < pass.Length; i++)
                    {
                        currentchar2 = pass[i];
                        if (char.IsUpper(currentchar2) && (char.IsLetterOrDigit(currentchar2)))
                        {
                            letdig = true;
                        }
                    }
                }
                if (letdig)
                {
                    Console.WriteLine("WELCOME");
                    return true;
                }
            }
            return letdig;

        }

Body:
Solve the first bug can be by adding a condition to check if the string is null or empty before any check after that

        public static bool passwordCheck(string pass)
        {
        bool symb = false;
        bool letdig = false;
        char currentchar;
        char currentchar2;
        //Solve the first bug
        if (string.IsNullOrEmpty(pass))
        {
            return false;
        }
        else
        {
            if (!(pass.Length >= 8 && pass.Length <= 25))
            {
                return true;
            }
            string symbols = "!@#$%^&*()_-+=[{]};:<>|./?.";
            char[] simbolchar = symbols.ToCharArray();

            for (int j = 0; j < pass.Length; j++)
            {
                currentchar = pass[j];
                foreach (var simb in simbolchar)
                {
                    if (simb == currentchar)
                    {
                        symb = true;
                    }
                }
                if (symb)
                {
                    for (int i = 0; i < pass.Length; i++)
                    {
                        currentchar2 = pass[i];
                        if (char.IsUpper(currentchar2) && (char.IsLetterOrDigit(currentchar2)))
                        {
                            letdig = true;
                        }
                    }
                }
                if (letdig)
                {
                    Console.WriteLine("WELCOME");
                    return true;
                }
            }
            return letdig;
        }
    }

As for code optimization, you can reading about clear code for your case


问:
sqs does not give me MessageAttributes when receiving message
I have written the following API to recieve message :

```<code>app.get('/receive', function(req, res) {
    var params = {
        QueueUrl: queueUrl,
        VisibilityTimeout: 600
    };

    sqs.receiveMessage(params, function(err, data) {
        if (err) {
            res.send(err);
        } else {
            console.log('data is ' + JSON.stringify(data));
            res.send(data);
        }
    });
});
</code>```

The response that I get is as follows:

```<code>{
    "ResponseMetadata": {
        "RequestId": "id"
    },
    "Messages": [
        {
            "MessageId": "id",
            "ReceiptHandle": "handle",
            "MD5OfBody": "body",
            "Body": "body"
        }
    ]
}
</code>```

.

the send message format for the API is as shown below:

```<code> let params = {
                       MessageBody: object,
                       QueueUrl: process.env.queueUrl,
                        MessageAttributes:{
                           "Title":{
                               DataType:'String',
                               StringValue:'Item Id Array',
                           }
                        },
                       DelaySeconds: 0
                   }
                   sqs.send(params, (err, data) => {
                       console.log('------------the send message data is------------',err,data);
                   });
</code>```

答:
To receive all SQS attributes -> .attributeNames(QueueAttributeName.ALL)

To Receive message metadata attributes -> .messageAttributeNames("yourMessageAttributeName")

Java/Kotlin

```<code> val request = ReceiveMessageRequest.builder()
                .queueUrl(url)
                .messageAttributeNames("yourMessageAttributeName")
                .attributeNames(QueueAttributeName.ALL)
                .build()
        val messages = client.receiveMessage(receiveMessageRequest).messages()
</code>```

Body:
I have written the following API to recieve message :

app.get('/receive', function(req, res) {
    var params = {
        QueueUrl: queueUrl,
        VisibilityTimeout: 600
    };

    sqs.receiveMessage(params, function(err, data) {
        if (err) {
            res.send(err);
        } else {
            console.log('data is ' + JSON.stringify(data));
            res.send(data);
        }
    });
});

The response that I get is as follows:

{
    "ResponseMetadata": {
        "RequestId": "id"
    },
    "Messages": [
        {
            "MessageId": "id",
            "ReceiptHandle": "handle",
            "MD5OfBody": "body",
            "Body": "body"
        }
    ]
}

.

the send message format for the API is as shown below:

 let params = {
                       MessageBody: object,
                       QueueUrl: process.env.queueUrl,
                        MessageAttributes:{
                           "Title":{
                               DataType:'String',
                               StringValue:'Item Id Array',
                           }
                        },
                       DelaySeconds: 0
                   }
                   sqs.send(params, (err, data) => {
                       console.log('------------the send message data is------------',err,data);
                   });

Body:
To receive all SQS attributes -> .attributeNames(QueueAttributeName.ALL)

To Receive message metadata attributes -> .messageAttributeNames("yourMessageAttributeName")

Java/Kotlin

 val request = ReceiveMessageRequest.builder()
                .queueUrl(url)
                .messageAttributeNames("yourMessageAttributeName")
                .attributeNames(QueueAttributeName.ALL)
                .build()
        val messages = client.receiveMessage(receiveMessageRequest).messages()